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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.918   ! raeburn     4: # $Id: lonnet.pm,v 1.917 2007/10/01 23:53:44 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.891     albertel  217:     my ($lonid) = @_;
                    218:     my $hostname = &hostname($lonid);
                    219:     if ($lonid) {
                    220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    221: 	if ($hostname && -e $peerfile) {
                    222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    224: 					     Type    => SOCK_STREAM,
                    225: 					     Timeout => 10);
                    226: 	    if ($client) {
                    227: 		print $client ("reset_retries\n");
                    228: 		my $answer=<$client>;
                    229: 		#reset just this one.
                    230: 	    }
                    231: 	}
                    232: 	return;
                    233:     }
                    234: 
1.836     www       235:     &logthis("Trying to reconnect lonc");
1.1       albertel  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  237:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  238: 	my $loncpid=<$fh>;
                    239:         chomp($loncpid);
                    240:         if (kill 0 => $loncpid) {
                    241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    242:             kill USR1 => $loncpid;
                    243:             sleep 1;
1.836     www       244:          } else {
1.12      www       245: 	    &logthis(
1.672     albertel  246:                "<font color=\"blue\">WARNING:".
1.12      www       247:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  248:         }
                    249:     } else {
1.836     www       250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  251:     }
                    252: }
                    253: 
                    254: # ------------------------------------------------------ Critical communication
1.12      www       255: 
1.1       albertel  256: sub critical {
                    257:     my ($cmd,$server)=@_;
1.838     albertel  258:     unless (&hostname($server)) {
1.672     albertel  259:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       260:                " Critical message to unknown server ($server)</font>");
                    261:         return 'no_such_host';
                    262:     }
1.1       albertel  263:     my $answer=reply($cmd,$server);
                    264:     if ($answer eq 'con_lost') {
                    265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  266: 	my $answer=reply($cmd,$server);
1.1       albertel  267:         if ($answer eq 'con_lost') {
                    268:             my $now=time;
                    269:             my $middlename=$cmd;
1.5       www       270:             $middlename=substr($middlename,0,16);
1.1       albertel  271:             $middlename=~s/\W//g;
                    272:             my $dfilename=
1.305     www       273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    274:             $dumpcount++;
1.1       albertel  275:             {
1.448     albertel  276: 		my $dfh;
                    277: 		if (open($dfh,">$dfilename")) {
                    278: 		    print $dfh "$cmd\n"; 
                    279: 		    close($dfh);
                    280: 		}
1.1       albertel  281:             }
                    282:             sleep 2;
                    283:             my $wcmd='';
                    284:             {
1.448     albertel  285: 		my $dfh;
                    286: 		if (open($dfh,"<$dfilename")) {
                    287: 		    $wcmd=<$dfh>; 
                    288: 		    close($dfh);
                    289: 		}
1.1       albertel  290:             }
                    291:             chomp($wcmd);
1.7       www       292:             if ($wcmd eq $cmd) {
1.672     albertel  293: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       294:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  295:                 &logperm("D:$server:$cmd");
                    296: 	        return 'con_delayed';
                    297:             } else {
1.672     albertel  298:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       299:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  300:                 &logperm("F:$server:$cmd");
                    301:                 return 'con_failed';
                    302:             }
                    303:         }
                    304:     }
                    305:     return $answer;
1.405     albertel  306: }
                    307: 
1.755     albertel  308: # ------------------------------------------- check if return value is an error
                    309: 
                    310: sub error {
                    311:     my ($result) = @_;
1.756     albertel  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  313: 	if ($2 == 2) { return undef; }
                    314: 	return $1;
                    315:     }
                    316:     return undef;
                    317: }
                    318: 
1.783     albertel  319: sub convert_and_load_session_env {
                    320:     my ($lonidsdir,$handle)=@_;
                    321:     my @profile;
                    322:     {
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
                   1386:     #&make_room($id,$value,$debug);
1.599     albertel 1387:     return $value;
                   1388: }
                   1389: 
                   1390: sub make_room {
                   1391:     my ($id,$value,$debug)=@_;
                   1392:     $remembered{$id}=$value;
                   1393:     if ($to_remember<0) { return; }
                   1394:     $accessed{$id}=[&gettimeofday()];
                   1395:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1396:     my $to_kick;
                   1397:     my $max_time=0;
                   1398:     foreach my $other (keys(%accessed)) {
                   1399: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1400: 	    $to_kick=$other;
                   1401: 	    $max_time=&tv_interval($accessed{$other});
                   1402: 	}
                   1403:     }
                   1404:     delete($remembered{$to_kick});
                   1405:     delete($accessed{$to_kick});
                   1406:     $kicks++;
                   1407:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1408:     return;
                   1409: }
                   1410: 
1.599     albertel 1411: sub purge_remembered {
1.604     albertel 1412:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1413:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1414:     undef(%remembered);
                   1415:     undef(%accessed);
1.428     albertel 1416: }
1.70      www      1417: # ------------------------------------- Read an entry from a user's environment
                   1418: 
                   1419: sub userenvironment {
                   1420:     my ($udom,$unam,@what)=@_;
                   1421:     my %returnhash=();
                   1422:     my @answer=split(/\&/,
                   1423:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1424:                       &homeserver($unam,$udom)));
                   1425:     my $i;
                   1426:     for ($i=0;$i<=$#what;$i++) {
                   1427: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1428:     }
                   1429:     return %returnhash;
1.1       albertel 1430: }
                   1431: 
1.617     albertel 1432: # ---------------------------------------------------------- Get a studentphoto
                   1433: sub studentphoto {
                   1434:     my ($udom,$unam,$ext) = @_;
                   1435:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1436:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1437:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1438:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1439:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1440:             } else {
                   1441:                 my ($result,$perm_reqd)=
1.707     albertel 1442: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1443:                 if ($result eq 'ok') {
                   1444:                     if (!($perm_reqd eq 'yes')) {
                   1445:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1446:                     }
                   1447:                 }
                   1448:             }
                   1449:         }
                   1450:     } else {
                   1451:         my ($result,$perm_reqd) = 
1.707     albertel 1452: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1453:         if ($result eq 'ok') {
                   1454:             if (!($perm_reqd eq 'yes')) {
                   1455:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1456:             }
                   1457:         }
                   1458:     }
                   1459:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1460: }
                   1461: 
                   1462: sub retrievestudentphoto {
                   1463:     my ($udom,$unam,$ext,$type) = @_;
                   1464:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1465:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1466:     if ($ret eq 'ok') {
                   1467:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1468:         if ($type eq 'thumbnail') {
                   1469:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1470:         }
                   1471:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1472:         return $tokenurl;
                   1473:     } else {
                   1474:         if ($type eq 'thumbnail') {
                   1475:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1476:         } else { 
                   1477:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1478:         }
1.617     albertel 1479:     }
                   1480: }
                   1481: 
1.263     www      1482: # -------------------------------------------------------------------- New chat
                   1483: 
                   1484: sub chatsend {
1.724     raeburn  1485:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1486:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1487:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1488:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1489:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1490: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1491: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1492: }
                   1493: 
                   1494: # ------------------------------------------ Find current version of a resource
                   1495: 
                   1496: sub getversion {
                   1497:     my $fname=&clutter(shift);
                   1498:     unless ($fname=~/^\/res\//) { return -1; }
                   1499:     return &currentversion(&filelocation('',$fname));
                   1500: }
                   1501: 
                   1502: sub currentversion {
                   1503:     my $fname=shift;
1.599     albertel 1504:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1505:     if (defined($cached)) { return $result; }
1.292     www      1506:     my $author=$fname;
                   1507:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1508:     my ($udom,$uname)=split(/\//,$author);
                   1509:     my $home=homeserver($uname,$udom);
                   1510:     if ($home eq 'no_host') { 
                   1511:         return -1; 
                   1512:     }
                   1513:     my $answer=reply("currentversion:$fname",$home);
                   1514:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1515: 	return -1;
                   1516:     }
1.599     albertel 1517:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1518: }
                   1519: 
1.1       albertel 1520: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1521: 
1.1       albertel 1522: sub subscribe {
                   1523:     my $fname=shift;
1.761     raeburn  1524:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1525:     $fname=~s/[\n\r]//g;
1.1       albertel 1526:     my $author=$fname;
                   1527:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1528:     my ($udom,$uname)=split(/\//,$author);
                   1529:     my $home=homeserver($uname,$udom);
1.335     albertel 1530:     if ($home eq 'no_host') {
                   1531:         return 'not_found';
1.1       albertel 1532:     }
                   1533:     my $answer=reply("sub:$fname",$home);
1.64      www      1534:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1535: 	$answer.=' by '.$home;
                   1536:     }
1.1       albertel 1537:     return $answer;
                   1538: }
                   1539:     
1.8       www      1540: # -------------------------------------------------------------- Replicate file
                   1541: 
                   1542: sub repcopy {
                   1543:     my $filename=shift;
1.23      www      1544:     $filename=~s/\/+/\//g;
1.607     raeburn  1545:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1546:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1547:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1548: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1549: 	return &repcopy_userfile($filename);
                   1550:     }
1.532     albertel 1551:     $filename=~s/[\n\r]//g;
1.8       www      1552:     my $transname="$filename.in.transfer";
1.828     www      1553: # FIXME: this should flock
1.607     raeburn  1554:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1555:     my $remoteurl=subscribe($filename);
1.64      www      1556:     if ($remoteurl =~ /^con_lost by/) {
                   1557: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1558:            return 'unavailable';
1.8       www      1559:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1560: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1561: 	   return 'not_found';
1.64      www      1562:     } elsif ($remoteurl =~ /^rejected by/) {
                   1563: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1564:            return 'forbidden';
1.20      www      1565:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1566:            return 'ok';
1.8       www      1567:     } else {
1.290     www      1568:         my $author=$filename;
                   1569:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1570:         my ($udom,$uname)=split(/\//,$author);
                   1571:         my $home=homeserver($uname,$udom);
                   1572:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1573:            my @parts=split(/\//,$filename);
                   1574:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1575:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1576:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1577: 	       return 'bad_request';
1.8       www      1578:            }
                   1579:            my $count;
                   1580:            for ($count=5;$count<$#parts;$count++) {
                   1581:                $path.="/$parts[$count]";
                   1582:                if ((-e $path)!=1) {
                   1583: 		   mkdir($path,0777);
                   1584:                }
                   1585:            }
                   1586:            my $ua=new LWP::UserAgent;
                   1587:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1588:            my $response=$ua->request($request,$transname);
                   1589:            if ($response->is_error()) {
                   1590: 	       unlink($transname);
                   1591:                my $message=$response->status_line;
1.672     albertel 1592:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1593:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1594:                return 'unavailable';
1.8       www      1595:            } else {
1.16      www      1596: 	       if ($remoteurl!~/\.meta$/) {
                   1597:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1598:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1599:                   if ($mresponse->is_error()) {
                   1600: 		      unlink($filename.'.meta');
                   1601:                       &logthis(
1.672     albertel 1602:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1603:                   }
                   1604: 	       }
1.8       www      1605:                rename($transname,$filename);
1.607     raeburn  1606:                return 'ok';
1.8       www      1607:            }
1.290     www      1608:        }
1.8       www      1609:     }
1.330     www      1610: }
                   1611: 
                   1612: # ------------------------------------------------ Get server side include body
                   1613: sub ssi_body {
1.381     albertel 1614:     my ($filelink,%form)=@_;
1.606     matthew  1615:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1616:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1617:     }
1.330     www      1618:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1619:                                      &ssi($filelink,%form));
1.778     albertel 1620:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1621:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1622:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1623:     return $output;
1.8       www      1624: }
                   1625: 
1.15      www      1626: # --------------------------------------------------------- Server Side Include
                   1627: 
1.782     albertel 1628: sub absolute_url {
                   1629:     my ($host_name) = @_;
                   1630:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1631:     if ($host_name eq '') {
                   1632: 	$host_name = $ENV{'SERVER_NAME'};
                   1633:     }
                   1634:     return $protocol.$host_name;
                   1635: }
                   1636: 
1.15      www      1637: sub ssi {
                   1638: 
1.23      www      1639:     my ($fn,%form)=@_;
1.15      www      1640: 
                   1641:     my $ua=new LWP::UserAgent;
1.23      www      1642:     
                   1643:     my $request;
1.711     albertel 1644: 
                   1645:     $form{'no_update_last_known'}=1;
1.895     albertel 1646:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1647:     if (%form) {
1.782     albertel 1648:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1649:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1650:     } else {
1.782     albertel 1651:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1652:     }
                   1653: 
1.15      www      1654:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1655:     my $response=$ua->request($request);
                   1656: 
1.324     www      1657:     return $response->content;
                   1658: }
                   1659: 
                   1660: sub externalssi {
                   1661:     my ($url)=@_;
                   1662:     my $ua=new LWP::UserAgent;
                   1663:     my $request=new HTTP::Request('GET',$url);
                   1664:     my $response=$ua->request($request);
1.15      www      1665:     return $response->content;
                   1666: }
1.254     www      1667: 
1.492     albertel 1668: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1669: 
                   1670: sub allowuploaded {
                   1671:     my ($srcurl,$url)=@_;
                   1672:     $url=&clutter(&declutter($url));
                   1673:     my $dir=$url;
                   1674:     $dir=~s/\/[^\/]+$//;
                   1675:     my %httpref=();
                   1676:     my $httpurl=&hreflocation('',$url);
                   1677:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1678:     &Apache::lonnet::appenv(%httpref);
1.254     www      1679: }
1.477     raeburn  1680: 
1.478     albertel 1681: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1682: # input: action, courseID, current domain, intended
1.637     raeburn  1683: #        path to file, source of file, instruction to parse file for objects,
                   1684: #        ref to hash for embedded objects,
                   1685: #        ref to hash for codebase of java objects.
                   1686: #
1.485     raeburn  1687: # output: url to file (if action was uploaddoc), 
                   1688: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1689: #
1.478     albertel 1690: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1691: # course.
1.477     raeburn  1692: #
1.478     albertel 1693: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1694: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1695: #          course's home server.
1.477     raeburn  1696: #
1.478     albertel 1697: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1698: #          be copied from $source (current location) to 
                   1699: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1700: #         and will then be copied to
                   1701: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1702: #         course's home server.
1.485     raeburn  1703: #
1.481     raeburn  1704: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1705: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1706: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1707: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1708: #         in course's home server.
1.637     raeburn  1709: #
1.477     raeburn  1710: 
                   1711: sub process_coursefile {
1.638     albertel 1712:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1713:     my $fetchresult;
1.638     albertel 1714:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1715:     if ($action eq 'propagate') {
1.638     albertel 1716:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1717: 			     $home);
1.481     raeburn  1718:     } else {
1.477     raeburn  1719:         my $fpath = '';
                   1720:         my $fname = $file;
1.478     albertel 1721:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1722:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1723:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1724:         if ($action eq 'copy') {
                   1725:             if ($source eq '') {
                   1726:                 $fetchresult = 'no source file';
                   1727:                 return $fetchresult;
                   1728:             } else {
                   1729:                 my $destination = $filepath.'/'.$fname;
                   1730:                 rename($source,$destination);
                   1731:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1732:                                  $home);
1.481     raeburn  1733:             }
                   1734:         } elsif ($action eq 'uploaddoc') {
                   1735:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1736:             print $fh $env{'form.'.$source};
1.481     raeburn  1737:             close($fh);
1.637     raeburn  1738:             if ($parser eq 'parse') {
                   1739:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1740:                 unless ($parse_result eq 'ok') {
                   1741:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1742:                 }
                   1743:             }
1.477     raeburn  1744:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1745:                                  $home);
1.481     raeburn  1746:             if ($fetchresult eq 'ok') {
                   1747:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1748:             } else {
                   1749:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1750:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1751:                 return '/adm/notfound.html';
                   1752:             }
1.477     raeburn  1753:         }
                   1754:     }
1.485     raeburn  1755:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1756:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1757:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1758:     }
                   1759:     return $fetchresult;
                   1760: }
                   1761: 
1.637     raeburn  1762: sub build_filepath {
                   1763:     my ($fpath) = @_;
                   1764:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1765:     unless ($fpath eq '') {
                   1766:         my @parts=split('/',$fpath);
                   1767:         foreach my $part (@parts) {
                   1768:             $filepath.= '/'.$part;
                   1769:             if ((-e $filepath)!=1) {
                   1770:                 mkdir($filepath,0777);
                   1771:             }
                   1772:         }
                   1773:     }
                   1774:     return $filepath;
                   1775: }
                   1776: 
                   1777: sub store_edited_file {
1.638     albertel 1778:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1779:     my $file = $primary_url;
                   1780:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1781:     my $fpath = '';
                   1782:     my $fname = $file;
                   1783:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1784:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1785:     my $filepath = &build_filepath($fpath);
                   1786:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1787:     print $fh $content;
                   1788:     close($fh);
1.638     albertel 1789:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1790:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1791: 			  $home);
1.637     raeburn  1792:     if ($$fetchresult eq 'ok') {
                   1793:         return '/uploaded/'.$fpath.'/'.$fname;
                   1794:     } else {
1.638     albertel 1795:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1796: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1797:         return '/adm/notfound.html';
                   1798:     }
                   1799: }
                   1800: 
1.531     albertel 1801: sub clean_filename {
1.831     albertel 1802:     my ($fname,$args)=@_;
1.315     www      1803: # Replace Windows backslashes by forward slashes
1.257     www      1804:     $fname=~s/\\/\//g;
1.831     albertel 1805:     if (!$args->{'keep_path'}) {
                   1806:         # Get rid of everything but the actual filename
                   1807: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1808:     }
1.315     www      1809: # Replace spaces by underscores
                   1810:     $fname=~s/\s+/\_/g;
                   1811: # Replace all other weird characters by nothing
1.831     albertel 1812:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1813: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1814: # numbers
                   1815:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1816:     return $fname;
                   1817: }
                   1818: 
1.608     albertel 1819: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1820: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1821: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1822: #        $coursedoc - if true up to the current course
                   1823: #                     if false
                   1824: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1825: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1826: #        $allfiles - reference to hash for embedded objects
                   1827: #        $codebase - reference to hash for codebase of java objects
                   1828: #        $desuname - username for permanent storage of uploaded file
                   1829: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1830: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1831: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1832: # 
1.686     albertel 1833: # output: url of file in userspace, or error: <message> 
                   1834: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1835: 
                   1836: 
1.531     albertel 1837: sub userfileupload {
1.860     raeburn  1838:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1839:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1840:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1841:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1842:     $fname=&clean_filename($fname);
1.315     www      1843: # See if there is anything left
1.257     www      1844:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1845:     chop($env{'form.'.$formname});
1.523     raeburn  1846:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1847:         my $now = time;
                   1848:         my $filepath = 'tmp/helprequests/'.$now;
                   1849:         my @parts=split(/\//,$filepath);
                   1850:         my $fullpath = $perlvar{'lonDaemons'};
                   1851:         for (my $i=0;$i<@parts;$i++) {
                   1852:             $fullpath .= '/'.$parts[$i];
                   1853:             if ((-e $fullpath)!=1) {
                   1854:                 mkdir($fullpath,0777);
                   1855:             }
                   1856:         }
                   1857:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1858:         print $fh $env{'form.'.$formname};
1.523     raeburn  1859:         close($fh);
1.741     raeburn  1860:         return $fullpath.'/'.$fname;
                   1861:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1862:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1863:                        '_'.$env{'user.domain'}.'/pending';
                   1864:         my @parts=split(/\//,$filepath);
                   1865:         my $fullpath = $perlvar{'lonDaemons'};
                   1866:         for (my $i=0;$i<@parts;$i++) {
                   1867:             $fullpath .= '/'.$parts[$i];
                   1868:             if ((-e $fullpath)!=1) {
                   1869:                 mkdir($fullpath,0777);
                   1870:             }
                   1871:         }
                   1872:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1873:         print $fh $env{'form.'.$formname};
                   1874:         close($fh);
                   1875:         return $fullpath.'/'.$fname;
1.523     raeburn  1876:     }
1.719     banghart 1877:     
1.258     www      1878: # Create the directory if not present
1.493     albertel 1879:     $fname="$subdir/$fname";
1.259     www      1880:     if ($coursedoc) {
1.638     albertel 1881: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1882: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1883:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1884:             return &finishuserfileupload($docuname,$docudom,
                   1885: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1886: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1887:         } else {
1.620     albertel 1888:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1889:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1890: 				       $fname,$formname,$parser,
                   1891: 				       $allfiles,$codebase);
1.481     raeburn  1892:         }
1.719     banghart 1893:     } elsif (defined($destuname)) {
                   1894:         my $docuname=$destuname;
                   1895:         my $docudom=$destudom;
1.860     raeburn  1896: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1897: 				     $parser,$allfiles,$codebase,
                   1898:                                      $thumbwidth,$thumbheight);
1.719     banghart 1899:         
1.259     www      1900:     } else {
1.638     albertel 1901:         my $docuname=$env{'user.name'};
                   1902:         my $docudom=$env{'user.domain'};
1.714     raeburn  1903:         if (exists($env{'form.group'})) {
                   1904:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1905:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1906:         }
1.860     raeburn  1907: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1908: 				     $parser,$allfiles,$codebase,
                   1909:                                      $thumbwidth,$thumbheight);
1.259     www      1910:     }
1.271     www      1911: }
                   1912: 
                   1913: sub finishuserfileupload {
1.860     raeburn  1914:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1915:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1916:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1917:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1918:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1919:     $file=$fname;
                   1920:     if ($fname=~m|/|) {
                   1921:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1922: 	$path.=$fnamepath.'/';
                   1923:     }
1.259     www      1924:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1925:     my $count;
                   1926:     for ($count=4;$count<=$#parts;$count++) {
                   1927:         $filepath.="/$parts[$count]";
                   1928:         if ((-e $filepath)!=1) {
                   1929: 	    mkdir($filepath,0777);
                   1930:         }
                   1931:     }
                   1932: # Save the file
                   1933:     {
1.701     albertel 1934: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1935: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1936: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1937: 	    return '/adm/notfound.html';
                   1938: 	}
                   1939: 	if (!print FH ($env{'form.'.$formname})) {
                   1940: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1941: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1942: 	    return '/adm/notfound.html';
                   1943: 	}
1.570     albertel 1944: 	close(FH);
1.258     www      1945:     }
1.637     raeburn  1946:     if ($parser eq 'parse') {
1.638     albertel 1947:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1948: 						   $codebase);
1.637     raeburn  1949:         unless ($parse_result eq 'ok') {
1.638     albertel 1950:             &logthis('Failed to parse '.$filepath.$file.
                   1951: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1952:         }
                   1953:     }
1.860     raeburn  1954:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1955:         my $input = $filepath.'/'.$file;
                   1956:         my $output = $filepath.'/'.'tn-'.$file;
                   1957:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1958:         system("convert -sample $thumbsize $input $output");
                   1959:         if (-e $filepath.'/'.'tn-'.$file) {
                   1960:             $fetchthumb  = 1; 
                   1961:         }
                   1962:     }
1.858     raeburn  1963:  
1.259     www      1964: # Notify homeserver to grep it
                   1965: #
1.638     albertel 1966:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1967:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1968:     if ($fetchresult eq 'ok') {
1.860     raeburn  1969:         if ($fetchthumb) {
                   1970:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1971:             if ($thumbresult ne 'ok') {
                   1972:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1973:                          $docuhome.': '.$thumbresult);
                   1974:             }
                   1975:         }
1.259     www      1976: #
1.258     www      1977: # Return the URL to it
1.494     albertel 1978:         return '/uploaded/'.$path.$file;
1.263     www      1979:     } else {
1.494     albertel 1980:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1981: 		 ': '.$fetchresult);
1.263     www      1982:         return '/adm/notfound.html';
1.858     raeburn  1983:     }
1.493     albertel 1984: }
                   1985: 
1.637     raeburn  1986: sub extract_embedded_items {
1.648     raeburn  1987:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1988:     my @state = ();
                   1989:     my %javafiles = (
                   1990:                       codebase => '',
                   1991:                       code => '',
                   1992:                       archive => ''
                   1993:                     );
                   1994:     my %mediafiles = (
                   1995:                       src => '',
                   1996:                       movie => '',
                   1997:                      );
1.648     raeburn  1998:     my $p;
                   1999:     if ($content) {
                   2000:         $p = HTML::LCParser->new($content);
                   2001:     } else {
                   2002:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2003:     }
1.641     albertel 2004:     while (my $t=$p->get_token()) {
1.640     albertel 2005: 	if ($t->[0] eq 'S') {
                   2006: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2007: 	    push(@state, $tagname);
1.648     raeburn  2008:             if (lc($tagname) eq 'allow') {
                   2009:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2010:             }
1.640     albertel 2011: 	    if (lc($tagname) eq 'img') {
                   2012: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2013: 	    }
1.886     albertel 2014: 	    if (lc($tagname) eq 'a') {
                   2015: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2016: 	    }
1.645     raeburn  2017:             if (lc($tagname) eq 'script') {
                   2018:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2019:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2020:                 } else {
                   2021:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2022:                 }
                   2023:             }
                   2024:             if (lc($tagname) eq 'link') {
                   2025:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2026:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2027:                 }
                   2028:             }
1.640     albertel 2029: 	    if (lc($tagname) eq 'object' ||
                   2030: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2031: 		foreach my $item (keys(%javafiles)) {
                   2032: 		    $javafiles{$item} = '';
                   2033: 		}
                   2034: 	    }
                   2035: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2036: 		my $name = lc($attr->{'name'});
                   2037: 		foreach my $item (keys(%javafiles)) {
                   2038: 		    if ($name eq $item) {
                   2039: 			$javafiles{$item} = $attr->{'value'};
                   2040: 			last;
                   2041: 		    }
                   2042: 		}
                   2043: 		foreach my $item (keys(%mediafiles)) {
                   2044: 		    if ($name eq $item) {
                   2045: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2046: 			last;
                   2047: 		    }
                   2048: 		}
                   2049: 	    }
                   2050: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2051: 		foreach my $item (keys(%javafiles)) {
                   2052: 		    if ($attr->{$item}) {
                   2053: 			$javafiles{$item} = $attr->{$item};
                   2054: 			last;
                   2055: 		    }
                   2056: 		}
                   2057: 		foreach my $item (keys(%mediafiles)) {
                   2058: 		    if ($attr->{$item}) {
                   2059: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2060: 			last;
                   2061: 		    }
                   2062: 		}
                   2063: 	    }
                   2064: 	} elsif ($t->[0] eq 'E') {
                   2065: 	    my ($tagname) = ($t->[1]);
                   2066: 	    if ($javafiles{'codebase'} ne '') {
                   2067: 		$javafiles{'codebase'} .= '/';
                   2068: 	    }  
                   2069: 	    if (lc($tagname) eq 'applet' ||
                   2070: 		lc($tagname) eq 'object' ||
                   2071: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2072: 		) {
                   2073: 		foreach my $item (keys(%javafiles)) {
                   2074: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2075: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2076: 			&add_filetype($allfiles,$file,$item);
                   2077: 		    }
                   2078: 		}
                   2079: 	    } 
                   2080: 	    pop @state;
                   2081: 	}
                   2082:     }
1.637     raeburn  2083:     return 'ok';
                   2084: }
                   2085: 
1.639     albertel 2086: sub add_filetype {
                   2087:     my ($allfiles,$file,$type)=@_;
                   2088:     if (exists($allfiles->{$file})) {
                   2089: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2090: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2091: 	}
                   2092:     } else {
                   2093: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2094:     }
                   2095: }
                   2096: 
1.493     albertel 2097: sub removeuploadedurl {
                   2098:     my ($url)=@_;
                   2099:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2100:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2101: }
                   2102: 
                   2103: sub removeuserfile {
                   2104:     my ($docuname,$docudom,$fname)=@_;
                   2105:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2106:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2107:     if ($result eq 'ok') {
                   2108:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2109:             my $metafile = $fname.'.meta';
                   2110:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2111: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2112:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2113:             my $sqlresult = 
1.823     albertel 2114:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2115:                                         'portfolio_metadata',$group,
                   2116:                                         'delete');
1.798     raeburn  2117:         }
                   2118:     }
                   2119:     return $result;
1.257     www      2120: }
1.15      www      2121: 
1.530     albertel 2122: sub mkdiruserfile {
                   2123:     my ($docuname,$docudom,$dir)=@_;
                   2124:     my $home=&homeserver($docuname,$docudom);
                   2125:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2126: }
                   2127: 
1.531     albertel 2128: sub renameuserfile {
                   2129:     my ($docuname,$docudom,$old,$new)=@_;
                   2130:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2131:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2132:                         &escape("$old").':'.&escape("$new"),$home);
                   2133:     if ($result eq 'ok') {
                   2134:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2135:             my $oldmeta = $old.'.meta';
                   2136:             my $newmeta = $new.'.meta';
                   2137:             my $metaresult = 
                   2138:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2139: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2140:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2141:             my $sqlresult = 
1.823     albertel 2142:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2143:                                         'portfolio_metadata',$group,
                   2144:                                         'delete');
1.798     raeburn  2145:         }
                   2146:     }
                   2147:     return $result;
1.531     albertel 2148: }
                   2149: 
1.14      www      2150: # ------------------------------------------------------------------------- Log
                   2151: 
                   2152: sub log {
                   2153:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2154:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2155: }
                   2156: 
                   2157: # ------------------------------------------------------------------ Course Log
1.352     www      2158: #
                   2159: # This routine flushes several buffers of non-mission-critical nature
                   2160: #
1.157     www      2161: 
                   2162: sub flushcourselogs {
1.352     www      2163:     &logthis('Flushing log buffers');
                   2164: #
                   2165: # course logs
                   2166: # This is a log of all transactions in a course, which can be used
                   2167: # for data mining purposes
                   2168: #
                   2169: # It also collects the courseid database, which lists last transaction
                   2170: # times and course titles for all courseids
                   2171: #
                   2172:     my %courseidbuffer=();
1.800     albertel 2173:     foreach my $crsid (keys %courselogs) {
1.352     www      2174:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2175: 		          &escape($courselogs{$crsid}),
                   2176: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2177: 	    delete $courselogs{$crsid};
                   2178:         } else {
                   2179:             &logthis('Failed to flush log buffer for '.$crsid);
                   2180:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2181:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2182:                         " exceeded maximum size, deleting.</font>");
                   2183:                delete $courselogs{$crsid};
                   2184:             }
1.352     www      2185:         }
1.918   ! raeburn  2186:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = (
        !          2187:             'description' => &escape($coursedescrbuf{$crsid}),
        !          2188:             'instcode'    => &escape($courseinstcodebuf{$crsid}),
        !          2189:             'type'        => &escape($coursetypebuf{$crsid}),
        !          2190:             'owner'       => &escape($courseownerbuf{$crsid}),
        !          2191:         );
1.191     harris41 2192:     }
1.352     www      2193: #
                   2194: # Write course id database (reverse lookup) to homeserver of courses 
                   2195: # Is used in pickcourse
                   2196: #
1.840     albertel 2197:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918   ! raeburn  2198:         my $response = &courseidput(&host_domain($crs_home),
        !          2199:                                     $courseidbuffer{$crs_home},$crs_home);
1.352     www      2200:     }
                   2201: #
                   2202: # File accesses
                   2203: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2204: #
1.449     matthew  2205:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2206:         if ($entry =~ /___count$/) {
                   2207:             my ($dom,$name);
1.807     albertel 2208:             ($dom,$name,undef)=
1.811     albertel 2209: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2210:             if (! defined($dom) || $dom eq '' || 
                   2211:                 ! defined($name) || $name eq '') {
1.620     albertel 2212:                 my $cid = $env{'request.course.id'};
                   2213:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2214:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2215:             }
1.450     matthew  2216:             my $value = $accesshash{$entry};
                   2217:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2218:             my %temphash=($url => $value);
1.449     matthew  2219:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2220:             if ($result eq 'ok') {
                   2221:                 delete $accesshash{$entry};
                   2222:             } elsif ($result eq 'unknown_cmd') {
                   2223:                 # Target server has old code running on it.
1.450     matthew  2224:                 my %temphash=($entry => $value);
1.449     matthew  2225:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2226:                     delete $accesshash{$entry};
                   2227:                 }
                   2228:             }
                   2229:         } else {
1.811     albertel 2230:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2231:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2232:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2233:                 delete $accesshash{$entry};
                   2234:             }
1.185     www      2235:         }
1.191     harris41 2236:     }
1.352     www      2237: #
                   2238: # Roles
                   2239: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2240: #
1.800     albertel 2241:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2242:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2243: 	    split(/\:/,$entry);
                   2244:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2245:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2246:                 $rudom,$runame) eq 'ok') {
                   2247: 	    delete $userrolehash{$entry};
                   2248:         }
                   2249:     }
1.662     raeburn  2250: #
                   2251: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2252: #
                   2253:     my %domrolebuffer = ();
                   2254:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2255:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2256:         if ($domrolebuffer{$rudom}) {
                   2257:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2258:                       '='.&escape($domainrolehash{$entry});
                   2259:         } else {
                   2260:             $domrolebuffer{$rudom}.=&escape($entry).
                   2261:                       '='.&escape($domainrolehash{$entry});
                   2262:         }
                   2263:         delete $domainrolehash{$entry};
                   2264:     }
                   2265:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2266: 	my %servers = &get_servers($dom,'library');
                   2267: 	foreach my $tryserver (keys(%servers)) {
                   2268: 	    unless (&reply('domroleput:'.$dom.':'.
                   2269: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2270: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2271: 	    }
1.662     raeburn  2272:         }
                   2273:     }
1.186     www      2274:     $dumpcount++;
1.157     www      2275: }
                   2276: 
                   2277: sub courselog {
                   2278:     my $what=shift;
1.158     www      2279:     $what=time.':'.$what;
1.620     albertel 2280:     unless ($env{'request.course.id'}) { return ''; }
                   2281:     $coursedombuf{$env{'request.course.id'}}=
                   2282:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2283:     $coursenumbuf{$env{'request.course.id'}}=
                   2284:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2285:     $coursehombuf{$env{'request.course.id'}}=
                   2286:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2287:     $coursedescrbuf{$env{'request.course.id'}}=
                   2288:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2289:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2290:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2291:     $courseownerbuf{$env{'request.course.id'}}=
                   2292:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2293:     $coursetypebuf{$env{'request.course.id'}}=
                   2294:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2295:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2296: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2297:     } else {
1.620     albertel 2298: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2299:     }
1.620     albertel 2300:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2301: 	&flushcourselogs();
                   2302:     }
1.158     www      2303: }
                   2304: 
                   2305: sub courseacclog {
                   2306:     my $fnsymb=shift;
1.620     albertel 2307:     unless ($env{'request.course.id'}) { return ''; }
                   2308:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2309:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2310:         $what.=':POST';
1.583     matthew  2311:         # FIXME: Probably ought to escape things....
1.800     albertel 2312: 	foreach my $key (keys(%env)) {
                   2313:             if ($key=~/^form\.(.*)/) {
                   2314: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2315:             }
1.191     harris41 2316:         }
1.583     matthew  2317:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2318:         # FIXME: We should not be depending on a form parameter that someone
                   2319:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2320:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2321:             $what.= ':POST';
                   2322:             # FIXME: Probably ought to escape things....
                   2323:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2324:                                  'crsdiscuss') {
1.620     albertel 2325:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2326:             }
                   2327:         }
1.158     www      2328:     }
                   2329:     &courselog($what);
1.149     www      2330: }
                   2331: 
1.185     www      2332: sub countacc {
                   2333:     my $url=&declutter(shift);
1.458     matthew  2334:     return if (! defined($url) || $url eq '');
1.620     albertel 2335:     unless ($env{'request.course.id'}) { return ''; }
                   2336:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2337:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2338:     $accesshash{$key}++;
1.185     www      2339: }
1.349     www      2340: 
1.361     www      2341: sub linklog {
                   2342:     my ($from,$to)=@_;
                   2343:     $from=&declutter($from);
                   2344:     $to=&declutter($to);
                   2345:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2346:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2347: }
                   2348:   
1.349     www      2349: sub userrolelog {
                   2350:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2351:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2352:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2353:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2354:         ($trole=~/^ta/)) {
1.350     www      2355:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2356:        $userrolehash
                   2357:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2358:                     =$tend.':'.$tstart;
1.662     raeburn  2359:     }
1.898     albertel 2360:     if (($env{'request.role'} =~ /dc\./) &&
                   2361: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2362: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2363: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2364:        $userrolehash
                   2365:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2366:                     =$tend.':'.$tstart;
                   2367:     }
1.662     raeburn  2368:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2369:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2370:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2371:         ($trole=~/^sc/)) {
                   2372:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2373:        $domainrolehash
                   2374:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2375:                     = $tend.':'.$tstart;
                   2376:     }
1.351     www      2377: }
                   2378: 
                   2379: sub get_course_adv_roles {
                   2380:     my $cid=shift;
1.620     albertel 2381:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2382:     my %coursehash=&coursedescription($cid);
1.470     www      2383:     my %nothide=();
1.800     albertel 2384:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2385: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2386:     }
1.351     www      2387:     my %returnhash=();
                   2388:     my %dumphash=
                   2389:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2390:     my $now=time;
1.800     albertel 2391:     foreach my $entry (keys %dumphash) {
                   2392: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2393:         if (($tstart) && ($tstart<0)) { next; }
                   2394:         if (($tend) && ($tend<$now)) { next; }
                   2395:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2396:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2397: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2398: 	if ((&privileged($username,$domain)) && 
                   2399: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2400: 	if ($role eq 'cr') { next; }
1.351     www      2401:         my $key=&plaintext($role);
                   2402:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2403:         if ($returnhash{$key}) {
                   2404: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2405:         } else {
                   2406:             $returnhash{$key}=$username.':'.$domain;
                   2407:         }
1.400     www      2408:      }
                   2409:     return %returnhash;
                   2410: }
                   2411: 
                   2412: sub get_my_roles {
1.858     raeburn  2413:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2414:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2415:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2416:     my %dumphash;
                   2417:     if ($context eq 'userroles') { 
                   2418:         %dumphash = &dump('roles',$udom,$uname);
                   2419:     } else {
                   2420:         %dumphash=
1.400     www      2421:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2422:     }
1.400     www      2423:     my %returnhash=();
                   2424:     my $now=time;
1.800     albertel 2425:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2426:         my ($role,$tend,$tstart);
                   2427:         if ($context eq 'userroles') {
                   2428: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2429:         } else {
                   2430:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2431:         }
1.400     www      2432:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2433:         my $status = 'active';
                   2434:         if (($tend) && ($tend<$now)) {
                   2435:             $status = 'previous';
                   2436:         } 
                   2437:         if (($tstart) && ($now<$tstart)) {
                   2438:             $status = 'future';
                   2439:         }
                   2440:         if (ref($types) eq 'ARRAY') {
                   2441:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2442:                 next;
                   2443:             } 
                   2444:         } else {
                   2445:             if ($status ne 'active') {
                   2446:                 next;
                   2447:             }
                   2448:         }
1.867     raeburn  2449:         my ($rolecode,$username,$domain,$section,$area);
                   2450:         if ($context eq 'userroles') {
                   2451:             ($area,$rolecode) = split(/_/,$entry);
                   2452:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2453:         } else {
                   2454:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2455:         }
1.832     raeburn  2456:         if (ref($roledoms) eq 'ARRAY') {
                   2457:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2458:                 next;
                   2459:             }
                   2460:         }
                   2461:         if (ref($roles) eq 'ARRAY') {
                   2462:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2463:                 next;
                   2464:             }
1.867     raeburn  2465:         }
1.400     www      2466: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2467:     }
1.373     www      2468:     return %returnhash;
1.399     www      2469: }
                   2470: 
                   2471: # ----------------------------------------------------- Frontpage Announcements
                   2472: #
                   2473: #
                   2474: 
                   2475: sub postannounce {
                   2476:     my ($server,$text)=@_;
1.844     albertel 2477:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2478:     unless ($text=~/\w/) { $text=''; }
                   2479:     return &reply('setannounce:'.&escape($text),$server);
                   2480: }
                   2481: 
                   2482: sub getannounce {
1.448     albertel 2483: 
                   2484:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2485: 	my $announcement='';
1.800     albertel 2486: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2487: 	close($fh);
1.399     www      2488: 	if ($announcement=~/\w/) { 
                   2489: 	    return 
                   2490:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2491:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2492: 	} else {
                   2493: 	    return '';
                   2494: 	}
                   2495:     } else {
                   2496: 	return '';
                   2497:     }
1.351     www      2498: }
1.353     www      2499: 
                   2500: # ---------------------------------------------------------- Course ID routines
                   2501: # Deal with domain's nohist_courseid.db files
                   2502: #
                   2503: 
                   2504: sub courseidput {
1.918   ! raeburn  2505:     my ($domain,$storehash,$coursehome)=@_;
        !          2506:     my $items='';
        !          2507:     my $now = time;
        !          2508:     foreach my $item (keys(%$storehash)) {
        !          2509:         $storehash->{$item}{'lasttime'} = $now;
        !          2510:         $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
        !          2511:     }
        !          2512:     $items=~s/\&$//;
        !          2513:     my $outcome = &reply('courseidputhash:'.$domain.':'.$items,$coursehome);
        !          2514:     if ($outcome eq 'unknown_cmd') {
        !          2515:         my $what;
        !          2516:         foreach my $cid (keys(%$storehash)) {
        !          2517:             $what .= &escape($cid).'=';
        !          2518:             foreach my $item ('description','instcode','owner','type') {
        !          2519:                 $what .= $storehash->{$item}.':';
        !          2520:             }
        !          2521:             $what =~ s/\:$/&/;
        !          2522:         }
        !          2523:         $what =~ s/\&$//;  
        !          2524:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
        !          2525:     } else {
        !          2526:         return $outcome;
        !          2527:     }
1.353     www      2528: }
                   2529: 
                   2530: sub courseiddump {
1.791     raeburn  2531:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.918   ! raeburn  2532:     my $as_hash = 1;
        !          2533:     my %returnhash;
        !          2534:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2535:     my %libserv = &all_library();
                   2536:     foreach my $tryserver (keys(%libserv)) {
                   2537:         if ( (  $hostidflag == 1 
                   2538: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2539: 	     || (!defined($hostidflag)) ) {
                   2540: 
1.918   ! raeburn  2541: 	    if (($domfilter eq '') ||
        !          2542: 		(&host_domain($tryserver) eq $domfilter)) {
        !          2543:                 my $rep = 
        !          2544:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
        !          2545:                          $sincefilter.':'.&escape($descfilter).':'.
        !          2546:                          &escape($instcodefilter).':'.&escape($ownerfilter).
        !          2547:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
        !          2548:                          ':'.&escape($regexp_ok).':'.$as_hash,$tryserver); 
        !          2549:                 my @pairs=split(/\&/,$rep);
        !          2550:                 foreach my $item (@pairs) {
        !          2551:                     my ($key,$value)=split(/\=/,$item,2);
        !          2552:                     $key = &unescape($key);
        !          2553:                     next if ($key =~ /^error: 2 /);
        !          2554:                     my $result = &thaw_unescape($value);
        !          2555:                     if (ref($result) eq 'HASH') {
        !          2556:                         $returnhash{$key}=$result;
        !          2557:                     } else {
        !          2558:                         my @responses = split(/:/,$result);
        !          2559:                         my @items = ('description','instcode','owner','type');
        !          2560:                         for (my $i=0; $i<@responses; $i++) {
        !          2561:                             $returnhash{$key}{$items[$i]} = $responses[$i];
        !          2562:                         }
        !          2563:                     } 
1.353     www      2564:                 }
                   2565:             }
                   2566:         }
                   2567:     }
                   2568:     return %returnhash;
                   2569: }
                   2570: 
1.658     raeburn  2571: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2572: 
                   2573: sub dcmailput {
1.685     raeburn  2574:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2575:     my $status = &Apache::lonnet::critical(
1.740     www      2576:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2577:        &escape($message),$server);
1.662     raeburn  2578:     return $status;
                   2579: }
                   2580: 
1.658     raeburn  2581: sub dcmaildump {
                   2582:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2583:     my %returnhash=();
1.846     albertel 2584: 
                   2585:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2586:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2587:                                                          &escape($enddate).':';
                   2588: 	my @esc_senders=map { &escape($_)} @$senders;
                   2589: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2590: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2591:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2592:             if (($key) && ($value)) {
                   2593:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2594:             }
                   2595:         }
                   2596:     }
                   2597:     return %returnhash;
                   2598: }
1.662     raeburn  2599: # ---------------------------------------------------------- Domain roles
                   2600: 
                   2601: sub get_domain_roles {
                   2602:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2603:     if (undef($startdate) || $startdate eq '') {
                   2604:         $startdate = '.';
                   2605:     }
                   2606:     if (undef($enddate) || $enddate eq '') {
                   2607:         $enddate = '.';
                   2608:     }
                   2609:     my $rolelist = join(':',@{$roles});
                   2610:     my %personnel = ();
1.841     albertel 2611: 
                   2612:     my %servers = &get_servers($dom,'library');
                   2613:     foreach my $tryserver (keys(%servers)) {
                   2614: 	%{$personnel{$tryserver}}=();
                   2615: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2616: 					    &escape($startdate).':'.
                   2617: 					    &escape($enddate).':'.
                   2618: 					    &escape($rolelist), $tryserver))) {
                   2619: 	    my ($key,$value) = split(/\=/,$line,2);
                   2620: 	    if (($key) && ($value)) {
                   2621: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2622: 	    }
                   2623: 	}
1.662     raeburn  2624:     }
                   2625:     return %personnel;
                   2626: }
1.658     raeburn  2627: 
1.149     www      2628: # ----------------------------------------------------------- Check out an item
                   2629: 
1.504     albertel 2630: sub get_first_access {
                   2631:     my ($type,$argsymb)=@_;
1.790     albertel 2632:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2633:     if ($argsymb) { $symb=$argsymb; }
                   2634:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2635:     if ($type eq 'map') {
                   2636: 	$res=&symbread($map);
                   2637:     } else {
                   2638: 	$res=$symb;
                   2639:     }
                   2640:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2641:     return $times{"$courseid\0$res"};
1.504     albertel 2642: }
                   2643: 
                   2644: sub set_first_access {
                   2645:     my ($type)=@_;
1.790     albertel 2646:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2647:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2648:     if ($type eq 'map') {
                   2649: 	$res=&symbread($map);
                   2650:     } else {
                   2651: 	$res=$symb;
                   2652:     }
                   2653:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2654:     if (!$firstaccess) {
1.588     albertel 2655: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2656:     }
                   2657:     return 'already_set';
1.504     albertel 2658: }
                   2659: 
1.149     www      2660: sub checkout {
                   2661:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2662:     my $now=time;
                   2663:     my $lonhost=$perlvar{'lonHostID'};
                   2664:     my $infostr=&escape(
1.234     www      2665:                  'CHECKOUTTOKEN&'.
1.149     www      2666:                  $tuname.'&'.
                   2667:                  $tudom.'&'.
                   2668:                  $tcrsid.'&'.
                   2669:                  $symb.'&'.
                   2670: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2671:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2672:     if ($token=~/^error\:/) { 
1.672     albertel 2673:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2674:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2675:                  "</font>");
                   2676:         return ''; 
                   2677:     }
                   2678: 
1.149     www      2679:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2680:     $token=~tr/a-z/A-Z/;
                   2681: 
1.153     www      2682:     my %infohash=('resource.0.outtoken' => $token,
                   2683:                   'resource.0.checkouttime' => $now,
                   2684:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2685: 
                   2686:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2687:        return '';
1.151     www      2688:     } else {
1.672     albertel 2689:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2690:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2691:                  "</font>");
1.149     www      2692:     }    
                   2693: 
                   2694:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2695:                          &escape('Checkout '.$infostr.' - '.
                   2696:                                                  $token)) ne 'ok') {
                   2697: 	return '';
1.151     www      2698:     } else {
1.672     albertel 2699:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2700:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2701:                  "</font>");
1.149     www      2702:     }
1.151     www      2703:     return $token;
1.149     www      2704: }
                   2705: 
                   2706: # ------------------------------------------------------------ Check in an item
                   2707: 
                   2708: sub checkin {
                   2709:     my $token=shift;
1.150     www      2710:     my $now=time;
                   2711:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2712:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2713:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2714:     $dtoken=~s/\W/\_/g;
1.234     www      2715:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2716:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2717: 
1.154     www      2718:     unless (($tuname) && ($tudom)) {
                   2719:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2720:         return '';
                   2721:     }
                   2722:     
                   2723:     unless (&allowed('mgr',$tcrsid)) {
                   2724:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2725:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2726:         return '';
                   2727:     }
                   2728: 
1.153     www      2729:     my %infohash=('resource.0.intoken' => $token,
                   2730:                   'resource.0.checkintime' => $now,
                   2731:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2732: 
                   2733:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2734:        return '';
                   2735:     }    
                   2736: 
                   2737:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2738:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2739: 	return '';
                   2740:     }
                   2741: 
                   2742:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2743: }
                   2744: 
                   2745: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2746: 
                   2747: sub expirespread {
                   2748:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2749:     my $cid=$env{'request.course.id'}; 
1.110     www      2750:     if ($cid) {
                   2751:        my $now=time;
                   2752:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2753:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2754:                             $env{'course.'.$cid.'.num'}.
1.110     www      2755: 	        	    ':nohist_expirationdates:'.
                   2756:                             &escape($key).'='.$now,
1.620     albertel 2757:                             $env{'course.'.$cid.'.home'})
1.110     www      2758:     }
                   2759:     return 'ok';
1.14      www      2760: }
                   2761: 
1.109     www      2762: # ----------------------------------------------------- Devalidate Spreadsheets
                   2763: 
                   2764: sub devalidate {
1.325     www      2765:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2766:     my $cid=$env{'request.course.id'}; 
1.109     www      2767:     if ($cid) {
1.391     matthew  2768:         # delete the stored spreadsheets for
                   2769:         # - the student level sheet of this user in course's homespace
                   2770:         # - the assessment level sheet for this resource 
                   2771:         #   for this user in user's homespace
1.553     albertel 2772: 	# - current conditional state info
1.325     www      2773: 	my $key=$uname.':'.$udom.':';
1.109     www      2774:         my $status=
1.299     matthew  2775: 	    &del('nohist_calculatedsheets',
1.391     matthew  2776: 		 [$key.'studentcalc:'],
1.620     albertel 2777: 		 $env{'course.'.$cid.'.domain'},
                   2778: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2779: 		.' '.
                   2780: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2781: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2782:         unless ($status eq 'ok ok') {
                   2783:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2784:                     $uname.' at '.$udom.' for '.
1.109     www      2785: 		    $symb.': '.$status);
1.133     albertel 2786:         }
1.553     albertel 2787: 	&delenv('user.state.'.$cid);
1.109     www      2788:     }
                   2789: }
                   2790: 
1.265     albertel 2791: sub get_scalar {
                   2792:     my ($string,$end) = @_;
                   2793:     my $value;
                   2794:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2795: 	$value = $1;
                   2796:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2797: 	$value = $1;
                   2798:     }
                   2799:     return &unescape($value);
                   2800: }
                   2801: 
                   2802: sub array2str {
                   2803:   my (@array) = @_;
                   2804:   my $result=&arrayref2str(\@array);
                   2805:   $result=~s/^__ARRAY_REF__//;
                   2806:   $result=~s/__END_ARRAY_REF__$//;
                   2807:   return $result;
                   2808: }
                   2809: 
1.204     albertel 2810: sub arrayref2str {
                   2811:   my ($arrayref) = @_;
1.265     albertel 2812:   my $result='__ARRAY_REF__';
1.204     albertel 2813:   foreach my $elem (@$arrayref) {
1.265     albertel 2814:     if(ref($elem) eq 'ARRAY') {
                   2815:       $result.=&arrayref2str($elem).'&';
                   2816:     } elsif(ref($elem) eq 'HASH') {
                   2817:       $result.=&hashref2str($elem).'&';
                   2818:     } elsif(ref($elem)) {
                   2819:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2820:     } else {
                   2821:       $result.=&escape($elem).'&';
                   2822:     }
                   2823:   }
                   2824:   $result=~s/\&$//;
1.265     albertel 2825:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2826:   return $result;
                   2827: }
                   2828: 
1.168     albertel 2829: sub hash2str {
1.204     albertel 2830:   my (%hash) = @_;
                   2831:   my $result=&hashref2str(\%hash);
1.265     albertel 2832:   $result=~s/^__HASH_REF__//;
                   2833:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2834:   return $result;
                   2835: }
                   2836: 
                   2837: sub hashref2str {
                   2838:   my ($hashref)=@_;
1.265     albertel 2839:   my $result='__HASH_REF__';
1.800     albertel 2840:   foreach my $key (sort(keys(%$hashref))) {
                   2841:     if (ref($key) eq 'ARRAY') {
                   2842:       $result.=&arrayref2str($key).'=';
                   2843:     } elsif (ref($key) eq 'HASH') {
                   2844:       $result.=&hashref2str($key).'=';
                   2845:     } elsif (ref($key)) {
1.265     albertel 2846:       $result.='=';
1.800     albertel 2847:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2848:     } else {
1.800     albertel 2849: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2850:     }
                   2851: 
1.800     albertel 2852:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2853:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2854:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2855:       $result.=&hashref2str($hashref->{$key}).'&';
                   2856:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2857:        $result.='&';
1.800     albertel 2858:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2859:     } else {
1.800     albertel 2860:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2861:     }
                   2862:   }
1.168     albertel 2863:   $result=~s/\&$//;
1.265     albertel 2864:   $result .= '__END_HASH_REF__';
1.168     albertel 2865:   return $result;
                   2866: }
                   2867: 
                   2868: sub str2hash {
1.265     albertel 2869:     my ($string)=@_;
                   2870:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2871:     return %$hash;
                   2872: }
                   2873: 
                   2874: sub str2hashref {
1.168     albertel 2875:   my ($string) = @_;
1.265     albertel 2876: 
                   2877:   my %hash;
                   2878: 
                   2879:   if($string !~ /^__HASH_REF__/) {
                   2880:       if (! ($string eq '' || !defined($string))) {
                   2881: 	  $hash{'error'}='Not hash reference';
                   2882:       }
                   2883:       return (\%hash, $string);
                   2884:   }
                   2885: 
                   2886:   $string =~ s/^__HASH_REF__//;
                   2887: 
                   2888:   while($string !~ /^__END_HASH_REF__/) {
                   2889:       #key
                   2890:       my $key='';
                   2891:       if($string =~ /^__HASH_REF__/) {
                   2892:           ($key, $string)=&str2hashref($string);
                   2893:           if(defined($key->{'error'})) {
                   2894:               $hash{'error'}='Bad data';
                   2895:               return (\%hash, $string);
                   2896:           }
                   2897:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2898:           ($key, $string)=&str2arrayref($string);
                   2899:           if($key->[0] eq 'Array reference error') {
                   2900:               $hash{'error'}='Bad data';
                   2901:               return (\%hash, $string);
                   2902:           }
                   2903:       } else {
                   2904:           $string =~ s/^(.*?)=//;
1.267     albertel 2905: 	  $key=&unescape($1);
1.265     albertel 2906:       }
                   2907:       $string =~ s/^=//;
                   2908: 
                   2909:       #value
                   2910:       my $value='';
                   2911:       if($string =~ /^__HASH_REF__/) {
                   2912:           ($value, $string)=&str2hashref($string);
                   2913:           if(defined($value->{'error'})) {
                   2914:               $hash{'error'}='Bad data';
                   2915:               return (\%hash, $string);
                   2916:           }
                   2917:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2918:           ($value, $string)=&str2arrayref($string);
                   2919:           if($value->[0] eq 'Array reference error') {
                   2920:               $hash{'error'}='Bad data';
                   2921:               return (\%hash, $string);
                   2922:           }
                   2923:       } else {
                   2924: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2925:       }
                   2926:       $string =~ s/^&//;
                   2927: 
                   2928:       $hash{$key}=$value;
1.204     albertel 2929:   }
1.265     albertel 2930: 
                   2931:   $string =~ s/^__END_HASH_REF__//;
                   2932: 
                   2933:   return (\%hash, $string);
1.204     albertel 2934: }
                   2935: 
                   2936: sub str2array {
1.265     albertel 2937:     my ($string)=@_;
                   2938:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2939:     return @$array;
                   2940: }
                   2941: 
                   2942: sub str2arrayref {
1.204     albertel 2943:   my ($string) = @_;
1.265     albertel 2944:   my @array;
                   2945: 
                   2946:   if($string !~ /^__ARRAY_REF__/) {
                   2947:       if (! ($string eq '' || !defined($string))) {
                   2948: 	  $array[0]='Array reference error';
                   2949:       }
                   2950:       return (\@array, $string);
                   2951:   }
                   2952: 
                   2953:   $string =~ s/^__ARRAY_REF__//;
                   2954: 
                   2955:   while($string !~ /^__END_ARRAY_REF__/) {
                   2956:       my $value='';
                   2957:       if($string =~ /^__HASH_REF__/) {
                   2958:           ($value, $string)=&str2hashref($string);
                   2959:           if(defined($value->{'error'})) {
                   2960:               $array[0] ='Array reference error';
                   2961:               return (\@array, $string);
                   2962:           }
                   2963:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2964:           ($value, $string)=&str2arrayref($string);
                   2965:           if($value->[0] eq 'Array reference error') {
                   2966:               $array[0] ='Array reference error';
                   2967:               return (\@array, $string);
                   2968:           }
                   2969:       } else {
                   2970: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2971:       }
                   2972:       $string =~ s/^&//;
                   2973: 
                   2974:       push(@array, $value);
1.191     harris41 2975:   }
1.265     albertel 2976: 
                   2977:   $string =~ s/^__END_ARRAY_REF__//;
                   2978: 
                   2979:   return (\@array, $string);
1.168     albertel 2980: }
                   2981: 
1.167     albertel 2982: # -------------------------------------------------------------------Temp Store
                   2983: 
1.168     albertel 2984: sub tmpreset {
                   2985:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2986:   if (!$symb) {
                   2987:     $symb=&symbread();
1.620     albertel 2988:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2989:   }
                   2990:   $symb=escape($symb);
                   2991: 
1.620     albertel 2992:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2993:   $namespace=~s/\//\_/g;
                   2994:   $namespace=~s/\W//g;
                   2995: 
1.620     albertel 2996:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2997:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2998:   if ($domain eq 'public' && $stuname eq 'public') {
                   2999:       $stuname=$ENV{'REMOTE_ADDR'};
                   3000:   }
1.168     albertel 3001:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3002:   my %hash;
                   3003:   if (tie(%hash,'GDBM_File',
                   3004: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3005: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3006:     foreach my $key (keys %hash) {
1.180     albertel 3007:       if ($key=~ /:$symb/) {
1.168     albertel 3008: 	delete($hash{$key});
                   3009:       }
                   3010:     }
                   3011:   }
                   3012: }
                   3013: 
1.167     albertel 3014: sub tmpstore {
1.168     albertel 3015:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3016: 
                   3017:   if (!$symb) {
                   3018:     $symb=&symbread();
1.620     albertel 3019:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3020:   }
                   3021:   $symb=escape($symb);
                   3022: 
                   3023:   if (!$namespace) {
                   3024:     # I don't think we would ever want to store this for a course.
                   3025:     # it seems this will only be used if we don't have a course.
1.620     albertel 3026:     #$namespace=$env{'request.course.id'};
1.168     albertel 3027:     #if (!$namespace) {
1.620     albertel 3028:       $namespace=$env{'request.state'};
1.168     albertel 3029:     #}
                   3030:   }
                   3031:   $namespace=~s/\//\_/g;
                   3032:   $namespace=~s/\W//g;
1.620     albertel 3033:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3034:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3035:   if ($domain eq 'public' && $stuname eq 'public') {
                   3036:       $stuname=$ENV{'REMOTE_ADDR'};
                   3037:   }
1.168     albertel 3038:   my $now=time;
                   3039:   my %hash;
                   3040:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3041:   if (tie(%hash,'GDBM_File',
                   3042: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3043: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3044:     $hash{"version:$symb"}++;
                   3045:     my $version=$hash{"version:$symb"};
                   3046:     my $allkeys=''; 
                   3047:     foreach my $key (keys(%$storehash)) {
                   3048:       $allkeys.=$key.':';
1.591     albertel 3049:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3050:     }
                   3051:     $hash{"$version:$symb:timestamp"}=$now;
                   3052:     $allkeys.='timestamp';
                   3053:     $hash{"$version:keys:$symb"}=$allkeys;
                   3054:     if (untie(%hash)) {
                   3055:       return 'ok';
                   3056:     } else {
                   3057:       return "error:$!";
                   3058:     }
                   3059:   } else {
                   3060:     return "error:$!";
                   3061:   }
                   3062: }
1.167     albertel 3063: 
1.168     albertel 3064: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3065: 
1.168     albertel 3066: sub tmprestore {
                   3067:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3068: 
1.168     albertel 3069:   if (!$symb) {
                   3070:     $symb=&symbread();
1.620     albertel 3071:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3072:   }
                   3073:   $symb=escape($symb);
                   3074: 
1.620     albertel 3075:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3076: 
1.620     albertel 3077:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3078:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3079:   if ($domain eq 'public' && $stuname eq 'public') {
                   3080:       $stuname=$ENV{'REMOTE_ADDR'};
                   3081:   }
1.168     albertel 3082:   my %returnhash;
                   3083:   $namespace=~s/\//\_/g;
                   3084:   $namespace=~s/\W//g;
                   3085:   my %hash;
                   3086:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3087:   if (tie(%hash,'GDBM_File',
                   3088: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3089: 	  &GDBM_READER(),0640)) {
1.168     albertel 3090:     my $version=$hash{"version:$symb"};
                   3091:     $returnhash{'version'}=$version;
                   3092:     my $scope;
                   3093:     for ($scope=1;$scope<=$version;$scope++) {
                   3094:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3095:       my @keys=split(/:/,$vkeys);
                   3096:       my $key;
                   3097:       $returnhash{"$scope:keys"}=$vkeys;
                   3098:       foreach $key (@keys) {
1.591     albertel 3099: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3100: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3101:       }
                   3102:     }
1.168     albertel 3103:     if (!(untie(%hash))) {
                   3104:       return "error:$!";
                   3105:     }
                   3106:   } else {
                   3107:     return "error:$!";
                   3108:   }
                   3109:   return %returnhash;
1.167     albertel 3110: }
                   3111: 
1.9       www      3112: # ----------------------------------------------------------------------- Store
                   3113: 
                   3114: sub store {
1.124     www      3115:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3116:     my $home='';
                   3117: 
1.168     albertel 3118:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3119: 
1.213     www      3120:     $symb=&symbclean($symb);
1.122     albertel 3121:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3122: 
1.620     albertel 3123:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3124:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3125: 
                   3126:     &devalidate($symb,$stuname,$domain);
1.109     www      3127: 
                   3128:     $symb=escape($symb);
1.187     www      3129:     if (!$namespace) { 
1.620     albertel 3130:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3131:           return ''; 
                   3132:        } 
                   3133:     }
1.620     albertel 3134:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3135: 
                   3136:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3137:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3138: 
1.12      www      3139:     my $namevalue='';
1.800     albertel 3140:     foreach my $key (keys(%$storehash)) {
                   3141:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3142:     }
1.12      www      3143:     $namevalue=~s/\&$//;
1.187     www      3144:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3145:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3146: }
                   3147: 
1.47      www      3148: # -------------------------------------------------------------- Critical Store
                   3149: 
                   3150: sub cstore {
1.124     www      3151:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3152:     my $home='';
                   3153: 
1.168     albertel 3154:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3155: 
1.213     www      3156:     $symb=&symbclean($symb);
1.122     albertel 3157:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3158: 
1.620     albertel 3159:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3160:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3161: 
                   3162:     &devalidate($symb,$stuname,$domain);
1.109     www      3163: 
                   3164:     $symb=escape($symb);
1.187     www      3165:     if (!$namespace) { 
1.620     albertel 3166:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3167:           return ''; 
                   3168:        } 
                   3169:     }
1.620     albertel 3170:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3171: 
                   3172:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3173:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3174: 
1.47      www      3175:     my $namevalue='';
1.800     albertel 3176:     foreach my $key (keys(%$storehash)) {
                   3177:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3178:     }
1.47      www      3179:     $namevalue=~s/\&$//;
1.187     www      3180:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3181:     return critical
                   3182:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3183: }
                   3184: 
1.9       www      3185: # --------------------------------------------------------------------- Restore
                   3186: 
                   3187: sub restore {
1.124     www      3188:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3189:     my $home='';
                   3190: 
1.168     albertel 3191:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3192: 
1.122     albertel 3193:     if (!$symb) {
                   3194:       unless ($symb=escape(&symbread())) { return ''; }
                   3195:     } else {
1.213     www      3196:       $symb=&escape(&symbclean($symb));
1.122     albertel 3197:     }
1.188     www      3198:     if (!$namespace) { 
1.620     albertel 3199:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3200:           return ''; 
                   3201:        } 
                   3202:     }
1.620     albertel 3203:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3204:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3205:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3206:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3207: 
1.12      www      3208:     my %returnhash=();
1.800     albertel 3209:     foreach my $line (split(/\&/,$answer)) {
                   3210: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3211:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3212:     }
1.75      www      3213:     my $version;
                   3214:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3215:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3216:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3217:        }
1.75      www      3218:     }
1.13      www      3219:     return %returnhash;
1.34      www      3220: }
                   3221: 
                   3222: # ---------------------------------------------------------- Course Description
                   3223: 
                   3224: sub coursedescription {
1.731     albertel 3225:     my ($courseid,$args)=@_;
1.34      www      3226:     $courseid=~s/^\///;
1.49      www      3227:     $courseid=~s/\_/\//g;
1.34      www      3228:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3229:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3230:     my $normalid=$cdomain.'_'.$cnum;
                   3231:     # need to always cache even if we get errors otherwise we keep 
                   3232:     # trying and trying and trying to get the course description.
                   3233:     my %envhash=();
                   3234:     my %returnhash=();
1.731     albertel 3235:     
                   3236:     my $expiretime=600;
                   3237:     if ($env{'request.course.id'} eq $normalid) {
                   3238: 	$expiretime=120;
                   3239:     }
                   3240: 
                   3241:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3242:     if (!$args->{'freshen_cache'}
                   3243: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3244: 	foreach my $key (keys(%env)) {
                   3245: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3246: 	    my ($setting) = $1;
                   3247: 	    $returnhash{$setting} = $env{$key};
                   3248: 	}
                   3249: 	return %returnhash;
                   3250:     }
                   3251: 
                   3252:     # get the data agin
                   3253:     if (!$args->{'one_time'}) {
                   3254: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3255:     }
1.811     albertel 3256: 
1.34      www      3257:     if ($chome ne 'no_host') {
1.302     albertel 3258:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3259:        if (!exists($returnhash{'con_lost'})) {
                   3260:            $returnhash{'home'}= $chome;
                   3261: 	   $returnhash{'domain'} = $cdomain;
                   3262: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3263:            if (!defined($returnhash{'type'})) {
                   3264:                $returnhash{'type'} = 'Course';
                   3265:            }
1.130     albertel 3266:            while (my ($name,$value) = each %returnhash) {
1.53      www      3267:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3268:            }
1.270     www      3269:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3270:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3271: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3272:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3273:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3274:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3275:        }
                   3276:     }
1.731     albertel 3277:     if (!$args->{'one_time'}) {
                   3278: 	&appenv(%envhash);
                   3279:     }
1.302     albertel 3280:     return %returnhash;
1.461     www      3281: }
                   3282: 
                   3283: # -------------------------------------------------See if a user is privileged
                   3284: 
                   3285: sub privileged {
                   3286:     my ($username,$domain)=@_;
                   3287:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3288: 			&homeserver($username,$domain));
                   3289:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3290:     my $now=time;
                   3291:     if ($rolesdump ne '') {
1.800     albertel 3292:         foreach my $entry (split(/&/,$rolesdump)) {
                   3293: 	    if ($entry!~/^rolesdef_/) {
                   3294: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3295: 		$area=~s/\_\w\w$//;
                   3296: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3297: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3298: 		    my $active=1;
                   3299: 		    if ($tend) {
                   3300: 			if ($tend<$now) { $active=0; }
                   3301: 		    }
                   3302: 		    if ($tstart) {
                   3303: 			if ($tstart>$now) { $active=0; }
                   3304: 		    }
                   3305: 		    if ($active) { return 1; }
                   3306: 		}
                   3307: 	    }
                   3308: 	}
                   3309:     }
                   3310:     return 0;
1.9       www      3311: }
1.1       albertel 3312: 
1.103     harris41 3313: # -------------------------------------------------------- Get user privileges
1.11      www      3314: 
                   3315: sub rolesinit {
                   3316:     my ($domain,$username,$authhost)=@_;
                   3317:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3318:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3319:     my %allroles=();
1.678     raeburn  3320:     my %allgroups=();   
1.11      www      3321:     my $now=time;
1.743     albertel 3322:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3323:     my $group_privs;
1.11      www      3324: 
                   3325:     if ($rolesdump ne '') {
1.800     albertel 3326:         foreach my $entry (split(/&/,$rolesdump)) {
                   3327: 	  if ($entry!~/^rolesdef_/) {
                   3328:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3329: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3330:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3331: 	    if ($role=~/^cr/) { 
1.807     albertel 3332: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3333: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3334: 		    ($tend,$tstart)=split('_',$trest);
                   3335: 		} else {
                   3336: 		    $trole=$role;
                   3337: 		}
1.678     raeburn  3338:             } elsif ($role =~ m|^gr/|) {
                   3339:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3340:                 ($trole,$group_privs) = split(/\//,$trole);
                   3341:                 $group_privs = &unescape($group_privs);
1.587     albertel 3342: 	    } else {
                   3343: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3344: 	    }
1.743     albertel 3345: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3346: 					 $username);
                   3347: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3348:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3349:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3350:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3351: 		my $spec=$trole.'.'.$area;
                   3352: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3353: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3354:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3355:                 } elsif ($trole eq 'gr') {
                   3356:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3357: 		} else {
1.567     raeburn  3358:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3359: 		}
1.12      www      3360:             }
1.662     raeburn  3361:           }
1.191     harris41 3362:         }
1.743     albertel 3363:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3364:         $userroles{'user.adv'}    = $adv;
                   3365: 	$userroles{'user.author'} = $author;
1.620     albertel 3366:         $env{'user.adv'}=$adv;
1.11      www      3367:     }
1.743     albertel 3368:     return \%userroles;  
1.11      www      3369: }
                   3370: 
1.567     raeburn  3371: sub set_arearole {
                   3372:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3373: # log the associated role with the area
                   3374:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3375:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3376: }
                   3377: 
                   3378: sub custom_roleprivs {
                   3379:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3380:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3381:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3382:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3383:         my ($rdummy,$roledef)=
                   3384:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3385:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3386:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3387:             if (defined($syspriv)) {
                   3388:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3389:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3390:             }
                   3391:             if ($tdomain ne '') {
                   3392:                 if (defined($dompriv)) {
                   3393:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3394:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3395:                 }
                   3396:                 if (($trest ne '') && (defined($coursepriv))) {
                   3397:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3398:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3399:                 }
                   3400:             }
                   3401:         }
                   3402:     }
                   3403: }
                   3404: 
1.678     raeburn  3405: sub group_roleprivs {
                   3406:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3407:     my $access = 1;
                   3408:     my $now = time;
                   3409:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3410:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3411:     if ($access) {
1.811     albertel 3412:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3413:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3414:     }
                   3415: }
1.567     raeburn  3416: 
                   3417: sub standard_roleprivs {
                   3418:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3419:     if (defined($pr{$trole.':s'})) {
                   3420:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3421:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3422:     }
                   3423:     if ($tdomain ne '') {
                   3424:         if (defined($pr{$trole.':d'})) {
                   3425:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3426:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3427:         }
                   3428:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3429:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3430:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3431:         }
                   3432:     }
                   3433: }
                   3434: 
                   3435: sub set_userprivs {
1.678     raeburn  3436:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3437:     my $author=0;
                   3438:     my $adv=0;
1.678     raeburn  3439:     my %grouproles = ();
                   3440:     if (keys(%{$allgroups}) > 0) {
                   3441:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3442:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3443:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3444:                 $trole = $1;
                   3445:                 $area = $2;
1.681     raeburn  3446:                 $sec = $3;
                   3447:                 $extendedarea = $area.$sec;
                   3448:                 if (exists($$allgroups{$area})) {
                   3449:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3450:                         my $spec = $trole.'.'.$extendedarea;
                   3451:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3452:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3453:                     }
                   3454:                 }
                   3455:             }
                   3456:         }
                   3457:     }
1.800     albertel 3458:     foreach my $group (keys(%grouproles)) {
                   3459:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3460:     }
1.800     albertel 3461:     foreach my $role (keys(%{$allroles})) {
                   3462:         my %thesepriv;
                   3463:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3464:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3465:             if ($item ne '') {
                   3466:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3467:                 if ($restrictions eq '') {
                   3468:                     $thesepriv{$privilege}='F';
                   3469:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3470:                     $thesepriv{$privilege}.=$restrictions;
                   3471:                 }
                   3472:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3473:             }
                   3474:         }
                   3475:         my $thesestr='';
1.800     albertel 3476:         foreach my $priv (keys(%thesepriv)) {
                   3477: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3478: 	}
                   3479:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3480:     }
                   3481:     return ($author,$adv);
                   3482: }
                   3483: 
1.12      www      3484: # --------------------------------------------------------------- get interface
                   3485: 
                   3486: sub get {
1.131     albertel 3487:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3488:    my $items='';
1.800     albertel 3489:    foreach my $item (@$storearr) {
                   3490:        $items.=&escape($item).'&';
1.191     harris41 3491:    }
1.12      www      3492:    $items=~s/\&$//;
1.620     albertel 3493:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3494:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3495:    my $uhome=&homeserver($uname,$udomain);
                   3496: 
1.133     albertel 3497:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3498:    my @pairs=split(/\&/,$rep);
1.273     albertel 3499:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3500:      return @pairs;
                   3501:    }
1.15      www      3502:    my %returnhash=();
1.42      www      3503:    my $i=0;
1.800     albertel 3504:    foreach my $item (@$storearr) {
                   3505:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3506:       $i++;
1.191     harris41 3507:    }
1.15      www      3508:    return %returnhash;
1.27      www      3509: }
                   3510: 
                   3511: # --------------------------------------------------------------- del interface
                   3512: 
                   3513: sub del {
1.133     albertel 3514:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3515:    my $items='';
1.800     albertel 3516:    foreach my $item (@$storearr) {
                   3517:        $items.=&escape($item).'&';
1.191     harris41 3518:    }
1.27      www      3519:    $items=~s/\&$//;
1.620     albertel 3520:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3521:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3522:    my $uhome=&homeserver($uname,$udomain);
                   3523: 
                   3524:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3525: }
                   3526: 
                   3527: # -------------------------------------------------------------- dump interface
                   3528: 
                   3529: sub dump {
1.755     albertel 3530:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3531:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3532:     if (!$uname) { $uname=$env{'user.name'}; }
                   3533:     my $uhome=&homeserver($uname,$udomain);
                   3534:     if ($regexp) {
                   3535: 	$regexp=&escape($regexp);
                   3536:     } else {
                   3537: 	$regexp='.';
                   3538:     }
                   3539:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3540:     my @pairs=split(/\&/,$rep);
                   3541:     my %returnhash=();
                   3542:     foreach my $item (@pairs) {
                   3543: 	my ($key,$value)=split(/=/,$item,2);
                   3544: 	$key = &unescape($key);
                   3545: 	next if ($key =~ /^error: 2 /);
                   3546: 	$returnhash{$key}=&thaw_unescape($value);
                   3547:     }
                   3548:     return %returnhash;
1.407     www      3549: }
                   3550: 
1.717     albertel 3551: # --------------------------------------------------------- dumpstore interface
                   3552: 
                   3553: sub dumpstore {
                   3554:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3555:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3556:    if (!$uname) { $uname=$env{'user.name'}; }
                   3557:    my $uhome=&homeserver($uname,$udomain);
                   3558:    if ($regexp) {
                   3559:        $regexp=&escape($regexp);
                   3560:    } else {
                   3561:        $regexp='.';
                   3562:    }
                   3563:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3564:    my @pairs=split(/\&/,$rep);
                   3565:    my %returnhash=();
                   3566:    foreach my $item (@pairs) {
                   3567:        my ($key,$value)=split(/=/,$item,2);
                   3568:        next if ($key =~ /^error: 2 /);
                   3569:        $returnhash{$key}=&thaw_unescape($value);
                   3570:    }
                   3571:    return %returnhash;
1.717     albertel 3572: }
                   3573: 
1.407     www      3574: # -------------------------------------------------------------- keys interface
                   3575: 
                   3576: sub getkeys {
                   3577:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3578:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3579:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3580:    my $uhome=&homeserver($uname,$udomain);
                   3581:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3582:    my @keyarray=();
1.800     albertel 3583:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3584:       next if ($key =~ /^error: 2 /);
1.800     albertel 3585:       push(@keyarray,&unescape($key));
1.407     www      3586:    }
                   3587:    return @keyarray;
1.318     matthew  3588: }
                   3589: 
1.319     matthew  3590: # --------------------------------------------------------------- currentdump
                   3591: sub currentdump {
1.328     matthew  3592:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3593:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3594:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3595:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3596:    my $uhome = &homeserver($sname,$sdom);
                   3597:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3598:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3599:    #
1.318     matthew  3600:    my %returnhash=();
1.319     matthew  3601:    #
                   3602:    if ($rep eq "unknown_cmd") { 
                   3603:        # an old lond will not know currentdump
                   3604:        # Do a dump and make it look like a currentdump
1.822     albertel 3605:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3606:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3607:        my %hash = @tmp;
                   3608:        @tmp=();
1.424     matthew  3609:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3610:    } else {
                   3611:        my @pairs=split(/\&/,$rep);
1.800     albertel 3612:        foreach my $pair (@pairs) {
                   3613:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3614:            my ($symb,$param) = split(/:/,$key);
                   3615:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3616:                                                         &thaw_unescape($value);
1.319     matthew  3617:        }
1.191     harris41 3618:    }
1.12      www      3619:    return %returnhash;
1.424     matthew  3620: }
                   3621: 
                   3622: sub convert_dump_to_currentdump{
                   3623:     my %hash = %{shift()};
                   3624:     my %returnhash;
                   3625:     # Code ripped from lond, essentially.  The only difference
                   3626:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3627:     # we might run in to problems with parameter names =~ /^v\./
                   3628:     while (my ($key,$value) = each(%hash)) {
                   3629:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3630: 	$symb  = &unescape($symb);
                   3631: 	$param = &unescape($param);
1.424     matthew  3632:         next if ($v eq 'version' || $symb eq 'keys');
                   3633:         next if (exists($returnhash{$symb}) &&
                   3634:                  exists($returnhash{$symb}->{$param}) &&
                   3635:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3636:         $returnhash{$symb}->{$param}=$value;
                   3637:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3638:     }
                   3639:     #
                   3640:     # Remove all of the keys in the hashes which keep track of
                   3641:     # the version of the parameter.
                   3642:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3643:         # use a foreach because we are going to delete from the hash.
                   3644:         foreach my $key (keys(%$param_hash)) {
                   3645:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3646:         }
                   3647:     }
                   3648:     return \%returnhash;
1.12      www      3649: }
                   3650: 
1.627     albertel 3651: # ------------------------------------------------------ critical inc interface
                   3652: 
                   3653: sub cinc {
                   3654:     return &inc(@_,'critical');
                   3655: }
                   3656: 
1.449     matthew  3657: # --------------------------------------------------------------- inc interface
                   3658: 
                   3659: sub inc {
1.627     albertel 3660:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3661:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3662:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3663:     my $uhome=&homeserver($uname,$udomain);
                   3664:     my $items='';
                   3665:     if (! ref($store)) {
                   3666:         # got a single value, so use that instead
                   3667:         $items = &escape($store).'=&';
                   3668:     } elsif (ref($store) eq 'SCALAR') {
                   3669:         $items = &escape($$store).'=&';        
                   3670:     } elsif (ref($store) eq 'ARRAY') {
                   3671:         $items = join('=&',map {&escape($_);} @{$store});
                   3672:     } elsif (ref($store) eq 'HASH') {
                   3673:         while (my($key,$value) = each(%{$store})) {
                   3674:             $items.= &escape($key).'='.&escape($value).'&';
                   3675:         }
                   3676:     }
                   3677:     $items=~s/\&$//;
1.627     albertel 3678:     if ($critical) {
                   3679: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3680:     } else {
                   3681: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3682:     }
1.449     matthew  3683: }
                   3684: 
1.12      www      3685: # --------------------------------------------------------------- put interface
                   3686: 
                   3687: sub put {
1.134     albertel 3688:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3689:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3690:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3691:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3692:    my $items='';
1.800     albertel 3693:    foreach my $item (keys(%$storehash)) {
                   3694:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3695:    }
1.12      www      3696:    $items=~s/\&$//;
1.134     albertel 3697:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3698: }
                   3699: 
1.631     albertel 3700: # ------------------------------------------------------------ newput interface
                   3701: 
                   3702: sub newput {
                   3703:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3704:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3705:    if (!$uname) { $uname=$env{'user.name'}; }
                   3706:    my $uhome=&homeserver($uname,$udomain);
                   3707:    my $items='';
                   3708:    foreach my $key (keys(%$storehash)) {
                   3709:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3710:    }
                   3711:    $items=~s/\&$//;
                   3712:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3713: }
                   3714: 
                   3715: # ---------------------------------------------------------  putstore interface
                   3716: 
1.524     raeburn  3717: sub putstore {
1.715     albertel 3718:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3719:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3720:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3721:    my $uhome=&homeserver($uname,$udomain);
                   3722:    my $items='';
1.715     albertel 3723:    foreach my $key (keys(%$storehash)) {
                   3724:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3725:    }
1.715     albertel 3726:    $items=~s/\&$//;
1.716     albertel 3727:    my $esc_symb=&escape($symb);
                   3728:    my $esc_v=&escape($version);
1.715     albertel 3729:    my $reply =
1.716     albertel 3730:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3731: 	      $uhome);
                   3732:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3733:        # gfall back to way things use to be done
1.715     albertel 3734:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3735: 			    $uname);
1.524     raeburn  3736:    }
1.715     albertel 3737:    return $reply;
                   3738: }
                   3739: 
                   3740: sub old_putstore {
1.716     albertel 3741:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3742:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3743:     if (!$uname) { $uname=$env{'user.name'}; }
                   3744:     my $uhome=&homeserver($uname,$udomain);
                   3745:     my %newstorehash;
1.800     albertel 3746:     foreach my $item (keys(%$storehash)) {
                   3747: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3748: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3749:     }
                   3750:     my $items='';
                   3751:     my %allitems = ();
1.800     albertel 3752:     foreach my $item (keys(%newstorehash)) {
                   3753: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3754: 	    my $key = $1.':keys:'.$2;
                   3755: 	    $allitems{$key} .= $3.':';
                   3756: 	}
1.800     albertel 3757: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3758:     }
1.800     albertel 3759:     foreach my $item (keys(%allitems)) {
                   3760: 	$allitems{$item} =~ s/\:$//;
                   3761: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3762:     }
                   3763:     $items=~s/\&$//;
                   3764:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3765: }
                   3766: 
1.47      www      3767: # ------------------------------------------------------ critical put interface
                   3768: 
                   3769: sub cput {
1.134     albertel 3770:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3771:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3772:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3773:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3774:    my $items='';
1.800     albertel 3775:    foreach my $item (keys(%$storehash)) {
                   3776:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3777:    }
1.47      www      3778:    $items=~s/\&$//;
1.134     albertel 3779:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3780: }
                   3781: 
                   3782: # -------------------------------------------------------------- eget interface
                   3783: 
                   3784: sub eget {
1.133     albertel 3785:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3786:    my $items='';
1.800     albertel 3787:    foreach my $item (@$storearr) {
                   3788:        $items.=&escape($item).'&';
1.191     harris41 3789:    }
1.12      www      3790:    $items=~s/\&$//;
1.620     albertel 3791:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3792:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3793:    my $uhome=&homeserver($uname,$udomain);
                   3794:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3795:    my @pairs=split(/\&/,$rep);
                   3796:    my %returnhash=();
1.42      www      3797:    my $i=0;
1.800     albertel 3798:    foreach my $item (@$storearr) {
                   3799:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3800:       $i++;
1.191     harris41 3801:    }
1.12      www      3802:    return %returnhash;
                   3803: }
                   3804: 
1.667     albertel 3805: # ------------------------------------------------------------ tmpput interface
                   3806: sub tmpput {
1.802     raeburn  3807:     my ($storehash,$server,$context)=@_;
1.667     albertel 3808:     my $items='';
1.800     albertel 3809:     foreach my $item (keys(%$storehash)) {
                   3810: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3811:     }
                   3812:     $items=~s/\&$//;
1.802     raeburn  3813:     if (defined($context)) {
                   3814:         $items .= ':'.&escape($context);
                   3815:     }
1.667     albertel 3816:     return &reply("tmpput:$items",$server);
                   3817: }
                   3818: 
                   3819: # ------------------------------------------------------------ tmpget interface
                   3820: sub tmpget {
1.688     albertel 3821:     my ($token,$server)=@_;
                   3822:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3823:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3824:     my %returnhash;
                   3825:     foreach my $item (split(/\&/,$rep)) {
                   3826: 	my ($key,$value)=split(/=/,$item);
                   3827: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3828:     }
                   3829:     return %returnhash;
                   3830: }
                   3831: 
1.688     albertel 3832: # ------------------------------------------------------------ tmpget interface
                   3833: sub tmpdel {
                   3834:     my ($token,$server)=@_;
                   3835:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3836:     return &reply("tmpdel:$token",$server);
                   3837: }
                   3838: 
1.765     albertel 3839: # -------------------------------------------------- portfolio access checking
                   3840: 
                   3841: sub portfolio_access {
1.766     albertel 3842:     my ($requrl) = @_;
1.765     albertel 3843:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3844:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3845:     if ($result) {
                   3846:         my %setters;
                   3847:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3848:             my ($startblock,$endblock) =
                   3849:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3850:             if ($startblock && $endblock) {
                   3851:                 return 'B';
                   3852:             }
                   3853:         } else {
                   3854:             my ($startblock,$endblock) =
                   3855:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3856:             if ($startblock && $endblock) {
                   3857:                 return 'B';
                   3858:             }
                   3859:         }
                   3860:     }
1.765     albertel 3861:     if ($result eq 'ok') {
1.766     albertel 3862:        return 'F';
1.765     albertel 3863:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3864:        return 'A';
1.765     albertel 3865:     }
1.766     albertel 3866:     return '';
1.765     albertel 3867: }
                   3868: 
                   3869: sub get_portfolio_access {
1.767     albertel 3870:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3871: 
                   3872:     if (!ref($access_hash)) {
                   3873: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3874: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3875: 						   $file_name);
                   3876: 	$access_hash = $access_controls{$file_name};
                   3877:     }
                   3878: 
1.765     albertel 3879:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3880:     my $now = time;
                   3881:     if (ref($access_hash) eq 'HASH') {
                   3882:         foreach my $key (keys(%{$access_hash})) {
                   3883:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3884:             if ($start > $now) {
                   3885:                 next;
                   3886:             }
                   3887:             if ($end && $end<$now) {
                   3888:                 next;
                   3889:             }
                   3890:             if ($scope eq 'public') {
                   3891:                 $public = $key;
                   3892:                 last;
                   3893:             } elsif ($scope eq 'guest') {
                   3894:                 $guest = $key;
                   3895:             } elsif ($scope eq 'domains') {
                   3896:                 push(@domains,$key);
                   3897:             } elsif ($scope eq 'users') {
                   3898:                 push(@users,$key);
                   3899:             } elsif ($scope eq 'course') {
                   3900:                 push(@courses,$key);
                   3901:             } elsif ($scope eq 'group') {
                   3902:                 push(@groups,$key);
                   3903:             }
                   3904:         }
                   3905:         if ($public) {
                   3906:             return 'ok';
                   3907:         }
                   3908:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3909:             if ($guest) {
                   3910:                 return $guest;
                   3911:             }
                   3912:         } else {
                   3913:             if (@domains > 0) {
                   3914:                 foreach my $domkey (@domains) {
                   3915:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3916:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3917:                             return 'ok';
                   3918:                         }
                   3919:                     }
                   3920:                 }
                   3921:             }
                   3922:             if (@users > 0) {
                   3923:                 foreach my $userkey (@users) {
1.865     raeburn  3924:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3925:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3926:                             if (ref($item) eq 'HASH') {
                   3927:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3928:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3929:                                     return 'ok';
                   3930:                                 }
                   3931:                             }
                   3932:                         }
                   3933:                     } 
1.765     albertel 3934:                 }
                   3935:             }
                   3936:             my %roleshash;
                   3937:             my @courses_and_groups = @courses;
                   3938:             push(@courses_and_groups,@groups); 
                   3939:             if (@courses_and_groups > 0) {
                   3940:                 my (%allgroups,%allroles); 
                   3941:                 my ($start,$end,$role,$sec,$group);
                   3942:                 foreach my $envkey (%env) {
1.811     albertel 3943:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3944:                         my $cid = $2.'_'.$3; 
                   3945:                         if ($1 eq 'gr') {
                   3946:                             $group = $4;
                   3947:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3948:                         } else {
                   3949:                             if ($4 eq '') {
                   3950:                                 $sec = 'none';
                   3951:                             } else {
                   3952:                                 $sec = $4;
                   3953:                             }
                   3954:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3955:                         }
1.811     albertel 3956:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3957:                         my $cid = $2.'_'.$3;
                   3958:                         if ($4 eq '') {
                   3959:                             $sec = 'none';
                   3960:                         } else {
                   3961:                             $sec = $4;
                   3962:                         }
                   3963:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3964:                     }
                   3965:                 }
                   3966:                 if (keys(%allroles) == 0) {
                   3967:                     return;
                   3968:                 }
                   3969:                 foreach my $key (@courses_and_groups) {
                   3970:                     my %content = %{$$access_hash{$key}};
                   3971:                     my $cnum = $content{'number'};
                   3972:                     my $cdom = $content{'domain'};
                   3973:                     my $cid = $cdom.'_'.$cnum;
                   3974:                     if (!exists($allroles{$cid})) {
                   3975:                         next;
                   3976:                     }    
                   3977:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3978:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3979:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3980:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3981:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3982:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3983:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3984:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3985:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3986:                                         if (grep/^all$/,@sections) {
                   3987:                                             return 'ok';
                   3988:                                         } else {
                   3989:                                             if (grep/^$sec$/,@sections) {
                   3990:                                                 return 'ok';
                   3991:                                             }
                   3992:                                         }
                   3993:                                     }
                   3994:                                 }
                   3995:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3996:                                     if (grep/^none$/,@groups) {
                   3997:                                         return 'ok';
                   3998:                                     }
                   3999:                                 } else {
                   4000:                                     if (grep/^all$/,@groups) {
                   4001:                                         return 'ok';
                   4002:                                     } 
                   4003:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4004:                                         if (grep/^$group$/,@groups) {
                   4005:                                             return 'ok';
                   4006:                                         }
                   4007:                                     }
                   4008:                                 } 
                   4009:                             }
                   4010:                         }
                   4011:                     }
                   4012:                 }
                   4013:             }
                   4014:             if ($guest) {
                   4015:                 return $guest;
                   4016:             }
                   4017:         }
                   4018:     }
                   4019:     return;
                   4020: }
                   4021: 
                   4022: sub course_group_datechecker {
                   4023:     my ($dates,$now,$status) = @_;
                   4024:     my ($start,$end) = split(/\./,$dates);
                   4025:     if (!$start && !$end) {
                   4026:         return 'ok';
                   4027:     }
                   4028:     if (grep/^active$/,@{$status}) {
                   4029:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4030:             return 'ok';
                   4031:         }
                   4032:     }
                   4033:     if (grep/^previous$/,@{$status}) {
                   4034:         if ($end > $now ) {
                   4035:             return 'ok';
                   4036:         }
                   4037:     }
                   4038:     if (grep/^future$/,@{$status}) {
                   4039:         if ($start > $now) {
                   4040:             return 'ok';
                   4041:         }
                   4042:     }
                   4043:     return; 
                   4044: }
                   4045: 
                   4046: sub parse_portfolio_url {
                   4047:     my ($url) = @_;
                   4048: 
                   4049:     my ($type,$udom,$unum,$group,$file_name);
                   4050:     
1.823     albertel 4051:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4052: 	$type = 1;
                   4053:         $udom = $1;
                   4054:         $unum = $2;
                   4055:         $file_name = $3;
1.823     albertel 4056:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4057: 	$type = 2;
                   4058:         $udom = $1;
                   4059:         $unum = $2;
                   4060:         $group = $3;
                   4061:         $file_name = $3.'/'.$4;
                   4062:     }
                   4063:     if (wantarray) {
                   4064: 	return ($type,$udom,$unum,$file_name,$group);
                   4065:     }
                   4066:     return $type;
                   4067: }
                   4068: 
                   4069: sub is_portfolio_url {
                   4070:     my ($url) = @_;
                   4071:     return scalar(&parse_portfolio_url($url));
                   4072: }
                   4073: 
1.798     raeburn  4074: sub is_portfolio_file {
                   4075:     my ($file) = @_;
1.820     raeburn  4076:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4077:         return 1;
                   4078:     }
                   4079:     return;
                   4080: }
                   4081: 
                   4082: 
1.341     www      4083: # ---------------------------------------------- Custom access rule evaluation
                   4084: 
                   4085: sub customaccess {
                   4086:     my ($priv,$uri)=@_;
1.807     albertel 4087:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4088:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4089:     $udom = &LONCAPA::clean_domain($udom);
                   4090:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4091:     my $access=0;
1.800     albertel 4092:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4093: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4094: 	if ($type eq 'user') {
                   4095: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4096: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4097: 		if ($tdom) {
                   4098: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4099: 		}
1.896     albertel 4100: 		if ($tuname) {
                   4101: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4102: 		}
                   4103: 		$access=($effect eq 'allow');
                   4104: 		last;
                   4105: 	    }
                   4106: 	} else {
                   4107: 	    if ($role) {
                   4108: 		if ($role ne $urole) { next; }
                   4109: 	    }
                   4110: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4111: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4112: 		if ($tdom) {
                   4113: 		    if ($tdom ne $udom) { next; }
                   4114: 		}
                   4115: 		if ($tcrs) {
                   4116: 		    if ($tcrs ne $ucrs) { next; }
                   4117: 		}
                   4118: 		if ($tsec) {
                   4119: 		    if ($tsec ne $usec) { next; }
                   4120: 		}
                   4121: 		$access=($effect eq 'allow');
                   4122: 		last;
                   4123: 	    }
                   4124: 	    if ($realm eq '' && $role eq '') {
                   4125: 		$access=($effect eq 'allow');
                   4126: 	    }
1.402     bowersj2 4127: 	}
1.341     www      4128:     }
                   4129:     return $access;
                   4130: }
                   4131: 
1.103     harris41 4132: # ------------------------------------------------- Check for a user privilege
1.12      www      4133: 
                   4134: sub allowed {
1.810     raeburn  4135:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4136:     my $ver_orguri=$uri;
1.439     www      4137:     $uri=&deversion($uri);
1.152     www      4138:     my $orguri=$uri;
1.52      www      4139:     $uri=&declutter($uri);
1.809     raeburn  4140: 
1.810     raeburn  4141:     if ($priv eq 'evb') {
                   4142: # Evade communication block restrictions for specified role in a course
                   4143:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4144:             return $1;
                   4145:         } else {
                   4146:             return;
                   4147:         }
                   4148:     }
                   4149: 
1.620     albertel 4150:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4151: # Free bre access to adm and meta resources
1.775     albertel 4152:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4153: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4154: 	&& ($priv eq 'bre')) {
1.14      www      4155: 	return 'F';
1.159     www      4156:     }
                   4157: 
1.545     banghart 4158: # Free bre access to user's own portfolio contents
1.714     raeburn  4159:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4160:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4161: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4162:         my %setters;
                   4163:         my ($startblock,$endblock) = 
                   4164:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4165:         if ($startblock && $endblock) {
                   4166:             return 'B';
                   4167:         } else {
                   4168:             return 'F';
                   4169:         }
1.545     banghart 4170:     }
                   4171: 
1.762     raeburn  4172: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4173:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4174:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4175:         if (exists($env{'request.course.id'})) {
                   4176:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4177:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4178:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4179:                 my $courseprivid=$env{'request.course.id'};
                   4180:                 $courseprivid=~s/\_/\//;
                   4181:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4182:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4183:                     return $1; 
1.762     raeburn  4184:                 } else {
                   4185:                     if ($env{'request.course.sec'}) {
                   4186:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4187:                     }
                   4188:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4189:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4190:                         return $2;
                   4191:                     }
1.714     raeburn  4192:                 }
                   4193:             }
                   4194:         }
                   4195:     }
                   4196: 
1.159     www      4197: # Free bre to public access
                   4198: 
                   4199:     if ($priv eq 'bre') {
1.238     www      4200:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4201: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4202:            return 'F'; 
                   4203:         }
1.238     www      4204:         if ($copyright eq 'priv') {
                   4205:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4206: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4207: 		return '';
                   4208:             }
                   4209:         }
                   4210:         if ($copyright eq 'domain') {
                   4211:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4212: 	    unless (($env{'user.domain'} eq $1) ||
                   4213:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4214: 		return '';
                   4215:             }
1.262     matthew  4216:         }
1.620     albertel 4217:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4218:             # Library role, so allow browsing of resources in this domain.
                   4219:             return 'F';
1.238     www      4220:         }
1.341     www      4221:         if ($copyright eq 'custom') {
                   4222: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4223:         }
1.14      www      4224:     }
1.264     matthew  4225:     # Domain coordinator is trying to create a course
1.620     albertel 4226:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4227:         # uri is the requested domain in this case.
                   4228:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4229:         # a role of dc for the domain in question.
1.620     albertel 4230:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4231:     }
1.29      www      4232: 
1.52      www      4233:     my $thisallowed='';
                   4234:     my $statecond=0;
                   4235:     my $courseprivid='';
                   4236: 
                   4237: # Course
                   4238: 
1.620     albertel 4239:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4240:        $thisallowed.=$1;
                   4241:     }
1.29      www      4242: 
1.52      www      4243: # Domain
                   4244: 
1.620     albertel 4245:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4246:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4247:        $thisallowed.=$1;
                   4248:     }
1.52      www      4249: 
                   4250: # Course: uri itself is a course
1.66      www      4251:     my $courseuri=$uri;
                   4252:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4253:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4254: 
1.620     albertel 4255:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4256:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4257:        $thisallowed.=$1;
                   4258:     }
1.29      www      4259: 
1.665     albertel 4260: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4261: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4262:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4263: 	$thisallowed='';
1.671     raeburn  4264:         my ($match)=&is_on_map($uri);
                   4265:         if ($match) {
                   4266:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4267:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4268:                 $thisallowed.=$1;
                   4269:             }
                   4270:         } else {
1.705     albertel 4271:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4272:             if ($refuri) {
                   4273:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4274:                     $thisallowed='F';
1.671     raeburn  4275:                 } else {
                   4276:                     $refuri=&declutter($refuri);
                   4277:                     my ($match) = &is_on_map($refuri);
                   4278:                     if ($match) {
                   4279:                         $thisallowed='F';
                   4280:                     }
1.669     raeburn  4281:                 }
1.671     raeburn  4282:             }
                   4283:         }
1.314     www      4284:     }
1.492     albertel 4285: 
1.766     albertel 4286:     if ($priv eq 'bre'
                   4287: 	&& $thisallowed ne 'F' 
                   4288: 	&& $thisallowed ne '2'
                   4289: 	&& &is_portfolio_url($uri)) {
                   4290: 	$thisallowed = &portfolio_access($uri);
                   4291:     }
                   4292:     
1.52      www      4293: # Full access at system, domain or course-wide level? Exit.
1.29      www      4294: 
                   4295:     if ($thisallowed=~/F/) {
                   4296: 	return 'F';
                   4297:     }
                   4298: 
1.52      www      4299: # If this is generating or modifying users, exit with special codes
1.29      www      4300: 
1.643     www      4301:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4302: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4303: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4304: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4305: 	    unless ($auname) { return $thisallowed; }
                   4306: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4307: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4308: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4309: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4310: 	}
1.52      www      4311: 	return $thisallowed;
                   4312:     }
                   4313: #
1.103     harris41 4314: # Gathered so far: system, domain and course wide privileges
1.52      www      4315: #
                   4316: # Course: See if uri or referer is an individual resource that is part of 
                   4317: # the course
                   4318: 
1.620     albertel 4319:     if ($env{'request.course.id'}) {
1.232     www      4320: 
1.620     albertel 4321:        $courseprivid=$env{'request.course.id'};
                   4322:        if ($env{'request.course.sec'}) {
                   4323:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4324:        }
                   4325:        $courseprivid=~s/\_/\//;
                   4326:        my $checkreferer=1;
1.232     www      4327:        my ($match,$cond)=&is_on_map($uri);
                   4328:        if ($match) {
                   4329:            $statecond=$cond;
1.620     albertel 4330:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4331:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4332:                $thisallowed.=$1;
                   4333:                $checkreferer=0;
                   4334:            }
1.29      www      4335:        }
1.83      www      4336:        
1.148     www      4337:        if ($checkreferer) {
1.620     albertel 4338: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4339:             unless ($refuri) {
1.800     albertel 4340:                 foreach my $key (keys(%env)) {
                   4341: 		    if ($key=~/^httpref\..*\*/) {
                   4342: 			my $pattern=$key;
1.156     www      4343:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4344:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4345:                         $pattern=~s/\//\\\//g;
1.152     www      4346:                         if ($orguri=~/$pattern/) {
1.800     albertel 4347: 			    $refuri=$env{$key};
1.148     www      4348:                         }
                   4349:                     }
1.191     harris41 4350:                 }
1.148     www      4351:             }
1.232     www      4352: 
1.148     www      4353:          if ($refuri) { 
1.152     www      4354: 	  $refuri=&declutter($refuri);
1.232     www      4355:           my ($match,$cond)=&is_on_map($refuri);
                   4356:             if ($match) {
                   4357:               my $refstatecond=$cond;
1.620     albertel 4358:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4359:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4360:                   $thisallowed.=$1;
1.53      www      4361:                   $uri=$refuri;
                   4362:                   $statecond=$refstatecond;
1.52      www      4363:               }
                   4364:           }
1.148     www      4365:         }
1.29      www      4366:        }
1.52      www      4367:    }
1.29      www      4368: 
1.52      www      4369: #
1.103     harris41 4370: # Gathered now: all privileges that could apply, and condition number
1.52      www      4371: # 
                   4372: #
                   4373: # Full or no access?
                   4374: #
1.29      www      4375: 
1.52      www      4376:     if ($thisallowed=~/F/) {
                   4377: 	return 'F';
                   4378:     }
1.29      www      4379: 
1.52      www      4380:     unless ($thisallowed) {
                   4381:         return '';
                   4382:     }
1.29      www      4383: 
1.52      www      4384: # Restrictions exist, deal with them
                   4385: #
                   4386: #   C:according to course preferences
                   4387: #   R:according to resource settings
                   4388: #   L:unless locked
                   4389: #   X:according to user session state
                   4390: #
                   4391: 
                   4392: # Possibly locked functionality, check all courses
1.54      www      4393: # Locks might take effect only after 10 minutes cache expiration for other
                   4394: # courses, and 2 minutes for current course
1.52      www      4395: 
                   4396:     my $envkey;
                   4397:     if ($thisallowed=~/L/) {
1.620     albertel 4398:         foreach $envkey (keys %env) {
1.54      www      4399:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4400:                my $courseid=$2;
                   4401:                my $roleid=$1.'.'.$2;
1.92      www      4402:                $courseid=~s/^\///;
1.54      www      4403:                my $expiretime=600;
1.620     albertel 4404:                if ($env{'request.role'} eq $roleid) {
1.54      www      4405: 		  $expiretime=120;
                   4406:                }
                   4407: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4408:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4409:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4410: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4411:                }
1.620     albertel 4412:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4413:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4414: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4415:                        &log($env{'user.domain'},$env{'user.name'},
                   4416:                             $env{'user.home'},
1.57      www      4417:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4418:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4419:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4420: 		       return '';
                   4421:                    }
                   4422:                }
1.620     albertel 4423:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4424:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4425: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4426:                        &log($env{'user.domain'},$env{'user.name'},
                   4427:                             $env{'user.home'},
1.57      www      4428:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4429:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4430:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4431: 		       return '';
                   4432:                    }
                   4433:                }
                   4434: 	   }
1.29      www      4435:        }
1.52      www      4436:     }
                   4437:    
                   4438: #
                   4439: # Rest of the restrictions depend on selected course
                   4440: #
                   4441: 
1.620     albertel 4442:     unless ($env{'request.course.id'}) {
1.766     albertel 4443: 	if ($thisallowed eq 'A') {
                   4444: 	    return 'A';
1.814     raeburn  4445:         } elsif ($thisallowed eq 'B') {
                   4446:             return 'B';
1.766     albertel 4447: 	} else {
                   4448: 	    return '1';
                   4449: 	}
1.52      www      4450:     }
1.29      www      4451: 
1.52      www      4452: #
                   4453: # Now user is definitely in a course
                   4454: #
1.53      www      4455: 
                   4456: 
                   4457: # Course preferences
                   4458: 
                   4459:    if ($thisallowed=~/C/) {
1.620     albertel 4460:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4461:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4462:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4463: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4464: 	   if ($priv ne 'pch') { 
                   4465: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4466: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4467: 			$env{'request.course.id'});
                   4468: 	   }
1.237     www      4469:            return '';
                   4470:        }
                   4471: 
1.620     albertel 4472:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4473: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4474: 	   if ($priv ne 'pch') { 
                   4475: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4476: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4477: 			$env{'request.course.id'});
                   4478: 	   }
1.54      www      4479:            return '';
                   4480:        }
1.53      www      4481:    }
                   4482: 
                   4483: # Resource preferences
                   4484: 
                   4485:    if ($thisallowed=~/R/) {
1.620     albertel 4486:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4487:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4488: 	   if ($priv ne 'pch') { 
                   4489: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4490: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4491: 	   }
                   4492: 	   return '';
1.54      www      4493:        }
1.53      www      4494:    }
1.30      www      4495: 
1.246     www      4496: # Restricted by state or randomout?
1.30      www      4497: 
1.52      www      4498:    if ($thisallowed=~/X/) {
1.620     albertel 4499:       if ($env{'acc.randomout'}) {
1.579     albertel 4500: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4501:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4502:             return ''; 
                   4503:          }
1.247     www      4504:       }
                   4505:       if (&condval($statecond)) {
1.52      www      4506: 	 return '2';
                   4507:       } else {
                   4508:          return '';
                   4509:       }
                   4510:    }
1.30      www      4511: 
1.766     albertel 4512:     if ($thisallowed eq 'A') {
                   4513: 	return 'A';
1.814     raeburn  4514:     } elsif ($thisallowed eq 'B') {
                   4515:         return 'B';
1.766     albertel 4516:     }
1.52      www      4517:    return 'F';
1.232     www      4518: }
                   4519: 
1.710     albertel 4520: sub split_uri_for_cond {
                   4521:     my $uri=&deversion(&declutter(shift));
                   4522:     my @uriparts=split(/\//,$uri);
                   4523:     my $filename=pop(@uriparts);
                   4524:     my $pathname=join('/',@uriparts);
                   4525:     return ($pathname,$filename);
                   4526: }
1.232     www      4527: # --------------------------------------------------- Is a resource on the map?
                   4528: 
                   4529: sub is_on_map {
1.710     albertel 4530:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4531:     #Trying to find the conditional for the file
1.620     albertel 4532:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4533: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4534:     if ($match) {
1.289     bowersj2 4535: 	return (1,$1);
                   4536:     } else {
1.434     www      4537: 	return (0,0);
1.289     bowersj2 4538:     }
1.12      www      4539: }
                   4540: 
1.427     www      4541: # --------------------------------------------------------- Get symb from alias
                   4542: 
                   4543: sub get_symb_from_alias {
                   4544:     my $symb=shift;
                   4545:     my ($map,$resid,$url)=&decode_symb($symb);
                   4546: # Already is a symb
                   4547:     if ($url) { return $symb; }
                   4548: # Must be an alias
                   4549:     my $aliassymb='';
                   4550:     my %bighash;
1.620     albertel 4551:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4552:                             &GDBM_READER(),0640)) {
                   4553:         my $rid=$bighash{'mapalias_'.$symb};
                   4554: 	if ($rid) {
                   4555: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4556: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4557: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4558: 	}
                   4559:         untie %bighash;
                   4560:     }
                   4561:     return $aliassymb;
                   4562: }
                   4563: 
1.12      www      4564: # ----------------------------------------------------------------- Define Role
                   4565: 
                   4566: sub definerole {
                   4567:   if (allowed('mcr','/')) {
                   4568:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4569:     foreach my $role (split(':',$sysrole)) {
                   4570: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4571:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4572:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4573: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4574:                return "refused:s:$crole&$cqual"; 
                   4575:             }
                   4576:         }
1.191     harris41 4577:     }
1.800     albertel 4578:     foreach my $role (split(':',$domrole)) {
                   4579: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4580:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4581:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4582: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4583:                return "refused:d:$crole&$cqual"; 
                   4584:             }
                   4585:         }
1.191     harris41 4586:     }
1.800     albertel 4587:     foreach my $role (split(':',$courole)) {
                   4588: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4589:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4590:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4591: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4592:                return "refused:c:$crole&$cqual"; 
                   4593:             }
                   4594:         }
1.191     harris41 4595:     }
1.620     albertel 4596:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4597:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4598: 	        "rolesdef_$rolename=".
                   4599:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4600:     return reply($command,$env{'user.home'});
1.12      www      4601:   } else {
                   4602:     return 'refused';
                   4603:   }
1.105     harris41 4604: }
                   4605: 
                   4606: # ---------------- Make a metadata query against the network of library servers
                   4607: 
                   4608: sub metadata_query {
1.244     matthew  4609:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4610:     my %rhash;
1.845     albertel 4611:     my %libserv = &all_library();
1.244     matthew  4612:     my @server_list = (defined($server_array) ? @$server_array
                   4613:                                               : keys(%libserv) );
                   4614:     for my $server (@server_list) {
1.118     harris41 4615: 	unless ($custom or $customshow) {
                   4616: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4617: 	    $rhash{$server}=$reply;
                   4618: 	}
                   4619: 	else {
                   4620: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4621: 			     &escape($custom).':'.&escape($customshow),
                   4622: 			     $server);
                   4623: 	    $rhash{$server}=$reply;
                   4624: 	}
1.112     harris41 4625:     }
1.118     harris41 4626:     return \%rhash;
1.240     www      4627: }
                   4628: 
                   4629: # ----------------------------------------- Send log queries and wait for reply
                   4630: 
                   4631: sub log_query {
                   4632:     my ($uname,$udom,$query,%filters)=@_;
                   4633:     my $uhome=&homeserver($uname,$udom);
                   4634:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4635:     my $uhost=&hostname($uhome);
1.800     albertel 4636:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4637:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4638:                        $uhome);
1.479     albertel 4639:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4640:     return get_query_reply($queryid);
                   4641: }
                   4642: 
1.818     raeburn  4643: # -------------------------- Update MySQL table for portfolio file
                   4644: 
                   4645: sub update_portfolio_table {
1.821     raeburn  4646:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4647:     my $homeserver = &homeserver($uname,$udom);
                   4648:     my $queryid=
1.821     raeburn  4649:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4650:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4651:     my $reply = &get_query_reply($queryid);
                   4652:     return $reply;
                   4653: }
                   4654: 
1.899     raeburn  4655: # -------------------------- Update MySQL allusers table
                   4656: 
                   4657: sub update_allusers_table {
                   4658:     my ($uname,$udom,$names) = @_;
                   4659:     my $homeserver = &homeserver($uname,$udom);
                   4660:     my $queryid=
                   4661:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4662:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4663:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4664:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4665:                'generation='.&escape($names->{'generation'}).'%%'.
                   4666:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4667:                'id='.&escape($names->{'id'}),$homeserver);
                   4668:     my $reply = &get_query_reply($queryid);
                   4669:     return $reply;
                   4670: }
                   4671: 
1.508     raeburn  4672: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4673: 
                   4674: sub fetch_enrollment_query {
1.511     raeburn  4675:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4676:     my $homeserver;
1.547     raeburn  4677:     my $maxtries = 1;
1.508     raeburn  4678:     if ($context eq 'automated') {
                   4679:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4680:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4681:     } else {
                   4682:         $homeserver = &homeserver($cnum,$dom);
                   4683:     }
1.838     albertel 4684:     my $host=&hostname($homeserver);
1.506     raeburn  4685:     my $cmd = '';
1.800     albertel 4686:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4687:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4688:     }
                   4689:     $cmd =~ s/%%$//;
                   4690:     $cmd = &escape($cmd);
                   4691:     my $query = 'fetchenrollment';
1.620     albertel 4692:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4693:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4694:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4695:         return 'error: '.$queryid;
                   4696:     }
1.506     raeburn  4697:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4698:     my $tries = 1;
                   4699:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4700:         $reply = &get_query_reply($queryid);
                   4701:         $tries ++;
                   4702:     }
1.526     raeburn  4703:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4704:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4705:     } else {
1.901     albertel 4706:         my @responses = split(/:/,$reply);
1.515     raeburn  4707:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4708:             foreach my $line (@responses) {
                   4709:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4710:                 $$replyref{$key} = $value;
                   4711:             }
                   4712:         } else {
1.506     raeburn  4713:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4714:             foreach my $line (@responses) {
                   4715:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4716:                 $$replyref{$key} = $value;
                   4717:                 if ($value > 0) {
1.800     albertel 4718:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4719:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4720:                         my $destname = $pathname.'/'.$filename;
                   4721:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4722:                         if ($xml_classlist =~ /^error/) {
                   4723:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4724:                         } else {
1.506     raeburn  4725:                             if ( open(FILE,">$destname") ) {
                   4726:                                 print FILE &unescape($xml_classlist);
                   4727:                                 close(FILE);
1.526     raeburn  4728:                             } else {
                   4729:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4730:                             }
                   4731:                         }
                   4732:                     }
                   4733:                 }
                   4734:             }
                   4735:         }
                   4736:         return 'ok';
                   4737:     }
                   4738:     return 'error';
                   4739: }
                   4740: 
1.242     www      4741: sub get_query_reply {
                   4742:     my $queryid=shift;
1.240     www      4743:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4744:     my $reply='';
                   4745:     for (1..100) {
                   4746: 	sleep 2;
                   4747:         if (-e $replyfile.'.end') {
1.448     albertel 4748: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4749: 		$reply = join('',<$fh>);
                   4750: 		close($fh);
1.240     www      4751: 	   } else { return 'error: reply_file_error'; }
1.242     www      4752:            return &unescape($reply);
                   4753: 	}
1.240     www      4754:     }
1.242     www      4755:     return 'timeout:'.$queryid;
1.240     www      4756: }
                   4757: 
                   4758: sub courselog_query {
1.241     www      4759: #
                   4760: # possible filters:
                   4761: # url: url or symb
                   4762: # username
                   4763: # domain
                   4764: # action: view, submit, grade
                   4765: # start: timestamp
                   4766: # end: timestamp
                   4767: #
1.240     www      4768:     my (%filters)=@_;
1.620     albertel 4769:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4770:     if ($filters{'url'}) {
                   4771: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4772:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4773:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4774:     }
1.620     albertel 4775:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4776:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4777:     return &log_query($cname,$cdom,'courselog',%filters);
                   4778: }
                   4779: 
                   4780: sub userlog_query {
1.858     raeburn  4781: #
                   4782: # possible filters:
                   4783: # action: log check role
                   4784: # start: timestamp
                   4785: # end: timestamp
                   4786: #
1.240     www      4787:     my ($uname,$udom,%filters)=@_;
                   4788:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4789: }
                   4790: 
1.506     raeburn  4791: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4792: 
                   4793: sub auto_run {
1.508     raeburn  4794:     my ($cnum,$cdom) = @_;
1.876     raeburn  4795:     my $response = 0;
                   4796:     my $settings;
                   4797:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4798:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4799:         $settings = $domconfig{'autoenroll'};
                   4800:         if ($settings->{'run'} eq '1') {
                   4801:             $response = 1;
                   4802:         }
                   4803:     } else {
                   4804:         my $homeserver = &homeserver($cnum,$cdom);
                   4805:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4806:     }
1.506     raeburn  4807:     return $response;
                   4808: }
1.776     albertel 4809: 
1.506     raeburn  4810: sub auto_get_sections {
1.508     raeburn  4811:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4812:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4813:     my @secs = ();
1.511     raeburn  4814:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4815:     unless ($response eq 'refused') {
1.901     albertel 4816:         @secs = split(/:/,$response);
1.506     raeburn  4817:     }
                   4818:     return @secs;
                   4819: }
1.776     albertel 4820: 
1.506     raeburn  4821: sub auto_new_course {
1.508     raeburn  4822:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4823:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4824:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4825:     return $response;
                   4826: }
1.776     albertel 4827: 
1.506     raeburn  4828: sub auto_validate_courseID {
1.508     raeburn  4829:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4830:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4831:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4832:     return $response;
                   4833: }
1.776     albertel 4834: 
1.506     raeburn  4835: sub auto_create_password {
1.873     raeburn  4836:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4837:     my ($homeserver,$response);
1.506     raeburn  4838:     my $create_passwd = 0;
                   4839:     my $authchk = '';
1.873     raeburn  4840:     if ($udom =~ /^$match_domain$/) {
                   4841:         $homeserver = &domain($udom,'primary');
                   4842:     }
                   4843:     if ($homeserver eq '') {
                   4844:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4845:             $homeserver = &homeserver($cnum,$cdom);
                   4846:         }
                   4847:     }
                   4848:     if ($homeserver eq '') {
                   4849:         $authchk = 'nodomain';
1.506     raeburn  4850:     } else {
1.873     raeburn  4851:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4852:         if ($response eq 'refused') {
                   4853:             $authchk = 'refused';
                   4854:         } else {
1.901     albertel 4855:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4856:         }
1.506     raeburn  4857:     }
                   4858:     return ($authparam,$create_passwd,$authchk);
                   4859: }
                   4860: 
1.706     raeburn  4861: sub auto_photo_permission {
                   4862:     my ($cnum,$cdom,$students) = @_;
                   4863:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4864:     my ($outcome,$perm_reqd,$conditions) = 
                   4865: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4866:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4867: 	return (undef,undef);
                   4868:     }
1.706     raeburn  4869:     return ($outcome,$perm_reqd,$conditions);
                   4870: }
                   4871: 
                   4872: sub auto_checkphotos {
                   4873:     my ($uname,$udom,$pid) = @_;
                   4874:     my $homeserver = &homeserver($uname,$udom);
                   4875:     my ($result,$resulttype);
                   4876:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4877: 				   &escape($uname).':'.&escape($pid),
                   4878: 				   $homeserver));
1.709     albertel 4879:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4880: 	return (undef,undef);
                   4881:     }
1.706     raeburn  4882:     if ($outcome) {
                   4883:         ($result,$resulttype) = split(/:/,$outcome);
                   4884:     } 
                   4885:     return ($result,$resulttype);
                   4886: }
                   4887: 
                   4888: sub auto_photochoice {
                   4889:     my ($cnum,$cdom) = @_;
                   4890:     my $homeserver = &homeserver($cnum,$cdom);
                   4891:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4892: 						       &escape($cdom),
                   4893: 						       $homeserver)));
1.709     albertel 4894:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4895: 	return (undef,undef);
                   4896:     }
1.706     raeburn  4897:     return ($update,$comment);
                   4898: }
                   4899: 
                   4900: sub auto_photoupdate {
                   4901:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4902:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4903:     my $host=&hostname($homeserver);
1.706     raeburn  4904:     my $cmd = '';
                   4905:     my $maxtries = 1;
1.800     albertel 4906:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4907:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4908:     }
                   4909:     $cmd =~ s/%%$//;
                   4910:     $cmd = &escape($cmd);
                   4911:     my $query = 'institutionalphotos';
                   4912:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4913:     unless ($queryid=~/^\Q$host\E\_/) {
                   4914:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4915:         return 'error: '.$queryid;
                   4916:     }
                   4917:     my $reply = &get_query_reply($queryid);
                   4918:     my $tries = 1;
                   4919:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4920:         $reply = &get_query_reply($queryid);
                   4921:         $tries ++;
                   4922:     }
                   4923:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4924:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4925:     } else {
                   4926:         my @responses = split(/:/,$reply);
                   4927:         my $outcome = shift(@responses); 
                   4928:         foreach my $item (@responses) {
                   4929:             my ($key,$value) = split(/=/,$item);
                   4930:             $$photo{$key} = $value;
                   4931:         }
                   4932:         return $outcome;
                   4933:     }
                   4934:     return 'error';
                   4935: }
                   4936: 
1.521     raeburn  4937: sub auto_instcode_format {
1.793     albertel 4938:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4939: 	$cat_order) = @_;
1.521     raeburn  4940:     my $courses = '';
1.772     raeburn  4941:     my @homeservers;
1.521     raeburn  4942:     if ($caller eq 'global') {
1.841     albertel 4943: 	my %servers = &get_servers($codedom,'library');
                   4944: 	foreach my $tryserver (keys(%servers)) {
                   4945: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4946: 		push(@homeservers,$tryserver);
                   4947: 	    }
1.584     raeburn  4948:         }
1.521     raeburn  4949:     } else {
1.772     raeburn  4950:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4951:     }
1.793     albertel 4952:     foreach my $code (keys(%{$instcodes})) {
                   4953:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4954:     }
                   4955:     chop($courses);
1.772     raeburn  4956:     my $ok_response = 0;
                   4957:     my $response;
                   4958:     while (@homeservers > 0 && $ok_response == 0) {
                   4959:         my $server = shift(@homeservers); 
                   4960:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4961:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4962:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4963: 		split(/:/,$response);
1.772     raeburn  4964:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4965:             push(@{$codetitles},&str2array($codetitles_str));
                   4966:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4967:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4968:             $ok_response = 1;
                   4969:         }
                   4970:     }
                   4971:     if ($ok_response) {
1.521     raeburn  4972:         return 'ok';
1.772     raeburn  4973:     } else {
                   4974:         return $response;
1.521     raeburn  4975:     }
                   4976: }
                   4977: 
1.792     raeburn  4978: sub auto_instcode_defaults {
                   4979:     my ($domain,$returnhash,$code_order) = @_;
                   4980:     my @homeservers;
1.841     albertel 4981: 
                   4982:     my %servers = &get_servers($domain,'library');
                   4983:     foreach my $tryserver (keys(%servers)) {
                   4984: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4985: 	    push(@homeservers,$tryserver);
                   4986: 	}
1.792     raeburn  4987:     }
1.841     albertel 4988: 
1.792     raeburn  4989:     my $response;
1.841     albertel 4990:     foreach my $server (@homeservers) {
1.792     raeburn  4991:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4992:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4993: 	
                   4994: 	foreach my $pair (split(/\&/,$response)) {
                   4995: 	    my ($name,$value)=split(/\=/,$pair);
                   4996: 	    if ($name eq 'code_order') {
                   4997: 		@{$code_order} = split(/\&/,&unescape($value));
                   4998: 	    } else {
                   4999: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5000: 	    }
                   5001: 	}
                   5002: 	return 'ok';
1.792     raeburn  5003:     }
1.841     albertel 5004: 
                   5005:     return $response;
1.792     raeburn  5006: } 
                   5007: 
1.777     albertel 5008: sub auto_validate_class_sec {
1.918   ! raeburn  5009:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5010:     my $homeserver = &homeserver($cnum,$cdom);
1.918   ! raeburn  5011:     my $ownerlist;
        !          5012:     if (ref($owners) eq 'ARRAY') {
        !          5013:         $ownerlist = join(',',@{$owners});
        !          5014:     } else {
        !          5015:         $ownerlist = $owners;
        !          5016:     }
1.773     raeburn  5017:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918   ! raeburn  5018:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5019:     return $response;
                   5020: }
                   5021: 
1.679     raeburn  5022: # ------------------------------------------------------- Course Group routines
                   5023: 
                   5024: sub get_coursegroups {
1.809     raeburn  5025:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5026:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5027: }
                   5028: 
1.679     raeburn  5029: sub modify_coursegroup {
                   5030:     my ($cdom,$cnum,$groupsettings) = @_;
                   5031:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5032: }
                   5033: 
1.809     raeburn  5034: sub toggle_coursegroup_status {
                   5035:     my ($cdom,$cnum,$group,$action) = @_;
                   5036:     my ($from_namespace,$to_namespace);
                   5037:     if ($action eq 'delete') {
                   5038:         $from_namespace = 'coursegroups';
                   5039:         $to_namespace = 'deleted_groups';
                   5040:     } else {
                   5041:         $from_namespace = 'deleted_groups';
                   5042:         $to_namespace = 'coursegroups';
                   5043:     }
                   5044:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5045:     if (my $tmp = &error(%curr_group)) {
                   5046:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5047:         return ('read error',$tmp);
                   5048:     } else {
                   5049:         my %savedsettings = %curr_group; 
1.809     raeburn  5050:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5051:         my $deloutcome;
                   5052:         if ($result eq 'ok') {
1.809     raeburn  5053:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5054:         } else {
                   5055:             return ('write error',$result);
                   5056:         }
                   5057:         if ($deloutcome eq 'ok') {
                   5058:             return 'ok';
                   5059:         } else {
                   5060:             return ('delete error',$deloutcome);
                   5061:         }
                   5062:     }
                   5063: }
                   5064: 
1.679     raeburn  5065: sub modify_group_roles {
                   5066:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5067:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5068:     my $role = 'gr/'.&escape($userprivs);
                   5069:     my ($uname,$udom) = split(/:/,$user);
                   5070:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5071:     if ($result eq 'ok') {
                   5072:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5073:     }
1.679     raeburn  5074:     return $result;
                   5075: }
                   5076: 
                   5077: sub modify_coursegroup_membership {
                   5078:     my ($cdom,$cnum,$membership) = @_;
                   5079:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5080:     return $result;
                   5081: }
                   5082: 
1.682     raeburn  5083: sub get_active_groups {
                   5084:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5085:     my $now = time;
                   5086:     my %groups = ();
                   5087:     foreach my $key (keys(%env)) {
1.811     albertel 5088:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5089:             my ($start,$end) = split(/\./,$env{$key});
                   5090:             if (($end!=0) && ($end<$now)) { next; }
                   5091:             if (($start!=0) && ($start>$now)) { next; }
                   5092:             if ($1 eq $cdom && $2 eq $cnum) {
                   5093:                 $groups{$3} = $env{$key} ;
                   5094:             }
                   5095:         }
                   5096:     }
                   5097:     return %groups;
                   5098: }
                   5099: 
1.683     raeburn  5100: sub get_group_membership {
                   5101:     my ($cdom,$cnum,$group) = @_;
                   5102:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5103: }
                   5104: 
                   5105: sub get_users_groups {
                   5106:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5107:     my @usersgroups;
1.683     raeburn  5108:     my $cachetime=1800;
                   5109: 
                   5110:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5111:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5112:     if (defined($cached)) {
1.734     albertel 5113:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5114:     } else {  
                   5115:         $grouplist = '';
1.816     raeburn  5116:         my $courseurl = &courseid_to_courseurl($courseid);
                   5117:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5118:         my $access_end = $env{'course.'.$courseid.
                   5119:                               '.default_enrollment_end_date'};
                   5120:         my $now = time;
                   5121:         foreach my $key (keys(%roleshash)) {
                   5122:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5123:                 my $group = $1;
                   5124:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5125:                     my $start = $2;
                   5126:                     my $end = $1;
                   5127:                     if ($start == -1) { next; } # deleted from group
                   5128:                     if (($start!=0) && ($start>$now)) { next; }
                   5129:                     if (($end!=0) && ($end<$now)) {
                   5130:                         if ($access_end && $access_end < $now) {
                   5131:                             if ($access_end - $end < 86400) {
                   5132:                                 push(@usersgroups,$group);
1.733     raeburn  5133:                             }
                   5134:                         }
1.817     raeburn  5135:                         next;
1.733     raeburn  5136:                     }
1.817     raeburn  5137:                     push(@usersgroups,$group);
1.683     raeburn  5138:                 }
                   5139:             }
                   5140:         }
1.817     raeburn  5141:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5142:         $grouplist = join(':',@usersgroups);
                   5143:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5144:     }
1.733     raeburn  5145:     return @usersgroups;
1.683     raeburn  5146: }
                   5147: 
                   5148: sub devalidate_getgroups_cache {
                   5149:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5150:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5151: 
1.683     raeburn  5152:     my $hashid="$udom:$uname:$courseid";
                   5153:     &devalidate_cache_new('getgroups',$hashid);
                   5154: }
                   5155: 
1.12      www      5156: # ------------------------------------------------------------------ Plain Text
                   5157: 
                   5158: sub plaintext {
1.742     raeburn  5159:     my ($short,$type,$cid) = @_;
1.758     albertel 5160:     if ($short =~ /^cr/) {
                   5161: 	return (split('/',$short))[-1];
                   5162:     }
1.742     raeburn  5163:     if (!defined($cid)) {
                   5164:         $cid = $env{'request.course.id'};
                   5165:     }
                   5166:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5167:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5168:                                           '.plaintext'});
                   5169:     }
                   5170:     my %rolenames = (
                   5171:                       Course => 'std',
                   5172:                       Group => 'alt1',
                   5173:                     );
                   5174:     if (defined($type) && 
                   5175:          defined($rolenames{$type}) && 
                   5176:          defined($prp{$short}{$rolenames{$type}})) {
                   5177:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5178:     } else {
                   5179:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5180:     }
1.12      www      5181: }
                   5182: 
                   5183: # ----------------------------------------------------------------- Assign Role
                   5184: 
                   5185: sub assignrole {
1.357     www      5186:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5187:     my $mrole;
                   5188:     if ($role =~ /^cr\//) {
1.393     www      5189:         my $cwosec=$url;
1.811     albertel 5190:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5191: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5192:            &logthis('Refused custom assignrole: '.
                   5193:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5194: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5195:            return 'refused'; 
                   5196:         }
1.21      www      5197:         $mrole='cr';
1.678     raeburn  5198:     } elsif ($role =~ /^gr\//) {
                   5199:         my $cwogrp=$url;
1.811     albertel 5200:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5201:         unless (&allowed('mdg',$cwogrp)) {
                   5202:             &logthis('Refused group assignrole: '.
                   5203:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5204:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5205:             return 'refused';
                   5206:         }
                   5207:         $mrole='gr';
1.21      www      5208:     } else {
1.82      www      5209:         my $cwosec=$url;
1.811     albertel 5210:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5211:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5212:            &logthis('Refused assignrole: '.
                   5213:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5214: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5215:            return 'refused'; 
                   5216:         }
1.21      www      5217:         $mrole=$role;
                   5218:     }
1.620     albertel 5219:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5220:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5221:     if ($end) { $command.='_'.$end; }
1.21      www      5222:     if ($start) {
                   5223: 	if ($end) { 
1.81      www      5224:            $command.='_'.$start; 
1.21      www      5225:         } else {
1.81      www      5226:            $command.='_0_'.$start;
1.21      www      5227:         }
                   5228:     }
1.739     raeburn  5229:     my $origstart = $start;
                   5230:     my $origend = $end;
1.357     www      5231: # actually delete
                   5232:     if ($deleteflag) {
1.373     www      5233: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5234: # modify command to delete the role
1.620     albertel 5235:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5236:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5237: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5238: # set start and finish to negative values for userrolelog
                   5239:            $start=-1;
                   5240:            $end=-1;
                   5241:         }
                   5242:     }
                   5243: # send command
1.349     www      5244:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5245: # log new user role if status is ok
1.349     www      5246:     if ($answer eq 'ok') {
1.663     raeburn  5247: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5248: # for course roles, perform group memberships changes triggered by role change.
                   5249:         unless ($role =~ /^gr/) {
                   5250:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5251:                                              $origstart);
                   5252:         }
1.349     www      5253:     }
                   5254:     return $answer;
1.169     harris41 5255: }
                   5256: 
                   5257: # -------------------------------------------------- Modify user authentication
1.197     www      5258: # Overrides without validation
                   5259: 
1.169     harris41 5260: sub modifyuserauth {
                   5261:     my ($udom,$uname,$umode,$upass)=@_;
                   5262:     my $uhome=&homeserver($uname,$udom);
1.197     www      5263:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5264:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5265:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5266:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5267:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5268: 		     &escape($upass),$uhome);
1.620     albertel 5269:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5270:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5271:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5272:     &log($udom,,$uname,$uhome,
1.620     albertel 5273:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5274:                                      $env{'user.name'}.', '.$umode.
1.197     www      5275:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5276:     unless ($reply eq 'ok') {
1.197     www      5277:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5278: 	return 'error: '.$reply;
                   5279:     }   
1.170     harris41 5280:     return 'ok';
1.80      www      5281: }
                   5282: 
1.81      www      5283: # --------------------------------------------------------------- Modify a user
1.80      www      5284: 
1.81      www      5285: sub modifyuser {
1.206     matthew  5286:     my ($udom,    $uname, $uid,
                   5287:         $umode,   $upass, $first,
                   5288:         $middle,  $last,  $gene,
1.387     www      5289:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5290:     $udom= &LONCAPA::clean_domain($udom);
                   5291:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5292:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5293:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5294: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5295:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5296:                                      ' desiredhome not specified'). 
1.620     albertel 5297:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5298:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5299:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5300: # ----------------------------------------------------------------- Create User
1.406     albertel 5301:     if (($uhome eq 'no_host') && 
                   5302: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5303:         my $unhome='';
1.844     albertel 5304:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5305:             $unhome = $desiredhome;
1.620     albertel 5306: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5307: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5308:         } else { # load balancing routine for determining $unhome
1.81      www      5309:             my $loadm=10000000;
1.841     albertel 5310: 	    my %servers = &get_servers($udom,'library');
                   5311: 	    foreach my $tryserver (keys(%servers)) {
                   5312: 		my $answer=reply('load',$tryserver);
                   5313: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5314: 		    $loadm=$answer;
                   5315: 		    $unhome=$tryserver;
                   5316: 		}
1.80      www      5317: 	    }
                   5318:         }
                   5319:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5320: 	    return 'error: unable to find a home server for '.$uname.
                   5321:                    ' in domain '.$udom;
1.80      www      5322:         }
                   5323:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5324:                          &escape($upass),$unhome);
                   5325: 	unless ($reply eq 'ok') {
                   5326:             return 'error: '.$reply;
                   5327:         }   
1.230     stredwic 5328:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5329:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5330: 	    return 'error: unable verify users home machine.';
1.80      www      5331:         }
1.209     matthew  5332:     }   # End of creation of new user
1.80      www      5333: # ---------------------------------------------------------------------- Add ID
                   5334:     if ($uid) {
                   5335:        $uid=~tr/A-Z/a-z/;
                   5336:        my %uidhash=&idrget($udom,$uname);
1.196     www      5337:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5338:          && (!$forceid)) {
1.80      www      5339: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5340: 	      return 'error: user id "'.$uid.'" does not match '.
                   5341:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5342:           }
                   5343:        } else {
                   5344: 	  &idput($udom,($uname => $uid));
                   5345:        }
                   5346:     }
                   5347: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5348:     my @tmp=&get('environment',
1.899     raeburn  5349: 		   ['firstname','middlename','lastname','generation','id',
                   5350:                     'permanentemail'],
1.134     albertel 5351: 		   $udom,$uname);
1.313     matthew  5352:     my %names;
                   5353:     if ($tmp[0] =~ m/^error:.*/) { 
                   5354:         %names=(); 
                   5355:     } else {
                   5356:         %names = @tmp;
                   5357:     }
1.388     www      5358: #
                   5359: # Make sure to not trash student environment if instructor does not bother
                   5360: # to supply name and email information
                   5361: #
                   5362:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5363:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5364:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5365:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5366:     if ($email) {
                   5367:        $email=~s/[^\w\@\.\-\,]//gs;
                   5368:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5369: 			   $names{'critnotification'} = $email;
                   5370: 			   $names{'permanentemail'} = $email; }
                   5371:     }
1.899     raeburn  5372:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5373:     my $reply = &put('environment', \%names, $udom,$uname);
                   5374:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5375:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5376:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5377:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5378:              $umode.', '.$first.', '.$middle.', '.
                   5379: 	     $last.', '.$gene.' by '.
1.620     albertel 5380:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5381:     return 'ok';
1.80      www      5382: }
                   5383: 
1.81      www      5384: # -------------------------------------------------------------- Modify student
1.80      www      5385: 
1.81      www      5386: sub modifystudent {
                   5387:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5388:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5389:     if (!$cid) {
1.620     albertel 5390: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5391: 	    return 'not_in_class';
                   5392: 	}
1.80      www      5393:     }
                   5394: # --------------------------------------------------------------- Make the user
1.81      www      5395:     my $reply=&modifyuser
1.209     matthew  5396: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5397:          $desiredhome,$email);
1.80      www      5398:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5399:     # This will cause &modify_student_enrollment to get the uid from the
                   5400:     # students environment
                   5401:     $uid = undef if (!$forceid);
1.455     albertel 5402:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5403: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5404:     return $reply;
                   5405: }
                   5406: 
                   5407: sub modify_student_enrollment {
1.515     raeburn  5408:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5409:     my ($cdom,$cnum,$chome);
                   5410:     if (!$cid) {
1.620     albertel 5411: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5412: 	    return 'not_in_class';
                   5413: 	}
1.620     albertel 5414: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5415: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5416:     } else {
                   5417: 	($cdom,$cnum)=split(/_/,$cid);
                   5418:     }
1.620     albertel 5419:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5420:     if (!$chome) {
1.457     raeburn  5421: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5422:     }
1.455     albertel 5423:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5424:     # Make sure the user exists
1.81      www      5425:     my $uhome=&homeserver($uname,$udom);
                   5426:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5427: 	return 'error: no such user';
                   5428:     }
1.297     matthew  5429:     # Get student data if we were not given enough information
                   5430:     if (!defined($first)  || $first  eq '' || 
                   5431:         !defined($last)   || $last   eq '' || 
                   5432:         !defined($uid)    || $uid    eq '' || 
                   5433:         !defined($middle) || $middle eq '' || 
                   5434:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5435:         # They did not supply us with enough data to enroll the student, so
                   5436:         # we need to pick up more information.
1.297     matthew  5437:         my %tmp = &get('environment',
1.294     matthew  5438:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5439:                        ,$udom,$uname);
                   5440: 
1.800     albertel 5441:         #foreach my $key (keys(%tmp)) {
                   5442:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5443:         #}
1.294     matthew  5444:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5445:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5446:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5447:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5448:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5449:     }
1.556     albertel 5450:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5451:     my $reply=cput('classlist',
                   5452: 		   {"$uname:$udom" => 
1.515     raeburn  5453: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5454: 		   $cdom,$cnum);
1.81      www      5455:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5456: 	return 'error: '.$reply;
1.652     albertel 5457:     } else {
                   5458: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5459:     }
1.297     matthew  5460:     # Add student role to user
1.83      www      5461:     my $uurl='/'.$cid;
1.81      www      5462:     $uurl=~s/\_/\//g;
                   5463:     if ($usec) {
                   5464: 	$uurl.='/'.$usec;
                   5465:     }
                   5466:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5467: }
                   5468: 
1.556     albertel 5469: sub format_name {
                   5470:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5471:     my $name;
                   5472:     if ($first ne 'lastname') {
                   5473: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5474:     } else {
                   5475: 	if ($lastname=~/\S/) {
                   5476: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5477: 	    $name=~s/\s+,/,/;
                   5478: 	} else {
                   5479: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5480: 	}
                   5481:     }
                   5482:     $name=~s/^\s+//;
                   5483:     $name=~s/\s+$//;
                   5484:     $name=~s/\s+/ /g;
                   5485:     return $name;
                   5486: }
                   5487: 
1.84      www      5488: # ------------------------------------------------- Write to course preferences
                   5489: 
                   5490: sub writecoursepref {
                   5491:     my ($courseid,%prefs)=@_;
                   5492:     $courseid=~s/^\///;
                   5493:     $courseid=~s/\_/\//g;
                   5494:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5495:     my $chome=homeserver($cnum,$cdomain);
                   5496:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5497: 	return 'error: no such course';
                   5498:     }
                   5499:     my $cstring='';
1.800     albertel 5500:     foreach my $pref (keys(%prefs)) {
                   5501: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5502:     }
1.84      www      5503:     $cstring=~s/\&$//;
                   5504:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5505: }
                   5506: 
                   5507: # ---------------------------------------------------------- Make/modify course
                   5508: 
                   5509: sub createcourse {
1.741     raeburn  5510:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5511:         $course_owner,$crstype)=@_;
1.84      www      5512:     $url=&declutter($url);
                   5513:     my $cid='';
1.264     matthew  5514:     unless (&allowed('ccc',$udom)) {
1.84      www      5515:         return 'refused';
                   5516:     }
                   5517: # ------------------------------------------------------------------- Create ID
1.674     www      5518:    my $uname=int(1+rand(9)).
                   5519:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5520:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5521:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5522: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5523:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5524:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5525:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5526:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5527:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5528:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5529:            return 'error: unable to generate unique course-ID';
                   5530:        } 
                   5531:    }
1.264     matthew  5532: # ------------------------------------------------ Check supplied server name
1.620     albertel 5533:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5534:     if (! &is_library($course_server)) {
1.264     matthew  5535:         return 'error:bad server name '.$course_server;
                   5536:     }
1.84      www      5537: # ------------------------------------------------------------- Make the course
                   5538:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5539:                       $course_server);
1.84      www      5540:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5541:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5542:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5543: 	return 'error: no such course';
                   5544:     }
1.271     www      5545: # ----------------------------------------------------------------- Course made
1.516     raeburn  5546: # log existence
1.918   ! raeburn  5547:     my $newcourse = {
        !          5548:                     $udom.'_'.$uname => {
        !          5549:                                      description => &escape($description),
        !          5550:                                      inst_code   => &escape($inst_code),
        !          5551:                                      owner       => &escape($course_owner),
        !          5552:                                      type        => &escape($crstype),
        !          5553:                                                 },
        !          5554:                     };
        !          5555:     &courseidput($udom,$newcourse);
1.358     www      5556:     &flushcourselogs();
                   5557: # set toplevel url
1.271     www      5558:     my $topurl=$url;
                   5559:     unless ($nonstandard) {
                   5560: # ------------------------------------------ For standard courses, make top url
                   5561:         my $mapurl=&clutter($url);
1.278     www      5562:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5563:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5564: <map>
                   5565: <resource id="1" type="start"></resource>
                   5566: <resource id="2" src="$mapurl"></resource>
                   5567: <resource id="3" type="finish"></resource>
                   5568: <link index="1" from="1" to="2"></link>
                   5569: <link index="2" from="2" to="3"></link>
                   5570: </map>
                   5571: ENDINITMAP
                   5572:         $topurl=&declutter(
1.638     albertel 5573:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5574:                           );
                   5575:     }
                   5576: # ----------------------------------------------------------- Write preferences
1.84      www      5577:     &writecoursepref($udom.'_'.$uname,
                   5578:                      ('description' => $description,
1.271     www      5579:                       'url'         => $topurl));
1.84      www      5580:     return '/'.$udom.'/'.$uname;
                   5581: }
                   5582: 
1.813     albertel 5583: sub is_course {
                   5584:     my ($cdom,$cnum) = @_;
                   5585:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.918   ! raeburn  5586: 				undef,'.',undef,1);
1.813     albertel 5587:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5588:         return 1;
                   5589:     }
                   5590:     return 0;
                   5591: }
                   5592: 
1.21      www      5593: # ---------------------------------------------------------- Assign Custom Role
                   5594: 
                   5595: sub assigncustomrole {
1.357     www      5596:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5597:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5598:                        $end,$start,$deleteflag);
1.21      www      5599: }
                   5600: 
                   5601: # ----------------------------------------------------------------- Revoke Role
                   5602: 
                   5603: sub revokerole {
1.357     www      5604:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5605:     my $now=time;
1.357     www      5606:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5607: }
                   5608: 
                   5609: # ---------------------------------------------------------- Revoke Custom Role
                   5610: 
                   5611: sub revokecustomrole {
1.357     www      5612:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5613:     my $now=time;
1.357     www      5614:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5615:            $deleteflag);
1.17      www      5616: }
                   5617: 
1.533     banghart 5618: # ------------------------------------------------------------ Disk usage
1.535     albertel 5619: sub diskusage {
1.533     banghart 5620:     my ($udom,$uname,$directoryRoot)=@_;
                   5621:     $directoryRoot =~ s/\/$//;
1.535     albertel 5622:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5623:     return $listing;
1.512     banghart 5624: }
                   5625: 
1.566     banghart 5626: sub is_locked {
                   5627:     my ($file_name, $domain, $user) = @_;
                   5628:     my @check;
                   5629:     my $is_locked;
                   5630:     push @check, $file_name;
1.613     albertel 5631:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5632: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5633:     my ($tmp)=keys(%locked);
                   5634:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5635:     
1.566     banghart 5636:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5637:         $is_locked = 'false';
                   5638:         foreach my $entry (@{$locked{$file_name}}) {
                   5639:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5640:                $is_locked = 'true';
                   5641:                last;
1.745     raeburn  5642:            }
                   5643:        }
1.566     banghart 5644:     } else {
                   5645:         $is_locked = 'false';
                   5646:     }
                   5647: }
                   5648: 
1.759     albertel 5649: sub declutter_portfile {
                   5650:     my ($file) = @_;
1.833     albertel 5651:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5652:     return $file;
                   5653: }
                   5654: 
1.559     banghart 5655: # ------------------------------------------------------------- Mark as Read Only
                   5656: 
                   5657: sub mark_as_readonly {
                   5658:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5659:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5660:     my ($tmp)=keys(%current_permissions);
                   5661:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5662:     foreach my $file (@{$files}) {
1.759     albertel 5663: 	$file = &declutter_portfile($file);
1.561     banghart 5664:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5665:     }
1.613     albertel 5666:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5667:     return;
                   5668: }
                   5669: 
1.572     banghart 5670: # ------------------------------------------------------------Save Selected Files
                   5671: 
                   5672: sub save_selected_files {
                   5673:     my ($user, $path, @files) = @_;
                   5674:     my $filename = $user."savedfiles";
1.573     banghart 5675:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5676:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5677:     foreach my $file (@files) {
1.620     albertel 5678:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5679:     }
                   5680:     foreach my $file (@other_files) {
1.574     banghart 5681:         print (OUT $file."\n");
1.572     banghart 5682:     }
1.574     banghart 5683:     close (OUT);
1.572     banghart 5684:     return 'ok';
                   5685: }
                   5686: 
1.574     banghart 5687: sub clear_selected_files {
                   5688:     my ($user) = @_;
                   5689:     my $filename = $user."savedfiles";
                   5690:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5691:     print (OUT undef);
                   5692:     close (OUT);
                   5693:     return ("ok");    
                   5694: }
                   5695: 
1.572     banghart 5696: sub files_in_path {
                   5697:     my ($user, $path) = @_;
                   5698:     my $filename = $user."savedfiles";
                   5699:     my %return_files;
1.574     banghart 5700:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5701:     while (my $line_in = <IN>) {
1.574     banghart 5702:         chomp ($line_in);
                   5703:         my @paths_and_file = split (m!/!, $line_in);
                   5704:         my $file_part = pop (@paths_and_file);
                   5705:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5706:         $path_part.='/';
                   5707:         my $path_and_file = $path_part.$file_part;
                   5708:         if ($path_part eq $path) {
                   5709:             $return_files{$file_part}= 'selected';
                   5710:         }
                   5711:     }
1.574     banghart 5712:     close (IN);
                   5713:     return (\%return_files);
1.572     banghart 5714: }
                   5715: 
                   5716: # called in portfolio select mode, to show files selected NOT in current directory
                   5717: sub files_not_in_path {
                   5718:     my ($user, $path) = @_;
                   5719:     my $filename = $user."savedfiles";
                   5720:     my @return_files;
                   5721:     my $path_part;
1.800     albertel 5722:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5723:     while (my $line = <IN>) {
1.572     banghart 5724:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5725:         my @paths_and_file = split(m|/|, $line);
                   5726:         my $file_part = pop(@paths_and_file);
                   5727:         chomp($file_part);
                   5728:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5729:         $path_part .= '/';
                   5730:         my $path_and_file = $path_part.$file_part;
                   5731:         if ($path_part ne $path) {
1.800     albertel 5732:             push(@return_files, ($path_and_file));
1.572     banghart 5733:         }
                   5734:     }
1.800     albertel 5735:     close(OUT);
1.574     banghart 5736:     return (@return_files);
1.572     banghart 5737: }
                   5738: 
1.745     raeburn  5739: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5740: 
1.745     raeburn  5741: sub get_portfile_permissions {
                   5742:     my ($domain,$user) = @_;
1.613     albertel 5743:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5744:     my ($tmp)=keys(%current_permissions);
                   5745:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5746:     return \%current_permissions;
                   5747: }
                   5748: 
                   5749: #---------------------------------------------Get portfolio file access controls
                   5750: 
1.749     raeburn  5751: sub get_access_controls {
1.745     raeburn  5752:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5753:     my %access;
                   5754:     my $real_file = $file;
                   5755:     $file =~ s/\.meta$//;
1.745     raeburn  5756:     if (defined($file)) {
1.749     raeburn  5757:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5758:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5759:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5760:             }
                   5761:         }
1.745     raeburn  5762:     } else {
1.749     raeburn  5763:         foreach my $key (keys(%{$current_permissions})) {
                   5764:             if ($key =~ /\0accesscontrol$/) {
                   5765:                 if (defined($group)) {
                   5766:                     if ($key !~ m-^\Q$group\E/-) {
                   5767:                         next;
                   5768:                     }
                   5769:                 }
                   5770:                 my ($fullpath) = split(/\0/,$key);
                   5771:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5772:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5773:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5774:                     }
                   5775:                 }
                   5776:             }
                   5777:         }
                   5778:     }
                   5779:     return %access;
                   5780: }
                   5781: 
                   5782: sub modify_access_controls {
                   5783:     my ($file_name,$changes,$domain,$user)=@_;
                   5784:     my ($outcome,$deloutcome);
                   5785:     my %store_permissions;
                   5786:     my %new_values;
                   5787:     my %new_control;
                   5788:     my %translation;
                   5789:     my @deletions = ();
                   5790:     my $now = time;
                   5791:     if (exists($$changes{'activate'})) {
                   5792:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5793:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5794:             my $numnew = scalar(@newitems);
                   5795:             for (my $i=0; $i<$numnew; $i++) {
                   5796:                 my $newkey = $newitems[$i];
                   5797:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5798:                 if ($newkey =~ /^\d+:/) { 
                   5799:                     $newkey =~ s/^(\d+)/$newid/;
                   5800:                     $translation{$1} = $newid;
                   5801:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5802:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5803:                     $translation{$1} = $newid;
                   5804:                 }
1.749     raeburn  5805:                 $new_values{$file_name."\0".$newkey} = 
                   5806:                                           $$changes{'activate'}{$newitems[$i]};
                   5807:                 $new_control{$newkey} = $now;
                   5808:             }
                   5809:         }
                   5810:     }
                   5811:     my %todelete;
                   5812:     my %changed_items;
                   5813:     foreach my $action ('delete','update') {
                   5814:         if (exists($$changes{$action})) {
                   5815:             if (ref($$changes{$action}) eq 'HASH') {
                   5816:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5817:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5818:                     if ($action eq 'delete') { 
                   5819:                         $todelete{$itemnum} = 1;
                   5820:                     } else {
                   5821:                         $changed_items{$itemnum} = $key;
                   5822:                     }
                   5823:                 }
1.745     raeburn  5824:             }
                   5825:         }
1.749     raeburn  5826:     }
                   5827:     # get lock on access controls for file.
                   5828:     my $lockhash = {
                   5829:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5830:                                                        ':'.$env{'user.domain'},
                   5831:                    }; 
                   5832:     my $tries = 0;
                   5833:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5834:    
                   5835:     while (($gotlock ne 'ok') && $tries <3) {
                   5836:         $tries ++;
                   5837:         sleep 1;
                   5838:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5839:     }
                   5840:     if ($gotlock eq 'ok') {
                   5841:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5842:         my ($tmp)=keys(%curr_permissions);
                   5843:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5844:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5845:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5846:             if (ref($curr_controls) eq 'HASH') {
                   5847:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5848:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5849:                     if (defined($todelete{$itemnum})) {
                   5850:                         push(@deletions,$file_name."\0".$control_item);
                   5851:                     } else {
                   5852:                         if (defined($changed_items{$itemnum})) {
                   5853:                             $new_control{$changed_items{$itemnum}} = $now;
                   5854:                             push(@deletions,$file_name."\0".$control_item);
                   5855:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5856:                         } else {
                   5857:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5858:                         }
                   5859:                     }
1.745     raeburn  5860:                 }
                   5861:             }
                   5862:         }
1.749     raeburn  5863:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5864:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5865:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5866:         #  remove lock
                   5867:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5868:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5869:         my ($file,$group);
                   5870:         if (&is_course($domain,$user)) {
                   5871:             ($group,$file) = split(/\//,$file_name,2);
                   5872:         } else {
                   5873:             $file = $file_name;
                   5874:         }
                   5875:         my $sqlresult =
                   5876:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5877:                                     $group);
1.749     raeburn  5878:     } else {
                   5879:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5880:     }
1.749     raeburn  5881:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5882: }
                   5883: 
1.827     raeburn  5884: sub make_public_indefinitely {
                   5885:     my ($requrl) = @_;
                   5886:     my $now = time;
                   5887:     my $action = 'activate';
                   5888:     my $aclnum = 0;
                   5889:     if (&is_portfolio_url($requrl)) {
                   5890:         my (undef,$udom,$unum,$file_name,$group) =
                   5891:             &parse_portfolio_url($requrl);
                   5892:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5893:         my %access_controls = &get_access_controls($current_perms,
                   5894:                                                    $group,$file_name);
                   5895:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5896:             my ($num,$scope,$end,$start) = 
                   5897:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5898:             if ($scope eq 'public') {
                   5899:                 if ($start <= $now && $end == 0) {
                   5900:                     $action = 'none';
                   5901:                 } else {
                   5902:                     $action = 'update';
                   5903:                     $aclnum = $num;
                   5904:                 }
                   5905:                 last;
                   5906:             }
                   5907:         }
                   5908:         if ($action eq 'none') {
                   5909:              return 'ok';
                   5910:         } else {
                   5911:             my %changes;
                   5912:             my $newend = 0;
                   5913:             my $newstart = $now;
                   5914:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5915:             $changes{$action}{$newkey} = {
                   5916:                 type => 'public',
                   5917:                 time => {
                   5918:                     start => $newstart,
                   5919:                     end   => $newend,
                   5920:                 },
                   5921:             };
                   5922:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5923:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5924:             return $outcome;
                   5925:         }
                   5926:     } else {
                   5927:         return 'invalid';
                   5928:     }
                   5929: }
                   5930: 
1.745     raeburn  5931: #------------------------------------------------------Get Marked as Read Only
                   5932: 
                   5933: sub get_marked_as_readonly {
                   5934:     my ($domain,$user,$what,$group) = @_;
                   5935:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5936:     my @readonly_files;
1.629     banghart 5937:     my $cmp1=$what;
                   5938:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5939:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5940:         if (defined($group)) {
                   5941:             if ($file_name !~ m-^\Q$group\E/-) {
                   5942:                 next;
                   5943:             }
                   5944:         }
1.561     banghart 5945:         if (ref($value) eq "ARRAY"){
                   5946:             foreach my $stored_what (@{$value}) {
1.629     banghart 5947:                 my $cmp2=$stored_what;
1.759     albertel 5948:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5949:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5950:                 }
1.629     banghart 5951:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5952:                     push(@readonly_files, $file_name);
1.745     raeburn  5953:                     last;
1.563     banghart 5954:                 } elsif (!defined($what)) {
                   5955:                     push(@readonly_files, $file_name);
1.745     raeburn  5956:                     last;
1.561     banghart 5957:                 }
                   5958:             }
1.745     raeburn  5959:         }
1.561     banghart 5960:     }
                   5961:     return @readonly_files;
                   5962: }
1.577     banghart 5963: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5964: 
1.577     banghart 5965: sub get_marked_as_readonly_hash {
1.745     raeburn  5966:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5967:     my %readonly_files;
1.745     raeburn  5968:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5969:         if (defined($group)) {
                   5970:             if ($file_name !~ m-^\Q$group\E/-) {
                   5971:                 next;
                   5972:             }
                   5973:         }
1.577     banghart 5974:         if (ref($value) eq "ARRAY"){
                   5975:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5976:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5977:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5978:                         if ($lock_descriptor eq 'graded') {
                   5979:                             $readonly_files{$file_name} = 'graded';
                   5980:                         } elsif ($lock_descriptor eq 'handback') {
                   5981:                             $readonly_files{$file_name} = 'handback';
                   5982:                         } else {
                   5983:                             if (!exists($readonly_files{$file_name})) {
                   5984:                                 $readonly_files{$file_name} = 'locked';
                   5985:                             }
                   5986:                         }
1.745     raeburn  5987:                     }
1.750     banghart 5988:                 } 
1.577     banghart 5989:             }
                   5990:         } 
                   5991:     }
                   5992:     return %readonly_files;
                   5993: }
1.559     banghart 5994: # ------------------------------------------------------------ Unmark as Read Only
                   5995: 
                   5996: sub unmark_as_readonly {
1.629     banghart 5997:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5998:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5999:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6000:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6001:     my $symb_crs = $what;
                   6002:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6003:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6004:     my ($tmp)=keys(%current_permissions);
                   6005:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6006:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6007:     foreach my $file (@readonly_files) {
1.759     albertel 6008: 	my $clean_file = &declutter_portfile($file);
                   6009: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6010: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6011:         my @new_locks;
                   6012:         my @del_keys;
                   6013:         if (ref($current_locks) eq "ARRAY"){
                   6014:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6015:                 my $compare=$locker;
1.749     raeburn  6016:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6017:                     $compare=join('',@{$locker});
1.746     raeburn  6018:                     if ($compare ne $symb_crs) {
                   6019:                         push(@new_locks, $locker);
                   6020:                     }
1.563     banghart 6021:                 }
                   6022:             }
1.650     albertel 6023:             if (scalar(@new_locks) > 0) {
1.563     banghart 6024:                 $current_permissions{$file} = \@new_locks;
                   6025:             } else {
                   6026:                 push(@del_keys, $file);
1.613     albertel 6027:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6028:                 delete($current_permissions{$file});
1.563     banghart 6029:             }
                   6030:         }
1.561     banghart 6031:     }
1.613     albertel 6032:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6033:     return;
                   6034: }
1.512     banghart 6035: 
1.17      www      6036: # ------------------------------------------------------------ Directory lister
                   6037: 
                   6038: sub dirlist {
1.253     stredwic 6039:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   6040: 
1.18      www      6041:     $uri=~s/^\///;
                   6042:     $uri=~s/\/$//;
1.253     stredwic 6043:     my ($udom, $uname);
                   6044:     (undef,$udom,$uname)=split(/\//,$uri);
                   6045:     if(defined($userdomain)) {
                   6046:         $udom = $userdomain;
                   6047:     }
                   6048:     if(defined($username)) {
                   6049:         $uname = $username;
                   6050:     }
                   6051: 
                   6052:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6053:     if(defined($alternateDirectoryRoot)) {
                   6054:         $dirRoot = $alternateDirectoryRoot;
                   6055:         $dirRoot =~ s/\/$//;
1.751     banghart 6056:     }
1.253     stredwic 6057: 
                   6058:     if($udom) {
                   6059:         if($uname) {
1.800     albertel 6060:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6061: 				 &homeserver($uname,$udom));
1.605     matthew  6062:             my @listing_results;
                   6063:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6064:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6065: 				  &homeserver($uname,$udom));
1.605     matthew  6066:                 @listing_results = split(/:/,$listing);
                   6067:             } else {
                   6068:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6069:             }
                   6070:             return @listing_results;
1.253     stredwic 6071:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6072:             my %allusers;
1.841     albertel 6073: 	    my %servers = &get_servers($udom,'library');
                   6074: 	    foreach my $tryserver (keys(%servers)) {
                   6075: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6076: 				     $udom, $tryserver);
                   6077: 		my @listing_results;
                   6078: 		if ($listing eq 'unknown_cmd') {
                   6079: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6080: 				      $udom, $tryserver);
                   6081: 		    @listing_results = split(/:/,$listing);
                   6082: 		} else {
                   6083: 		    @listing_results =
                   6084: 			map { &unescape($_); } split(/:/,$listing);
                   6085: 		}
                   6086: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6087: 		    $listing_results[0] ne 'empty'       &&
                   6088: 		    $listing_results[0] ne 'con_lost') {
                   6089: 		    foreach my $line (@listing_results) {
                   6090: 			my ($entry) = split(/&/,$line,2);
                   6091: 			$allusers{$entry} = 1;
                   6092: 		    }
                   6093: 		}
1.253     stredwic 6094:             }
                   6095:             my $alluserstr='';
1.800     albertel 6096:             foreach my $user (sort(keys(%allusers))) {
                   6097:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6098:             }
                   6099:             $alluserstr=~s/:$//;
                   6100:             return split(/:/,$alluserstr);
                   6101:         } else {
1.800     albertel 6102:             return ('missing user name');
1.253     stredwic 6103:         }
                   6104:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6105:         my @all_domains = sort(&all_domains());
                   6106:          foreach my $domain (@all_domains) {
                   6107:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6108:          }
                   6109:          return @all_domains;
                   6110:      } else {
1.800     albertel 6111:         return ('missing domain');
1.275     stredwic 6112:     }
                   6113: }
                   6114: 
                   6115: # --------------------------------------------- GetFileTimestamp
                   6116: # This function utilizes dirlist and returns the date stamp for
                   6117: # when it was last modified.  It will also return an error of -1
                   6118: # if an error occurs
                   6119: 
1.410     matthew  6120: ##
                   6121: ## FIXME: This subroutine assumes its caller knows something about the
                   6122: ## directory structure of the home server for the student ($root).
                   6123: ## Not a good assumption to make.  Since this is for looking up files
                   6124: ## in user directories, the full path should be constructed by lond, not
                   6125: ## whatever machine we request data from.
                   6126: ##
1.275     stredwic 6127: sub GetFileTimestamp {
                   6128:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6129:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6130:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6131:     my $subdir=$studentName.'__';
                   6132:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6133:     my $proname="$studentDomain/$subdir/$studentName";
                   6134:     $proname .= '/'.$filename;
1.375     matthew  6135:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6136:                                               $studentName, $root);
1.275     stredwic 6137:     my @stats = split('&', $fileStat);
                   6138:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6139:         # @stats contains first the filename, then the stat output
                   6140:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6141:     } else {
                   6142:         return -1;
1.253     stredwic 6143:     }
1.26      www      6144: }
                   6145: 
1.712     albertel 6146: sub stat_file {
                   6147:     my ($uri) = @_;
1.787     albertel 6148:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6149: 
1.712     albertel 6150:     my ($udom,$uname,$file,$dir);
                   6151:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6152: 	($udom,$uname,$file) =
1.811     albertel 6153: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6154: 	$file = 'userfiles/'.$file;
1.740     www      6155: 	$dir = &propath($udom,$uname);
1.712     albertel 6156:     }
                   6157:     if ($uri =~ m-^/res/-) {
                   6158: 	($udom,$uname) = 
1.807     albertel 6159: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6160: 	$file = $uri;
                   6161:     }
                   6162: 
                   6163:     if (!$udom || !$uname || !$file) {
                   6164: 	# unable to handle the uri
                   6165: 	return ();
                   6166:     }
                   6167: 
                   6168:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6169:     my @stats = split('&', $result);
1.721     banghart 6170:     
1.712     albertel 6171:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6172: 	shift(@stats); #filename is first
                   6173: 	return @stats;
                   6174:     }
                   6175:     return ();
                   6176: }
                   6177: 
1.26      www      6178: # -------------------------------------------------------- Value of a Condition
                   6179: 
1.713     albertel 6180: # gets the value of a specific preevaluated condition
                   6181: #    stored in the string  $env{user.state.<cid>}
                   6182: # or looks up a condition reference in the bighash and if if hasn't
                   6183: # already been evaluated recurses into docondval to get the value of
                   6184: # the condition, then memoizing it to 
                   6185: #   $env{user.state.<cid>.<condition>}
1.40      www      6186: sub directcondval {
                   6187:     my $number=shift;
1.620     albertel 6188:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6189: 	&Apache::lonuserstate::evalstate();
                   6190:     }
1.713     albertel 6191:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6192: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6193:     } elsif ($number =~ /^_/) {
                   6194: 	my $sub_condition;
                   6195: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6196: 		&GDBM_READER(),0640)) {
                   6197: 	    $sub_condition=$bighash{'conditions'.$number};
                   6198: 	    untie(%bighash);
                   6199: 	}
                   6200: 	my $value = &docondval($sub_condition);
                   6201: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6202: 	return $value;
                   6203:     }
1.620     albertel 6204:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6205:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6206:     } else {
                   6207:        return 2;
                   6208:     }
                   6209: }
                   6210: 
1.713     albertel 6211: # get the collection of conditions for this resource
1.26      www      6212: sub condval {
                   6213:     my $condidx=shift;
1.54      www      6214:     my $allpathcond='';
1.713     albertel 6215:     foreach my $cond (split(/\|/,$condidx)) {
                   6216: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6217: 	    $allpathcond.=
                   6218: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6219: 	}
1.191     harris41 6220:     }
1.54      www      6221:     $allpathcond=~s/\|$//;
1.713     albertel 6222:     return &docondval($allpathcond);
                   6223: }
                   6224: 
                   6225: #evaluates an expression of conditions
                   6226: sub docondval {
                   6227:     my ($allpathcond) = @_;
                   6228:     my $result=0;
                   6229:     if ($env{'request.course.id'}
                   6230: 	&& defined($allpathcond)) {
                   6231: 	my $operand='|';
                   6232: 	my @stack;
                   6233: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6234: 	    if ($chunk eq '(') {
                   6235: 		push @stack,($operand,$result);
                   6236: 	    } elsif ($chunk eq ')') {
                   6237: 		my $before=pop @stack;
                   6238: 		if (pop @stack eq '&') {
                   6239: 		    $result=$result>$before?$before:$result;
                   6240: 		} else {
                   6241: 		    $result=$result>$before?$result:$before;
                   6242: 		}
                   6243: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6244: 		$operand=$chunk;
                   6245: 	    } else {
                   6246: 		my $new=directcondval($chunk);
                   6247: 		if ($operand eq '&') {
                   6248: 		    $result=$result>$new?$new:$result;
                   6249: 		} else {
                   6250: 		    $result=$result>$new?$result:$new;
                   6251: 		}
                   6252: 	    }
                   6253: 	}
1.26      www      6254:     }
                   6255:     return $result;
1.421     albertel 6256: }
                   6257: 
                   6258: # ---------------------------------------------------- Devalidate courseresdata
                   6259: 
                   6260: sub devalidatecourseresdata {
                   6261:     my ($coursenum,$coursedomain)=@_;
                   6262:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6263:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6264: }
                   6265: 
1.763     www      6266: 
1.200     www      6267: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6268: #
                   6269: #  Parameters:
                   6270: #      $coursenum    - Number of the course.
                   6271: #      $coursedomain - Domain at which the course was created.
                   6272: #  Returns:
                   6273: #     A hash of the course parameters along (I think) with timestamps
                   6274: #     and version info.
1.877     foxr     6275: 
1.624     albertel 6276: sub get_courseresdata {
                   6277:     my ($coursenum,$coursedomain)=@_;
1.200     www      6278:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6279:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6280:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6281:     my %dumpreply;
1.417     albertel 6282:     unless (defined($cached)) {
1.624     albertel 6283: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6284: 	$result=\%dumpreply;
1.251     albertel 6285: 	my ($tmp) = keys(%dumpreply);
                   6286: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6287: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6288: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6289: 	    return $tmp;
1.416     albertel 6290: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6291: 	    $result=undef;
1.599     albertel 6292: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6293: 	}
                   6294:     }
1.624     albertel 6295:     return $result;
                   6296: }
                   6297: 
1.633     albertel 6298: sub devalidateuserresdata {
                   6299:     my ($uname,$udom)=@_;
                   6300:     my $hashid="$udom:$uname";
                   6301:     &devalidate_cache_new('userres',$hashid);
                   6302: }
                   6303: 
1.624     albertel 6304: sub get_userresdata {
                   6305:     my ($uname,$udom)=@_;
                   6306:     #most student don\'t have any data set, check if there is some data
                   6307:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6308: 
                   6309:     my $hashid="$udom:$uname";
                   6310:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6311:     if (!defined($cached)) {
                   6312: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6313: 	$result=\%resourcedata;
                   6314: 	&do_cache_new('userres',$hashid,$result,600);
                   6315:     }
                   6316:     my ($tmp)=keys(%$result);
                   6317:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6318: 	return $result;
                   6319:     }
                   6320:     #error 2 occurs when the .db doesn't exist
                   6321:     if ($tmp!~/error: 2 /) {
1.672     albertel 6322: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6323: 		 " Trying to get resource data for ".
                   6324: 		 $uname." at ".$udom.": ".
                   6325: 		 $tmp."</font>");
                   6326:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6327: 	#&EXT_cache_set($udom,$uname);
                   6328: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6329: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6330:     }
                   6331:     return $tmp;
                   6332: }
1.879     foxr     6333: #----------------------------------------------- resdata - return resource data
                   6334: #  Purpose:
                   6335: #    Return resource data for either users or for a course.
                   6336: #  Parameters:
                   6337: #     $name      - Course/user name.
                   6338: #     $domain    - Name of the domain the user/course is registered on.
                   6339: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6340: #     @which     - Array of names of resources desired.
                   6341: #  Returns:
                   6342: #     The value of the first reasource in @which that is found in the
                   6343: #     resource hash.
                   6344: #  Exceptional Conditions:
                   6345: #     If the $type passed in is not valid (not the string 'course' or 
                   6346: #     'user', an undefined  reference is returned.
                   6347: #     If none of the resources are found, an undef is returned
1.624     albertel 6348: sub resdata {
                   6349:     my ($name,$domain,$type,@which)=@_;
                   6350:     my $result;
                   6351:     if ($type eq 'course') {
                   6352: 	$result=&get_courseresdata($name,$domain);
                   6353:     } elsif ($type eq 'user') {
                   6354: 	$result=&get_userresdata($name,$domain);
                   6355:     }
                   6356:     if (!ref($result)) { return $result; }    
1.251     albertel 6357:     foreach my $item (@which) {
1.417     albertel 6358: 	if (defined($result->{$item})) {
                   6359: 	    return $result->{$item};
1.251     albertel 6360: 	}
1.250     albertel 6361:     }
1.291     albertel 6362:     return undef;
1.200     www      6363: }
                   6364: 
1.379     matthew  6365: #
                   6366: # EXT resource caching routines
                   6367: #
                   6368: 
                   6369: sub clear_EXT_cache_status {
1.383     albertel 6370:     &delenv('cache.EXT.');
1.379     matthew  6371: }
                   6372: 
                   6373: sub EXT_cache_status {
                   6374:     my ($target_domain,$target_user) = @_;
1.383     albertel 6375:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6376:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6377:         # We know already the user has no data
                   6378:         return 1;
                   6379:     } else {
                   6380:         return 0;
                   6381:     }
                   6382: }
                   6383: 
                   6384: sub EXT_cache_set {
                   6385:     my ($target_domain,$target_user) = @_;
1.383     albertel 6386:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6387:     #&appenv($cachename => time);
1.379     matthew  6388: }
                   6389: 
1.28      www      6390: # --------------------------------------------------------- Value of a Variable
1.58      www      6391: sub EXT {
1.715     albertel 6392: 
1.395     albertel 6393:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6394:     unless ($varname) { return ''; }
1.218     albertel 6395:     #get real user name/domain, courseid and symb
                   6396:     my $courseid;
1.359     albertel 6397:     my $publicuser;
1.427     www      6398:     if ($symbparm) {
                   6399: 	$symbparm=&get_symb_from_alias($symbparm);
                   6400:     }
1.218     albertel 6401:     if (!($uname && $udom)) {
1.790     albertel 6402:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6403:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6404:     } else {
1.620     albertel 6405: 	$courseid=$env{'request.course.id'};
1.218     albertel 6406:     }
1.48      www      6407:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6408:     my $rest;
1.320     albertel 6409:     if (defined($therest[0])) {
1.48      www      6410:        $rest=join('.',@therest);
                   6411:     } else {
                   6412:        $rest='';
                   6413:     }
1.320     albertel 6414: 
1.57      www      6415:     my $qualifierrest=$qualifier;
                   6416:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6417:     my $spacequalifierrest=$space;
                   6418:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6419:     if ($realm eq 'user') {
1.48      www      6420: # --------------------------------------------------------------- user.resource
                   6421: 	if ($space eq 'resource') {
1.651     albertel 6422: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6423: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6424: 		 &&
1.744     albertel 6425: 		 ($symbparm eq &symbread()) ) {	
                   6426: 		# if we are in the middle of processing the resource the
                   6427: 		# get the value we are planning on committing
                   6428:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6429:                     return $Apache::lonhomework::results{$qualifierrest};
                   6430:                 } else {
                   6431:                     return $Apache::lonhomework::history{$qualifierrest};
                   6432:                 }
1.335     albertel 6433: 	    } else {
1.359     albertel 6434: 		my %restored;
1.620     albertel 6435: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6436: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6437: 		} else {
                   6438: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6439: 		}
1.335     albertel 6440: 		return $restored{$qualifierrest};
                   6441: 	    }
1.48      www      6442: # ----------------------------------------------------------------- user.access
                   6443:         } elsif ($space eq 'access') {
1.218     albertel 6444: 	    # FIXME - not supporting calls for a specific user
1.48      www      6445:             return &allowed($qualifier,$rest);
                   6446: # ------------------------------------------ user.preferences, user.environment
                   6447:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6448: 	    if (($uname eq $env{'user.name'}) &&
                   6449: 		($udom eq $env{'user.domain'})) {
                   6450: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6451: 	    } else {
1.359     albertel 6452: 		my %returnhash;
                   6453: 		if (!$publicuser) {
                   6454: 		    %returnhash=&userenvironment($udom,$uname,
                   6455: 						 $qualifierrest);
                   6456: 		}
1.218     albertel 6457: 		return $returnhash{$qualifierrest};
                   6458: 	    }
1.48      www      6459: # ----------------------------------------------------------------- user.course
                   6460:         } elsif ($space eq 'course') {
1.218     albertel 6461: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6462:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6463: # ------------------------------------------------------------------- user.role
                   6464:         } elsif ($space eq 'role') {
1.218     albertel 6465: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6466:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6467:             if ($qualifier eq 'value') {
                   6468: 		return $role;
                   6469:             } elsif ($qualifier eq 'extent') {
                   6470:                 return $where;
                   6471:             }
                   6472: # ----------------------------------------------------------------- user.domain
                   6473:         } elsif ($space eq 'domain') {
1.218     albertel 6474:             return $udom;
1.48      www      6475: # ------------------------------------------------------------------- user.name
                   6476:         } elsif ($space eq 'name') {
1.218     albertel 6477:             return $uname;
1.48      www      6478: # ---------------------------------------------------- Any other user namespace
1.29      www      6479:         } else {
1.359     albertel 6480: 	    my %reply;
                   6481: 	    if (!$publicuser) {
                   6482: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6483: 	    }
                   6484: 	    return $reply{$qualifierrest};
1.48      www      6485:         }
1.236     www      6486:     } elsif ($realm eq 'query') {
                   6487: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6488:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6489: 						[$spacequalifierrest]);
1.620     albertel 6490: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6491:    } elsif ($realm eq 'request') {
1.48      www      6492: # ------------------------------------------------------------- request.browser
                   6493:         if ($space eq 'browser') {
1.430     www      6494: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6495: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6496: 		    return 1;
                   6497: 		} else {
                   6498: 		    return 0;
                   6499: 		}
                   6500: 	    } else {
1.620     albertel 6501: 		return $env{'browser.'.$qualifier};
1.430     www      6502: 	    }
1.57      www      6503: # ------------------------------------------------------------ request.filename
                   6504:         } else {
1.620     albertel 6505:             return $env{'request.'.$spacequalifierrest};
1.29      www      6506:         }
1.28      www      6507:     } elsif ($realm eq 'course') {
1.48      www      6508: # ---------------------------------------------------------- course.description
1.620     albertel 6509:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6510:     } elsif ($realm eq 'resource') {
1.165     www      6511: 
1.620     albertel 6512: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6513: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6514: 	}
1.693     albertel 6515: 
                   6516: 	if ($space eq 'title') {
                   6517: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6518: 	    return &gettitle($symbparm);
                   6519: 	}
                   6520: 	
                   6521: 	if ($space eq 'map') {
                   6522: 	    my ($map) = &decode_symb($symbparm);
                   6523: 	    return &symbread($map);
                   6524: 	}
1.905     albertel 6525: 	if ($space eq 'filename') {
                   6526: 	    if ($symbparm) {
                   6527: 		return &clutter((&decode_symb($symbparm))[2]);
                   6528: 	    }
                   6529: 	    return &hreflocation('',$env{'request.filename'});
                   6530: 	}
1.693     albertel 6531: 
                   6532: 	my ($section, $group, @groups);
1.593     albertel 6533: 	my ($courselevelm,$courselevel);
1.539     albertel 6534: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6535: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6536: 
1.218     albertel 6537: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6538: 
1.60      www      6539: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6540: 	    my $symbp=$symbparm;
1.735     albertel 6541: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6542: 
                   6543: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6544: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6545: 
1.620     albertel 6546: 	    if (($env{'user.name'} eq $uname) &&
                   6547: 		($env{'user.domain'} eq $udom)) {
                   6548: 		$section=$env{'request.course.sec'};
1.733     raeburn  6549:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6550:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6551: 	    } else {
1.539     albertel 6552: 		if (! defined($usection)) {
1.551     albertel 6553: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6554: 		} else {
                   6555: 		    $section = $usection;
                   6556: 		}
1.733     raeburn  6557:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6558: 	    }
                   6559: 
                   6560: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6561: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6562: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6563: 
1.593     albertel 6564: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6565: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6566: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6567: 
1.60      www      6568: # ----------------------------------------------------------- first, check user
1.624     albertel 6569: 
                   6570: 	    my $userreply=&resdata($uname,$udom,'user',
                   6571: 				       ($courselevelr,$courselevelm,
                   6572: 					$courselevel));
                   6573: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6574: 
1.594     albertel 6575: # ------------------------------------------------ second, check some of course
1.684     raeburn  6576:             my $coursereply;
1.691     raeburn  6577:             if (@groups > 0) {
                   6578:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6579:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6580:                 if (defined($coursereply)) { return $coursereply; }
                   6581:             }
1.96      www      6582: 
1.684     raeburn  6583: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6584: 				     $env{'course.'.$courseid.'.domain'},
                   6585: 				     'course',
                   6586: 				     ($seclevelr,$seclevelm,$seclevel,
                   6587: 				      $courselevelr));
1.287     albertel 6588: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6589: 
1.60      www      6590: # ------------------------------------------------------ third, check map parms
1.218     albertel 6591: 	    my %parmhash=();
                   6592: 	    my $thisparm='';
                   6593: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6594: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6595: 		    &GDBM_READER(),0640)) {
1.218     albertel 6596: 		$thisparm=$parmhash{$symbparm};
                   6597: 		untie(%parmhash);
                   6598: 	    }
                   6599: 	    if ($thisparm) { return $thisparm; }
                   6600: 	}
1.594     albertel 6601: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6602: 
1.218     albertel 6603: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6604: 	my $filename;
                   6605: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6606: 	if ($symbparm) {
1.409     www      6607: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6608: 	} else {
1.620     albertel 6609: 	    $filename=$env{'request.filename'};
1.282     albertel 6610: 	}
                   6611: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6612: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6613: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6614: 	if (defined($metadata)) { return $metadata; }
1.142     www      6615: 
1.594     albertel 6616: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6617: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6618: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6619: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6620: 				     $env{'course.'.$courseid.'.domain'},
                   6621: 				     'course',
                   6622: 				     ($courselevelm,$courselevel));
1.593     albertel 6623: 	    if (defined($coursereply)) { return $coursereply; }
                   6624: 	}
1.145     www      6625: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6626: 	unless ($space eq '0') {
1.336     albertel 6627: 	    my @parts=split(/_/,$space);
                   6628: 	    my $id=pop(@parts);
                   6629: 	    my $part=join('_',@parts);
                   6630: 	    if ($part eq '') { $part='0'; }
                   6631: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6632: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6633: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6634: 	}
1.395     albertel 6635: 	if ($recurse) { return undef; }
                   6636: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6637: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6638: 
1.48      www      6639: # ---------------------------------------------------- Any other user namespace
                   6640:     } elsif ($realm eq 'environment') {
                   6641: # ----------------------------------------------------------------- environment
1.620     albertel 6642: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6643: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6644: 	} else {
1.770     albertel 6645: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6646: 		return '';
                   6647: 	    }
1.219     albertel 6648: 	    my %returnhash=&userenvironment($udom,$uname,
                   6649: 					    $spacequalifierrest);
                   6650: 	    return $returnhash{$spacequalifierrest};
                   6651: 	}
1.28      www      6652:     } elsif ($realm eq 'system') {
1.48      www      6653: # ----------------------------------------------------------------- system.time
                   6654: 	if ($space eq 'time') {
                   6655: 	    return time;
                   6656:         }
1.696     albertel 6657:     } elsif ($realm eq 'server') {
                   6658: # ----------------------------------------------------------------- system.time
                   6659: 	if ($space eq 'name') {
                   6660: 	    return $ENV{'SERVER_NAME'};
                   6661:         }
1.28      www      6662:     }
1.48      www      6663:     return '';
1.61      www      6664: }
                   6665: 
1.691     raeburn  6666: sub check_group_parms {
                   6667:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6668:     my @groupitems = ();
                   6669:     my $resultitem;
                   6670:     my @levels = ($symbparm,$mapparm,$what);
                   6671:     foreach my $group (@{$groups}) {
                   6672:         foreach my $level (@levels) {
                   6673:              my $item = $courseid.'.['.$group.'].'.$level;
                   6674:              push(@groupitems,$item);
                   6675:         }
                   6676:     }
                   6677:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6678:                             $env{'course.'.$courseid.'.domain'},
                   6679:                                      'course',@groupitems);
                   6680:     return $coursereply;
                   6681: }
                   6682: 
                   6683: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6684:     my ($courseid,@groups) = @_;
                   6685:     @groups = sort(@groups);
1.691     raeburn  6686:     return @groups;
                   6687: }
                   6688: 
1.395     albertel 6689: sub packages_tab_default {
                   6690:     my ($uri,$varname)=@_;
                   6691:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6692: 
                   6693:     my (@extension,@specifics,$do_default);
                   6694:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6695: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6696: 	if ($pack_type eq 'default') {
                   6697: 	    $do_default=1;
                   6698: 	} elsif ($pack_type eq 'extension') {
                   6699: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6700: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6701: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6702: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6703: 	}
                   6704:     }
                   6705:     # first look for a package that matches the requested part id
                   6706:     foreach my $package (@specifics) {
                   6707: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6708: 	next if ($pack_part ne $part);
                   6709: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6710: 	    return $packagetab{"$pack_type&$name&default"};
                   6711: 	}
                   6712:     }
                   6713:     # look for any possible matching non extension_ package
                   6714:     foreach my $package (@specifics) {
                   6715: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6716: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6717: 	    return $packagetab{"$pack_type&$name&default"};
                   6718: 	}
1.585     albertel 6719: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6720: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6721: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6722: 	}
                   6723:     }
1.738     albertel 6724:     # look for any posible extension_ match
                   6725:     foreach my $package (@extension) {
                   6726: 	my ($package,$pack_type)=@{$package};
                   6727: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6728: 	    return $packagetab{"$pack_type&$name&default"};
                   6729: 	}
                   6730: 	if (defined($packagetab{$package."&$name&default"})) {
                   6731: 	    return $packagetab{$package."&$name&default"};
                   6732: 	}
                   6733:     }
                   6734:     # look for a global default setting
                   6735:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6736: 	return $packagetab{"default&$name&default"};
                   6737:     }
1.395     albertel 6738:     return undef;
                   6739: }
                   6740: 
1.334     albertel 6741: sub add_prefix_and_part {
                   6742:     my ($prefix,$part)=@_;
                   6743:     my $keyroot;
                   6744:     if (defined($prefix) && $prefix !~ /^__/) {
                   6745: 	# prefix that has a part already
                   6746: 	$keyroot=$prefix;
                   6747:     } elsif (defined($prefix)) {
                   6748: 	# prefix that is missing a part
                   6749: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6750:     } else {
                   6751: 	# no prefix at all
                   6752: 	if (defined($part)) { $keyroot='_'.$part; }
                   6753:     }
                   6754:     return $keyroot;
                   6755: }
                   6756: 
1.71      www      6757: # ---------------------------------------------------------------- Get metadata
                   6758: 
1.599     albertel 6759: my %metaentry;
1.71      www      6760: sub metadata {
1.176     www      6761:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6762:     $uri=&declutter($uri);
1.288     albertel 6763:     # if it is a non metadata possible uri return quickly
1.529     albertel 6764:     if (($uri eq '') || 
                   6765: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6766: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6767:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6768: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6769: 	return undef;
1.288     albertel 6770:     }
1.73      www      6771:     my $filename=$uri;
                   6772:     $uri=~s/\.meta$//;
1.172     www      6773: #
                   6774: # Is the metadata already cached?
1.177     www      6775: # Look at timestamp of caching
1.172     www      6776: # Everything is cached by the main uri, libraries are never directly cached
                   6777: #
1.428     albertel 6778:     if (!defined($liburi)) {
1.599     albertel 6779: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6780: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6781:     }
                   6782:     {
1.172     www      6783: #
                   6784: # Is this a recursive call for a library?
                   6785: #
1.599     albertel 6786: #	if (! exists($metacache{$uri})) {
                   6787: #	    $metacache{$uri}={};
                   6788: #	}
1.171     www      6789:         if ($liburi) {
                   6790: 	    $liburi=&declutter($liburi);
                   6791:             $filename=$liburi;
1.401     bowersj2 6792:         } else {
1.599     albertel 6793: 	    &devalidate_cache_new('meta',$uri);
                   6794: 	    undef(%metaentry);
1.401     bowersj2 6795: 	}
1.140     www      6796:         my %metathesekeys=();
1.73      www      6797:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6798: 	my $metastring;
1.768     albertel 6799: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6800: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6801: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6802: 	    $metastring=&getfile($file);
1.489     albertel 6803: 	}
1.208     albertel 6804:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6805:         my $token;
1.140     www      6806:         undef %metathesekeys;
1.71      www      6807:         while ($token=$parser->get_token) {
1.339     albertel 6808: 	    if ($token->[0] eq 'S') {
                   6809: 		if (defined($token->[2]->{'package'})) {
1.172     www      6810: #
                   6811: # This is a package - get package info
                   6812: #
1.339     albertel 6813: 		    my $package=$token->[2]->{'package'};
                   6814: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6815: 		    if (defined($token->[2]->{'id'})) { 
                   6816: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6817: 		    }
1.599     albertel 6818: 		    if ($metaentry{':packages'}) {
                   6819: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6820: 		    } else {
1.599     albertel 6821: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6822: 		    }
1.736     albertel 6823: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6824: 			my $part=$keyroot;
                   6825: 			$part=~s/^\_//;
1.736     albertel 6826: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6827: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6828: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6829: 			    # ignore package.tab specified default values
                   6830:                             # here &package_tab_default() will fetch those
                   6831: 			    if ($subp eq 'default') { next; }
1.736     albertel 6832: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6833: 			    my $unikey;
                   6834: 			    if ($pack =~ /_0$/) {
                   6835: 				$unikey='parameter_0_'.$name;
                   6836: 				$part=0;
                   6837: 			    } else {
                   6838: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6839: 			    }
1.339     albertel 6840: 			    if ($subp eq 'display') {
                   6841: 				$value.=' [Part: '.$part.']';
                   6842: 			    }
1.599     albertel 6843: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6844: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6845: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6846: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6847: 			    }
1.599     albertel 6848: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6849: 				$metaentry{':'.$unikey}=
                   6850: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6851: 			    }
1.339     albertel 6852: 			}
                   6853: 		    }
                   6854: 		} else {
1.172     www      6855: #
                   6856: # This is not a package - some other kind of start tag
1.339     albertel 6857: #
                   6858: 		    my $entry=$token->[1];
                   6859: 		    my $unikey;
                   6860: 		    if ($entry eq 'import') {
                   6861: 			$unikey='';
                   6862: 		    } else {
                   6863: 			$unikey=$entry;
                   6864: 		    }
                   6865: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6866: 
                   6867: 		    if (defined($token->[2]->{'id'})) { 
                   6868: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6869: 		    }
1.175     www      6870: 
1.339     albertel 6871: 		    if ($entry eq 'import') {
1.175     www      6872: #
                   6873: # Importing a library here
1.339     albertel 6874: #
                   6875: 			if ($depthcount<20) {
                   6876: 			    my $location=$parser->get_text('/import');
                   6877: 			    my $dir=$filename;
                   6878: 			    $dir=~s|[^/]*$||;
                   6879: 			    $location=&filelocation($dir,$location);
1.736     albertel 6880: 			    my $metadata = 
                   6881: 				&metadata($uri,'keys', $location,$unikey,
                   6882: 					  $depthcount+1);
                   6883: 			    foreach my $meta (split(',',$metadata)) {
                   6884: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6885: 				$metathesekeys{$meta}=1;
1.339     albertel 6886: 			    }
                   6887: 			}
                   6888: 		    } else { 
                   6889: 			
                   6890: 			if (defined($token->[2]->{'name'})) { 
                   6891: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6892: 			}
                   6893: 			$metathesekeys{$unikey}=1;
1.736     albertel 6894: 			foreach my $param (@{$token->[3]}) {
                   6895: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6896: 				$token->[2]->{$param};
1.339     albertel 6897: 			}
                   6898: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6899: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6900: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6901: 		 # only ws inside the tag, and not in default, so use default
                   6902: 		 # as value
1.599     albertel 6903: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6904: 			} elsif ( $internaltext =~ /\S/ ) {
                   6905: 		  # something interesting inside the tag
                   6906: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6907: 			} else {
1.908     albertel 6908: 		  # no interesting values, don't set a default
1.339     albertel 6909: 			}
1.172     www      6910: # end of not-a-package not-a-library import
1.339     albertel 6911: 		    }
1.172     www      6912: # end of not-a-package start tag
1.339     albertel 6913: 		}
1.172     www      6914: # the next is the end of "start tag"
1.339     albertel 6915: 	    }
                   6916: 	}
1.483     albertel 6917: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6918: 	$extension = lc($extension);
                   6919: 	if ($extension eq 'htm') { $extension='html'; }
                   6920: 
1.737     albertel 6921: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6922: 	    #no specific packages #how's our extension
                   6923: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6924: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6925: 					 \%metathesekeys);
                   6926: 	}
1.883     albertel 6927: 
                   6928: 	if (!exists($metaentry{':packages'})
                   6929: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6930: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6931: 		#no specific packages well let's get default then
                   6932: 		if ($key!~/^default&/) { next; }
1.488     albertel 6933: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6934: 					     \%metathesekeys);
                   6935: 	    }
                   6936: 	}
1.338     www      6937: # are there custom rights to evaluate
1.599     albertel 6938: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6939: 
1.338     www      6940:     #
                   6941:     # Importing a rights file here
1.339     albertel 6942:     #
                   6943: 	    unless ($depthcount) {
1.599     albertel 6944: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6945: 		my $dir=$filename;
                   6946: 		$dir=~s|[^/]*$||;
                   6947: 		$location=&filelocation($dir,$location);
1.736     albertel 6948: 		my $rights_metadata =
                   6949: 		    &metadata($uri,'keys',$location,'_rights',
                   6950: 			      $depthcount+1);
                   6951: 		foreach my $rights (split(',',$rights_metadata)) {
                   6952: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6953: 		    $metathesekeys{$rights}=1;
1.339     albertel 6954: 		}
                   6955: 	    }
                   6956: 	}
1.737     albertel 6957: 	# uniqifiy package listing
                   6958: 	my %seen;
                   6959: 	my @uniq_packages =
                   6960: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6961: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6962: 
                   6963: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6964: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6965: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6966: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6967: # this is the end of "was not already recently cached
1.71      www      6968:     }
1.599     albertel 6969:     return $metaentry{':'.$what};
1.261     albertel 6970: }
                   6971: 
1.488     albertel 6972: sub metadata_create_package_def {
1.483     albertel 6973:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6974:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6975:     if ($subp eq 'default') { next; }
                   6976:     
1.599     albertel 6977:     if (defined($metaentry{':packages'})) {
                   6978: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6979:     } else {
1.599     albertel 6980: 	$metaentry{':packages'}=$package;
1.483     albertel 6981:     }
                   6982:     my $value=$packagetab{$key};
                   6983:     my $unikey;
                   6984:     $unikey='parameter_0_'.$name;
1.599     albertel 6985:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6986:     $$metathesekeys{$unikey}=1;
1.599     albertel 6987:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6988: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6989:     }
1.599     albertel 6990:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6991: 	$metaentry{':'.$unikey}=
                   6992: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6993:     }
                   6994: }
                   6995: 
1.261     albertel 6996: sub metadata_generate_part0 {
                   6997:     my ($metadata,$metacache,$uri) = @_;
                   6998:     my %allnames;
1.737     albertel 6999:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7000: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7001: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7002: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7003: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7004: 	    $allnames{$name}=$part;
                   7005: 	  }
                   7006: 	}
                   7007:     }
                   7008:     foreach my $name (keys(%allnames)) {
                   7009:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7010:       my $key=":parameter_0_$name";
1.261     albertel 7011:       $$metacache{"$key.part"}='0';
                   7012:       $$metacache{"$key.name"}=$name;
1.428     albertel 7013:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7014: 					   $allnames{$name}.'_'.$name.
                   7015: 					   '.type'};
1.428     albertel 7016:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7017: 			     '.display'};
1.644     www      7018:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7019:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7020:       $$metacache{"$key.display"}=$olddis;
                   7021:     }
1.71      www      7022: }
                   7023: 
1.764     albertel 7024: # ------------------------------------------------------ Devalidate title cache
                   7025: 
                   7026: sub devalidate_title_cache {
                   7027:     my ($url)=@_;
                   7028:     if (!$env{'request.course.id'}) { return; }
                   7029:     my $symb=&symbread($url);
                   7030:     if (!$symb) { return; }
                   7031:     my $key=$env{'request.course.id'}."\0".$symb;
                   7032:     &devalidate_cache_new('title',$key);
                   7033: }
                   7034: 
1.301     www      7035: # ------------------------------------------------- Get the title of a resource
                   7036: 
                   7037: sub gettitle {
                   7038:     my $urlsymb=shift;
                   7039:     my $symb=&symbread($urlsymb);
1.534     albertel 7040:     if ($symb) {
1.620     albertel 7041: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7042: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7043: 	if (defined($cached)) { 
                   7044: 	    return $result;
                   7045: 	}
1.534     albertel 7046: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7047: 	my $title='';
1.907     albertel 7048: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7049: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7050: 	} else {
                   7051: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7052: 		    &GDBM_READER(),0640)) {
                   7053: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7054: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7055: 		untie(%bighash);
                   7056: 	    }
1.534     albertel 7057: 	}
                   7058: 	$title=~s/\&colon\;/\:/gs;
                   7059: 	if ($title) {
1.599     albertel 7060: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7061: 	}
                   7062: 	$urlsymb=$url;
                   7063:     }
                   7064:     my $title=&metadata($urlsymb,'title');
                   7065:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7066:     return $title;
1.301     www      7067: }
1.613     albertel 7068: 
1.614     albertel 7069: sub get_slot {
                   7070:     my ($which,$cnum,$cdom)=@_;
                   7071:     if (!$cnum || !$cdom) {
1.790     albertel 7072: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7073: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7074: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7075:     }
1.703     albertel 7076:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7077:     my %slotinfo;
                   7078:     if (exists($remembered{$key})) {
                   7079: 	$slotinfo{$which} = $remembered{$key};
                   7080:     } else {
                   7081: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7082: 	&Apache::lonhomework::showhash(%slotinfo);
                   7083: 	my ($tmp)=keys(%slotinfo);
                   7084: 	if ($tmp=~/^error:/) { return (); }
                   7085: 	$remembered{$key} = $slotinfo{$which};
                   7086:     }
1.616     albertel 7087:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7088: 	return %{$slotinfo{$which}};
                   7089:     }
                   7090:     return $slotinfo{$which};
1.614     albertel 7091: }
1.31      www      7092: # ------------------------------------------------- Update symbolic store links
                   7093: 
                   7094: sub symblist {
                   7095:     my ($mapname,%newhash)=@_;
1.438     www      7096:     $mapname=&deversion(&declutter($mapname));
1.31      www      7097:     my %hash;
1.620     albertel 7098:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7099:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7100:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7101: 	    foreach my $url (keys %newhash) {
                   7102: 		next if ($url eq 'last_known'
                   7103: 			 && $env{'form.no_update_last_known'});
                   7104: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7105: 						    $newhash{$url}->[1],
                   7106: 						    $newhash{$url}->[0]);
1.191     harris41 7107:             }
1.31      www      7108:             if (untie(%hash)) {
                   7109: 		return 'ok';
                   7110:             }
                   7111:         }
                   7112:     }
                   7113:     return 'error';
1.212     www      7114: }
                   7115: 
                   7116: # --------------------------------------------------------------- Verify a symb
                   7117: 
                   7118: sub symbverify {
1.510     www      7119:     my ($symb,$thisurl)=@_;
                   7120:     my $thisfn=$thisurl;
1.439     www      7121:     $thisfn=&declutter($thisfn);
1.215     www      7122: # direct jump to resource in page or to a sequence - will construct own symbs
                   7123:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7124: # check URL part
1.409     www      7125:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7126: 
1.431     www      7127:     unless ($url eq $thisfn) { return 0; }
1.213     www      7128: 
1.216     www      7129:     $symb=&symbclean($symb);
1.510     www      7130:     $thisurl=&deversion($thisurl);
1.439     www      7131:     $thisfn=&deversion($thisfn);
1.213     www      7132: 
                   7133:     my %bighash;
                   7134:     my $okay=0;
1.431     www      7135: 
1.620     albertel 7136:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7137:                             &GDBM_READER(),0640)) {
1.510     www      7138:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7139:         unless ($ids) { 
1.510     www      7140:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7141:         }
                   7142:         if ($ids) {
                   7143: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7144: 	    foreach my $id (split(/\,/,$ids)) {
                   7145: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7146:                if (
                   7147:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7148:    eq $symb) { 
1.620     albertel 7149: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7150: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7151: 		       $okay=1; 
                   7152: 		   }
                   7153: 	       }
1.216     www      7154: 	   }
                   7155:         }
1.213     www      7156: 	untie(%bighash);
                   7157:     }
                   7158:     return $okay;
1.31      www      7159: }
                   7160: 
1.210     www      7161: # --------------------------------------------------------------- Clean-up symb
                   7162: 
                   7163: sub symbclean {
                   7164:     my $symb=shift;
1.568     albertel 7165:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7166: # remove version from map
                   7167:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7168: 
1.210     www      7169: # remove version from URL
                   7170:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7171: 
1.507     www      7172: # remove wrapper
                   7173: 
1.510     www      7174:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7175:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7176:     return $symb;
1.409     www      7177: }
                   7178: 
                   7179: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7180: 
                   7181: sub encode_symb {
                   7182:     my ($map,$resid,$url)=@_;
                   7183:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7184: }
1.409     www      7185: 
                   7186: sub decode_symb {
1.568     albertel 7187:     my $symb=shift;
                   7188:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7189:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7190:     return (&fixversion($map),$resid,&fixversion($url));
                   7191: }
                   7192: 
                   7193: sub fixversion {
                   7194:     my $fn=shift;
1.609     banghart 7195:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7196:     my %bighash;
                   7197:     my $uri=&clutter($fn);
1.620     albertel 7198:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7199: # is this cached?
1.599     albertel 7200:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7201:     if (defined($cached)) { return $result; }
                   7202: # unfortunately not cached, or expired
1.620     albertel 7203:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7204: 	    &GDBM_READER(),0640)) {
                   7205:  	if ($bighash{'version_'.$uri}) {
                   7206:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7207:  	    unless (($version eq 'mostrecent') || 
                   7208: 		    ($version==&getversion($uri))) {
1.440     www      7209:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7210:  	    }
                   7211:  	}
                   7212:  	untie %bighash;
1.413     www      7213:     }
1.599     albertel 7214:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7215: }
                   7216: 
                   7217: sub deversion {
                   7218:     my $url=shift;
                   7219:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7220:     return $url;
1.210     www      7221: }
                   7222: 
1.31      www      7223: # ------------------------------------------------------ Return symb list entry
                   7224: 
                   7225: sub symbread {
1.249     www      7226:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7227:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7228:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7229: # no filename provided? try from environment
1.44      www      7230:     unless ($thisfn) {
1.620     albertel 7231:         if ($env{'request.symb'}) {
                   7232: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7233: 	}
1.620     albertel 7234: 	$thisfn=$env{'request.filename'};
1.44      www      7235:     }
1.569     albertel 7236:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7237: # is that filename actually a symb? Verify, clean, and return
                   7238:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7239: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7240: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7241: 	}
1.242     www      7242:     }
1.44      www      7243:     $thisfn=declutter($thisfn);
1.31      www      7244:     my %hash;
1.37      www      7245:     my %bighash;
                   7246:     my $syval='';
1.620     albertel 7247:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7248:         my $targetfn = $thisfn;
1.609     banghart 7249:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7250:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7251:         }
1.687     albertel 7252: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7253: 	    $targetfn=$1;
                   7254: 	}
1.620     albertel 7255:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7256:                       &GDBM_READER(),0640)) {
1.481     raeburn  7257: 	    $syval=$hash{$targetfn};
1.37      www      7258:             untie(%hash);
                   7259:         }
                   7260: # ---------------------------------------------------------- There was an entry
                   7261:         if ($syval) {
1.601     albertel 7262: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7263: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7264: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7265: 		    #return $env{$cache_str}='';
1.601     albertel 7266: 		#}    
                   7267: 		#$syval.=$1;
                   7268: 	    #}
1.37      www      7269:         } else {
                   7270: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7271:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7272:                             &GDBM_READER(),0640)) {
1.37      www      7273: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7274:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7275:               unless ($ids) { 
                   7276:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7277:               }
                   7278:               unless ($ids) {
                   7279: # alias?
                   7280: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7281:               }
1.37      www      7282:               if ($ids) {
                   7283: # ------------------------------------------------------------------- Has ID(s)
                   7284:                  my @possibilities=split(/\,/,$ids);
1.39      www      7285:                  if ($#possibilities==0) {
                   7286: # ----------------------------------------------- There is only one possibility
1.37      www      7287: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7288: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7289: 						    $resid,$thisfn);
1.249     www      7290:                  } elsif (!$donotrecurse) {
1.39      www      7291: # ------------------------------------------ There is more than one possibility
                   7292:                      my $realpossible=0;
1.800     albertel 7293:                      foreach my $id (@possibilities) {
                   7294: 			 my $file=$bighash{'src_'.$id};
1.39      www      7295:                          if (&allowed('bre',$file)) {
1.800     albertel 7296:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7297:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7298: 				$realpossible++;
1.626     albertel 7299:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7300: 						    $resid,$thisfn);
1.39      www      7301:                             }
                   7302: 			 }
1.191     harris41 7303:                      }
1.39      www      7304: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7305:                  } else {
                   7306:                      $syval='';
1.37      www      7307:                  }
                   7308: 	      }
                   7309:               untie(%bighash)
1.481     raeburn  7310:            }
1.31      www      7311:         }
1.62      www      7312:         if ($syval) {
1.620     albertel 7313: 	    return $env{$cache_str}=$syval;
1.62      www      7314:         }
1.31      www      7315:     }
1.44      www      7316:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7317:     return $env{$cache_str}='';
1.31      www      7318: }
                   7319: 
                   7320: # ---------------------------------------------------------- Return random seed
                   7321: 
1.32      www      7322: sub numval {
                   7323:     my $txt=shift;
                   7324:     $txt=~tr/A-J/0-9/;
                   7325:     $txt=~tr/a-j/0-9/;
                   7326:     $txt=~tr/K-T/0-9/;
                   7327:     $txt=~tr/k-t/0-9/;
                   7328:     $txt=~tr/U-Z/0-5/;
                   7329:     $txt=~tr/u-z/0-5/;
                   7330:     $txt=~s/\D//g;
1.564     albertel 7331:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7332:     return int($txt);
1.368     albertel 7333: }
                   7334: 
1.484     albertel 7335: sub numval2 {
                   7336:     my $txt=shift;
                   7337:     $txt=~tr/A-J/0-9/;
                   7338:     $txt=~tr/a-j/0-9/;
                   7339:     $txt=~tr/K-T/0-9/;
                   7340:     $txt=~tr/k-t/0-9/;
                   7341:     $txt=~tr/U-Z/0-5/;
                   7342:     $txt=~tr/u-z/0-5/;
                   7343:     $txt=~s/\D//g;
                   7344:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7345:     my $total;
                   7346:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7347:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7348:     return int($total);
                   7349: }
                   7350: 
1.575     albertel 7351: sub numval3 {
                   7352:     use integer;
                   7353:     my $txt=shift;
                   7354:     $txt=~tr/A-J/0-9/;
                   7355:     $txt=~tr/a-j/0-9/;
                   7356:     $txt=~tr/K-T/0-9/;
                   7357:     $txt=~tr/k-t/0-9/;
                   7358:     $txt=~tr/U-Z/0-5/;
                   7359:     $txt=~tr/u-z/0-5/;
                   7360:     $txt=~s/\D//g;
                   7361:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7362:     my $total;
                   7363:     foreach my $val (@txts) { $total+=$val; }
                   7364:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7365:     return $total;
                   7366: }
                   7367: 
1.675     albertel 7368: sub digest {
                   7369:     my ($data)=@_;
                   7370:     my $digest=&Digest::MD5::md5($data);
                   7371:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7372:     my ($e,$f);
                   7373:     {
                   7374:         use integer;
                   7375:         $e=($a+$b);
                   7376:         $f=($c+$d);
                   7377:         if ($_64bit) {
                   7378:             $e=(($e<<32)>>32);
                   7379:             $f=(($f<<32)>>32);
                   7380:         }
                   7381:     }
                   7382:     if (wantarray) {
                   7383: 	return ($e,$f);
                   7384:     } else {
                   7385: 	my $g;
                   7386: 	{
                   7387: 	    use integer;
                   7388: 	    $g=($e+$f);
                   7389: 	    if ($_64bit) {
                   7390: 		$g=(($g<<32)>>32);
                   7391: 	    }
                   7392: 	}
                   7393: 	return $g;
                   7394:     }
                   7395: }
                   7396: 
1.368     albertel 7397: sub latest_rnd_algorithm_id {
1.675     albertel 7398:     return '64bit5';
1.366     albertel 7399: }
1.32      www      7400: 
1.503     albertel 7401: sub get_rand_alg {
                   7402:     my ($courseid)=@_;
1.790     albertel 7403:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7404:     if ($courseid) {
1.620     albertel 7405: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7406:     }
                   7407:     return &latest_rnd_algorithm_id();
                   7408: }
                   7409: 
1.562     albertel 7410: sub validCODE {
                   7411:     my ($CODE)=@_;
                   7412:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7413:     return 0;
                   7414: }
                   7415: 
1.491     albertel 7416: sub getCODE {
1.620     albertel 7417:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7418:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7419: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7420: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7421: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7422:     }
                   7423:     return undef;
                   7424: }
                   7425: 
1.31      www      7426: sub rndseed {
1.155     albertel 7427:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7428:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7429:     if (!defined($symb)) {
1.366     albertel 7430: 	unless ($symb=$wsymb) { return time; }
                   7431:     }
                   7432:     if (!$courseid) { $courseid=$wcourseid; }
                   7433:     if (!$domain) { $domain=$wdomain; }
                   7434:     if (!$username) { $username=$wusername }
1.503     albertel 7435:     my $which=&get_rand_alg();
1.803     albertel 7436: 
1.491     albertel 7437:     if (defined(&getCODE())) {
1.675     albertel 7438: 	if ($which eq '64bit5') {
                   7439: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7440: 	} elsif ($which eq '64bit4') {
1.575     albertel 7441: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7442: 	} else {
                   7443: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7444: 	}
1.675     albertel 7445:     } elsif ($which eq '64bit5') {
                   7446: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7447:     } elsif ($which eq '64bit4') {
                   7448: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7449:     } elsif ($which eq '64bit3') {
                   7450: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7451:     } elsif ($which eq '64bit2') {
                   7452: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7453:     } elsif ($which eq '64bit') {
                   7454: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7455:     }
                   7456:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7457: }
                   7458: 
                   7459: sub rndseed_32bit {
                   7460:     my ($symb,$courseid,$domain,$username)=@_;
                   7461:     {
                   7462: 	use integer;
                   7463: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7464: 	my $symbseed=numval($symb) << 22;
                   7465: 	my $namechck=unpack("%32C*",$username) << 17;
                   7466: 	my $nameseed=numval($username) << 12;
                   7467: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7468: 	my $courseseed=unpack("%32C*",$courseid);
                   7469: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7470: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7471: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7472: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7473: 	return $num;
                   7474:     }
                   7475: }
                   7476: 
                   7477: sub rndseed_64bit {
                   7478:     my ($symb,$courseid,$domain,$username)=@_;
                   7479:     {
                   7480: 	use integer;
                   7481: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7482: 	my $symbseed=numval($symb) << 10;
                   7483: 	my $namechck=unpack("%32S*",$username);
                   7484: 	
                   7485: 	my $nameseed=numval($username) << 21;
                   7486: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7487: 	my $courseseed=unpack("%32S*",$courseid);
                   7488: 	
                   7489: 	my $num1=$symbchck+$symbseed+$namechck;
                   7490: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7491: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7492: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7493: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7494: 	return "$num1,$num2";
1.155     albertel 7495:     }
1.366     albertel 7496: }
                   7497: 
1.443     albertel 7498: sub rndseed_64bit2 {
                   7499:     my ($symb,$courseid,$domain,$username)=@_;
                   7500:     {
                   7501: 	use integer;
                   7502: 	# strings need to be an even # of cahracters long, it it is odd the
                   7503:         # last characters gets thrown away
                   7504: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7505: 	my $symbseed=numval($symb) << 10;
                   7506: 	my $namechck=unpack("%32S*",$username.' ');
                   7507: 	
                   7508: 	my $nameseed=numval($username) << 21;
1.501     albertel 7509: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7510: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7511: 	
                   7512: 	my $num1=$symbchck+$symbseed+$namechck;
                   7513: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7514: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7515: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7516: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7517: 	return "$num1,$num2";
                   7518:     }
                   7519: }
                   7520: 
                   7521: sub rndseed_64bit3 {
                   7522:     my ($symb,$courseid,$domain,$username)=@_;
                   7523:     {
                   7524: 	use integer;
                   7525: 	# strings need to be an even # of cahracters long, it it is odd the
                   7526:         # last characters gets thrown away
                   7527: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7528: 	my $symbseed=numval2($symb) << 10;
                   7529: 	my $namechck=unpack("%32S*",$username.' ');
                   7530: 	
                   7531: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7532: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7533: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7534: 	
                   7535: 	my $num1=$symbchck+$symbseed+$namechck;
                   7536: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7537: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7538: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7539: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7540: 	
1.503     albertel 7541: 	return "$num1:$num2";
1.443     albertel 7542:     }
                   7543: }
                   7544: 
1.575     albertel 7545: sub rndseed_64bit4 {
                   7546:     my ($symb,$courseid,$domain,$username)=@_;
                   7547:     {
                   7548: 	use integer;
                   7549: 	# strings need to be an even # of cahracters long, it it is odd the
                   7550:         # last characters gets thrown away
                   7551: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7552: 	my $symbseed=numval3($symb) << 10;
                   7553: 	my $namechck=unpack("%32S*",$username.' ');
                   7554: 	
                   7555: 	my $nameseed=numval3($username) << 21;
                   7556: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7557: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7558: 	
                   7559: 	my $num1=$symbchck+$symbseed+$namechck;
                   7560: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7561: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7562: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7563: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7564: 	
                   7565: 	return "$num1:$num2";
                   7566:     }
                   7567: }
                   7568: 
1.675     albertel 7569: sub rndseed_64bit5 {
                   7570:     my ($symb,$courseid,$domain,$username)=@_;
                   7571:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7572:     return "$num1:$num2";
                   7573: }
                   7574: 
1.366     albertel 7575: sub rndseed_CODE_64bit {
                   7576:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7577:     {
1.366     albertel 7578: 	use integer;
1.443     albertel 7579: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7580: 	my $symbseed=numval2($symb);
1.491     albertel 7581: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7582: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7583: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7584: 	my $num1=$symbseed+$CODEchck;
                   7585: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7586: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7587: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7588: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7589: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7590: 	return "$num1:$num2";
1.366     albertel 7591:     }
                   7592: }
                   7593: 
1.575     albertel 7594: sub rndseed_CODE_64bit4 {
                   7595:     my ($symb,$courseid,$domain,$username)=@_;
                   7596:     {
                   7597: 	use integer;
                   7598: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7599: 	my $symbseed=numval3($symb);
                   7600: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7601: 	my $CODEseed=numval3(&getCODE());
                   7602: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7603: 	my $num1=$symbseed+$CODEchck;
                   7604: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7605: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7606: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7607: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7608: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7609: 	return "$num1:$num2";
                   7610:     }
                   7611: }
                   7612: 
1.675     albertel 7613: sub rndseed_CODE_64bit5 {
                   7614:     my ($symb,$courseid,$domain,$username)=@_;
                   7615:     my $code = &getCODE();
                   7616:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7617:     return "$num1:$num2";
                   7618: }
                   7619: 
1.366     albertel 7620: sub setup_random_from_rndseed {
                   7621:     my ($rndseed)=@_;
1.503     albertel 7622:     if ($rndseed =~/([,:])/) {
                   7623: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7624: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7625:     } else {
                   7626: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7627:     }
1.36      albertel 7628: }
                   7629: 
1.474     albertel 7630: sub latest_receipt_algorithm_id {
1.835     albertel 7631:     return 'receipt3';
1.474     albertel 7632: }
                   7633: 
1.480     www      7634: sub recunique {
                   7635:     my $fucourseid=shift;
                   7636:     my $unique;
1.835     albertel 7637:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7638: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7639: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7640:     } else {
                   7641: 	$unique=$perlvar{'lonReceipt'};
                   7642:     }
                   7643:     return unpack("%32C*",$unique);
                   7644: }
                   7645: 
                   7646: sub recprefix {
                   7647:     my $fucourseid=shift;
                   7648:     my $prefix;
1.835     albertel 7649:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7650: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7651: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7652:     } else {
                   7653: 	$prefix=$perlvar{'lonHostID'};
                   7654:     }
                   7655:     return unpack("%32C*",$prefix);
                   7656: }
                   7657: 
1.76      www      7658: sub ireceipt {
1.474     albertel 7659:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7660: 
                   7661:     my $return =&recprefix($fucourseid).'-';
                   7662: 
                   7663:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7664: 	$env{'request.state'} eq 'construct') {
                   7665: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7666: 	return $return;
                   7667:     }
                   7668: 
1.76      www      7669:     my $cuname=unpack("%32C*",$funame);
                   7670:     my $cudom=unpack("%32C*",$fudom);
                   7671:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7672:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7673:     my $cunique=&recunique($fucourseid);
1.474     albertel 7674:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7675:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7676: 
1.790     albertel 7677: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7678: 			       
                   7679: 	$return.= ($cunique%$cuname+
                   7680: 		   $cunique%$cudom+
                   7681: 		   $cusymb%$cuname+
                   7682: 		   $cusymb%$cudom+
                   7683: 		   $cucourseid%$cuname+
                   7684: 		   $cucourseid%$cudom+
                   7685: 		   $cpart%$cuname+
                   7686: 		   $cpart%$cudom);
                   7687:     } else {
                   7688: 	$return.= ($cunique%$cuname+
                   7689: 		   $cunique%$cudom+
                   7690: 		   $cusymb%$cuname+
                   7691: 		   $cusymb%$cudom+
                   7692: 		   $cucourseid%$cuname+
                   7693: 		   $cucourseid%$cudom);
                   7694:     }
                   7695:     return $return;
1.76      www      7696: }
                   7697: 
                   7698: sub receipt {
1.474     albertel 7699:     my ($part)=@_;
1.790     albertel 7700:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7701:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7702: }
1.260     ng       7703: 
1.790     albertel 7704: sub whichuser {
                   7705:     my ($passedsymb)=@_;
                   7706:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7707:     if (defined($env{'form.grade_symb'})) {
                   7708: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7709: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7710: 	if (!$allowed &&
                   7711: 	    exists($env{'request.course.sec'}) &&
                   7712: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7713: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7714: 			      '/'.$env{'request.course.sec'});
                   7715: 	}
                   7716: 	if ($allowed) {
                   7717: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7718: 	    $courseid=$tmp_courseid;
                   7719: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7720: 	    ($name)=&get_env_multiple('form.grade_username');
                   7721: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7722: 	}
                   7723:     }
                   7724:     if (!$passedsymb) {
                   7725: 	$symb=&symbread();
                   7726:     } else {
                   7727: 	$symb=$passedsymb;
                   7728:     }
                   7729:     $courseid=$env{'request.course.id'};
                   7730:     $domain=$env{'user.domain'};
                   7731:     $name=$env{'user.name'};
                   7732:     if ($name eq 'public' && $domain eq 'public') {
                   7733: 	if (!defined($env{'form.username'})) {
                   7734: 	    $env{'form.username'}.=time.rand(10000000);
                   7735: 	}
                   7736: 	$name.=$env{'form.username'};
                   7737:     }
                   7738:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7739: 
                   7740: }
                   7741: 
1.36      albertel 7742: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7743: # returns either the contents of the file or 
                   7744: # -1 if the file doesn't exist
1.481     raeburn  7745: #
                   7746: # if the target is a file that was uploaded via DOCS, 
                   7747: # a check will be made to see if a current copy exists on the local server,
                   7748: # if it does this will be served, otherwise a copy will be retrieved from
                   7749: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7750: # the local server.   
1.472     albertel 7751: 
1.36      albertel 7752: sub getfile {
1.538     albertel 7753:     my ($file) = @_;
1.609     banghart 7754:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7755:     &repcopy($file);
                   7756:     return &readfile($file);
                   7757: }
                   7758: 
                   7759: sub repcopy_userfile {
                   7760:     my ($file)=@_;
1.609     banghart 7761:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7762:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7763:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7764: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7765:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7766:     if (-e "$file") {
1.828     www      7767: # we already have a local copy, check it out
1.538     albertel 7768: 	my @fileinfo = stat($file);
1.828     www      7769: 	my $rtncode;
                   7770: 	my $info;
1.538     albertel 7771: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7772: 	if ($lwpresp ne 'ok') {
1.828     www      7773: # there is no such file anymore, even though we had a local copy
1.482     albertel 7774: 	    if ($rtncode eq '404') {
1.538     albertel 7775: 		unlink($file);
1.482     albertel 7776: 	    }
                   7777: 	    return -1;
                   7778: 	}
                   7779: 	if ($info < $fileinfo[9]) {
1.828     www      7780: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7781: 	    return 'ok';
1.828     www      7782: 	} else {
                   7783: # the file is outdated, get rid of it
                   7784: 	    unlink($file);
1.482     albertel 7785: 	}
1.828     www      7786:     }
                   7787: # one way or the other, at this point, we don't have the file
                   7788: # construct the correct path for the file
                   7789:     my @parts = ($cdom,$cnum); 
                   7790:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7791: 	push @parts, split(/\//,$1);
                   7792:     }
                   7793:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7794:     foreach my $part (@parts) {
                   7795: 	$path .= '/'.$part;
                   7796: 	if (!-e $path) {
                   7797: 	    mkdir($path,0770);
1.482     albertel 7798: 	}
                   7799:     }
1.828     www      7800: # now the path exists for sure
                   7801: # get a user agent
                   7802:     my $ua=new LWP::UserAgent;
                   7803:     my $transferfile=$file.'.in.transfer';
                   7804: # FIXME: this should flock
                   7805:     if (-e $transferfile) { return 'ok'; }
                   7806:     my $request;
                   7807:     $uri=~s/^\///;
1.838     albertel 7808:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7809:     my $response=$ua->request($request,$transferfile);
                   7810: # did it work?
                   7811:     if ($response->is_error()) {
                   7812: 	unlink($transferfile);
                   7813: 	&logthis("Userfile repcopy failed for $uri");
                   7814: 	return -1;
                   7815:     }
                   7816: # worked, rename the transfer file
                   7817:     rename($transferfile,$file);
1.607     raeburn  7818:     return 'ok';
1.481     raeburn  7819: }
                   7820: 
1.517     albertel 7821: sub tokenwrapper {
                   7822:     my $uri=shift;
1.552     albertel 7823:     $uri=~s|^http\://([^/]+)||;
                   7824:     $uri=~s|^/||;
1.620     albertel 7825:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7826:     my $token=$1;
1.552     albertel 7827:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7828:     if ($udom && $uname && $file) {
                   7829: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7830:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7831:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7832:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7833:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7834:     } else {
                   7835:         return '/adm/notfound.html';
                   7836:     }
                   7837: }
                   7838: 
1.828     www      7839: # call with reqtype HEAD: get last modification time
                   7840: # call with reqtype GET: get the file contents
                   7841: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7842: #
1.481     raeburn  7843: sub getuploaded {
                   7844:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7845:     $uri=~s/^\///;
1.838     albertel 7846:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7847:     my $ua=new LWP::UserAgent;
                   7848:     my $request=new HTTP::Request($reqtype,$uri);
                   7849:     my $response=$ua->request($request);
                   7850:     $$rtncode = $response->code;
1.482     albertel 7851:     if (! $response->is_success()) {
                   7852: 	return 'failed';
                   7853:     }      
                   7854:     if ($reqtype eq 'HEAD') {
1.486     www      7855: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7856:     } elsif ($reqtype eq 'GET') {
                   7857: 	$$info = $response->content;
1.472     albertel 7858:     }
1.482     albertel 7859:     return 'ok';
1.36      albertel 7860: }
                   7861: 
1.481     raeburn  7862: sub readfile {
                   7863:     my $file = shift;
                   7864:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7865:     my $fh;
                   7866:     open($fh,"<$file");
                   7867:     my $a='';
1.800     albertel 7868:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7869:     return $a;
                   7870: }
                   7871: 
1.36      albertel 7872: sub filelocation {
1.590     banghart 7873:     my ($dir,$file) = @_;
                   7874:     my $location;
                   7875:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7876: 
                   7877:     if ($file =~ m-^/adm/-) {
                   7878: 	$file=~s-^/adm/wrapper/-/-;
                   7879: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7880:     }
1.882     albertel 7881: 
1.590     banghart 7882:     if ($file=~m:^/~:) { # is a contruction space reference
                   7883:         $location = $file;
                   7884:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7885:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7886: 	# is a correct contruction space reference
                   7887:         $location = $file;
1.609     banghart 7888:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7889:         my ($udom,$uname,$filename)=
1.811     albertel 7890:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7891:         my $home=&homeserver($uname,$udom);
                   7892:         my $is_me=0;
                   7893:         my @ids=&current_machine_ids();
                   7894:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7895:         if ($is_me) {
1.740     www      7896:   	    $location=&propath($udom,$uname).
1.590     banghart 7897:   	      '/userfiles/'.$filename;
                   7898:         } else {
                   7899:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7900:   	      $udom.'/'.$uname.'/'.$filename;
                   7901:         }
1.882     albertel 7902:     } elsif ($file =~ m-^/adm/-) {
                   7903: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7904:     } else {
                   7905:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7906:         $file=~s:^/res/:/:;
                   7907:         if ( !( $file =~ m:^/:) ) {
                   7908:             $location = $dir. '/'.$file;
                   7909:         } else {
                   7910:             $location = '/home/httpd/html/res'.$file;
                   7911:         }
1.59      albertel 7912:     }
1.590     banghart 7913:     $location=~s://+:/:g; # remove duplicate /
                   7914:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7915:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7916:     return $location;
1.46      www      7917: }
1.36      albertel 7918: 
1.46      www      7919: sub hreflocation {
                   7920:     my ($dir,$file)=@_;
1.460     albertel 7921:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7922: 	$file=filelocation($dir,$file);
1.700     albertel 7923:     } elsif ($file=~m-^/adm/-) {
                   7924: 	$file=~s-^/adm/wrapper/-/-;
                   7925: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7926:     }
                   7927:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7928: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7929:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7930: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7931:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7932: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7933: 	    -/uploaded/$1/$2/-x;
1.46      www      7934:     }
1.913     albertel 7935:     if ($file=~ m{^/userfiles/}) {
                   7936: 	$file =~ s{^/userfiles/}{/uploaded/};
                   7937:     }
1.462     albertel 7938:     return $file;
1.465     albertel 7939: }
                   7940: 
                   7941: sub current_machine_domains {
1.853     albertel 7942:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7943: }
                   7944: 
                   7945: sub machine_domains {
                   7946:     my ($hostname) = @_;
1.465     albertel 7947:     my @domains;
1.838     albertel 7948:     my %hostname = &all_hostnames();
1.465     albertel 7949:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7950: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7951: 	if ($hostname eq $name) {
1.844     albertel 7952: 	    push(@domains,&host_domain($id));
1.465     albertel 7953: 	}
                   7954:     }
                   7955:     return @domains;
                   7956: }
                   7957: 
                   7958: sub current_machine_ids {
1.853     albertel 7959:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7960: }
                   7961: 
                   7962: sub machine_ids {
                   7963:     my ($hostname) = @_;
                   7964:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7965:     my @ids;
1.888     albertel 7966:     my %name_to_host = &all_names();
1.889     albertel 7967:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7968: 	return @{ $name_to_host{$hostname} };
                   7969:     }
                   7970:     return;
1.31      www      7971: }
                   7972: 
1.824     raeburn  7973: sub additional_machine_domains {
                   7974:     my @domains;
                   7975:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7976:     while( my $line = <$fh>) {
                   7977:         $line =~ s/\s//g;
                   7978:         push(@domains,$line);
                   7979:     }
                   7980:     return @domains;
                   7981: }
                   7982: 
                   7983: sub default_login_domain {
                   7984:     my $domain = $perlvar{'lonDefDomain'};
                   7985:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7986:     foreach my $posdom (&current_machine_domains(),
                   7987:                         &additional_machine_domains()) {
                   7988:         if (lc($posdom) eq lc($testdomain)) {
                   7989:             $domain=$posdom;
                   7990:             last;
                   7991:         }
                   7992:     }
                   7993:     return $domain;
                   7994: }
                   7995: 
1.31      www      7996: # ------------------------------------------------------------- Declutters URLs
                   7997: 
                   7998: sub declutter {
                   7999:     my $thisfn=shift;
1.569     albertel 8000:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8001:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8002:     $thisfn=~s/^\///;
1.697     albertel 8003:     $thisfn=~s|^adm/wrapper/||;
                   8004:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8005:     $thisfn=~s/^res\///;
1.235     www      8006:     $thisfn=~s/\?.+$//;
1.268     www      8007:     return $thisfn;
                   8008: }
                   8009: 
                   8010: # ------------------------------------------------------------- Clutter up URLs
                   8011: 
                   8012: sub clutter {
                   8013:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8014:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8015: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8016:        $thisfn='/res'.$thisfn; 
                   8017:     }
1.694     albertel 8018:     if ($thisfn !~m|/adm|) {
1.695     albertel 8019: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8020: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8021: 	} else {
                   8022: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8023: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8024: 	    if ($embstyle eq 'ssi'
                   8025: 		|| ($embstyle eq 'hdn')
                   8026: 		|| ($embstyle eq 'rat')
                   8027: 		|| ($embstyle eq 'prv')
                   8028: 		|| ($embstyle eq 'ign')) {
                   8029: 		#do nothing with these
                   8030: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8031: 		|| ($embstyle eq 'emb')
                   8032: 		|| ($embstyle eq 'wrp')) {
                   8033: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8034: 	    } elsif ($embstyle eq 'unk'
                   8035: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8036: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8037: 	    } else {
1.718     www      8038: #		&logthis("Got a blank emb style");
1.695     albertel 8039: 	    }
1.694     albertel 8040: 	}
                   8041:     }
1.31      www      8042:     return $thisfn;
1.12      www      8043: }
                   8044: 
1.787     albertel 8045: sub clutter_with_no_wrapper {
                   8046:     my $uri = &clutter(shift);
                   8047:     if ($uri =~ m-^/adm/-) {
                   8048: 	$uri =~ s-^/adm/wrapper/-/-;
                   8049: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8050:     }
                   8051:     return $uri;
                   8052: }
                   8053: 
1.557     albertel 8054: sub freeze_escape {
                   8055:     my ($value)=@_;
                   8056:     if (ref($value)) {
                   8057: 	$value=&nfreeze($value);
                   8058: 	return '__FROZEN__'.&escape($value);
                   8059:     }
                   8060:     return &escape($value);
                   8061: }
                   8062: 
1.11      www      8063: 
1.557     albertel 8064: sub thaw_unescape {
                   8065:     my ($value)=@_;
                   8066:     if ($value =~ /^__FROZEN__/) {
                   8067: 	substr($value,0,10,undef);
                   8068: 	$value=&unescape($value);
                   8069: 	return &thaw($value);
                   8070:     }
                   8071:     return &unescape($value);
                   8072: }
                   8073: 
1.436     albertel 8074: sub correct_line_ends {
                   8075:     my ($result)=@_;
                   8076:     $$result =~s/\r\n/\n/mg;
                   8077:     $$result =~s/\r/\n/mg;
1.415     albertel 8078: }
1.1       albertel 8079: # ================================================================ Main Program
                   8080: 
1.184     www      8081: sub goodbye {
1.204     albertel 8082:    &logthis("Starting Shut down");
1.443     albertel 8083: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8084:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8085: #converted
1.599     albertel 8086: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8087:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8088: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8089: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8090: #1.1 only
1.870     albertel 8091: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8092: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8093: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8094: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8095:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8096:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8097:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8098:    &flushcourselogs();
                   8099:    &logthis("Shutting down");
                   8100: }
                   8101: 
1.852     albertel 8102: sub get_dns {
1.869     albertel 8103:     my ($url,$func,$ignore_cache) = @_;
                   8104:     if (!$ignore_cache) {
                   8105: 	my ($content,$cached)=
                   8106: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8107: 	if ($cached) {
                   8108: 	    &$func($content);
                   8109: 	    return;
                   8110: 	}
                   8111:     }
                   8112: 
                   8113:     my %alldns;
1.852     albertel 8114:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8115:     foreach my $dns (<$config>) {
                   8116: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8117: 	$alldns{$1} = 1;
                   8118:     }
                   8119:     while (%alldns) {
                   8120: 	my ($dns) = keys(%alldns);
                   8121: 	delete($alldns{$dns});
1.852     albertel 8122: 	my $ua=new LWP::UserAgent;
                   8123: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8124: 	my $response=$ua->request($request);
                   8125: 	next if ($response->is_error());
                   8126: 	my @content = split("\n",$response->content);
1.869     albertel 8127: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8128: 	&$func(\@content);
1.869     albertel 8129: 	return;
1.852     albertel 8130:     }
                   8131:     close($config);
1.871     albertel 8132:     my $which = (split('/',$url))[3];
                   8133:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8134:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8135:     my @content = <$config>;
                   8136:     &$func(\@content);
                   8137:     return;
1.852     albertel 8138: }
1.327     albertel 8139: # ------------------------------------------------------------ Read domain file
                   8140: {
1.852     albertel 8141:     my $loaded;
1.846     albertel 8142:     my %domain;
                   8143: 
1.852     albertel 8144:     sub parse_domain_tab {
                   8145: 	my ($lines) = @_;
                   8146: 	foreach my $line (@$lines) {
                   8147: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8148: 
1.846     albertel 8149: 	    chomp($line);
1.852     albertel 8150: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8151: 	    my %this_domain;
                   8152: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8153: 			       'lang_def', 'city', 'longi', 'lati',
                   8154: 			       'primary') {
                   8155: 		$this_domain{$field} = shift(@elements);
                   8156: 	    }
                   8157: 	    $domain{$name} = \%this_domain;
1.852     albertel 8158: 	}
                   8159:     }
1.864     albertel 8160: 
                   8161:     sub reset_domain_info {
                   8162: 	undef($loaded);
                   8163: 	undef(%domain);
                   8164:     }
                   8165: 
1.852     albertel 8166:     sub load_domain_tab {
1.869     albertel 8167: 	my ($ignore_cache) = @_;
                   8168: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8169: 	my $fh;
                   8170: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8171: 	    my @lines = <$fh>;
                   8172: 	    &parse_domain_tab(\@lines);
1.448     albertel 8173: 	}
1.852     albertel 8174: 	close($fh);
                   8175: 	$loaded = 1;
1.327     albertel 8176:     }
1.846     albertel 8177: 
                   8178:     sub domain {
1.852     albertel 8179: 	&load_domain_tab() if (!$loaded);
                   8180: 
1.846     albertel 8181: 	my ($name,$what) = @_;
                   8182: 	return if ( !exists($domain{$name}) );
                   8183: 
                   8184: 	if (!$what) {
                   8185: 	    return $domain{$name}{'description'};
                   8186: 	}
                   8187: 	return $domain{$name}{$what};
                   8188:     }
1.327     albertel 8189: }
                   8190: 
                   8191: 
1.1       albertel 8192: # ------------------------------------------------------------- Read hosts file
                   8193: {
1.838     albertel 8194:     my %hostname;
1.844     albertel 8195:     my %hostdom;
1.845     albertel 8196:     my %libserv;
1.852     albertel 8197:     my $loaded;
1.888     albertel 8198:     my %name_to_host;
1.852     albertel 8199: 
                   8200:     sub parse_hosts_tab {
                   8201: 	my ($file) = @_;
                   8202: 	foreach my $configline (@$file) {
                   8203: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8204: 	    next if ($configline =~ /^\^/);
                   8205: 	    chomp($configline);
                   8206: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8207: 	    $name=~s/\s//g;
                   8208: 	    if ($id && $domain && $role && $name) {
                   8209: 		$hostname{$id}=$name;
1.888     albertel 8210: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8211: 		$hostdom{$id}=$domain;
                   8212: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8213: 	    }
                   8214: 	}
                   8215:     }
1.864     albertel 8216:     
                   8217:     sub reset_hosts_info {
1.897     albertel 8218: 	&purge_remembered();
1.864     albertel 8219: 	&reset_domain_info();
                   8220: 	&reset_hosts_ip_info();
1.892     albertel 8221: 	undef(%name_to_host);
1.864     albertel 8222: 	undef(%hostname);
                   8223: 	undef(%hostdom);
                   8224: 	undef(%libserv);
                   8225: 	undef($loaded);
                   8226:     }
1.1       albertel 8227: 
1.852     albertel 8228:     sub load_hosts_tab {
1.869     albertel 8229: 	my ($ignore_cache) = @_;
                   8230: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8231: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8232: 	my @config = <$config>;
                   8233: 	&parse_hosts_tab(\@config);
                   8234: 	close($config);
                   8235: 	$loaded=1;
1.1       albertel 8236:     }
1.852     albertel 8237: 
1.838     albertel 8238:     sub hostname {
1.852     albertel 8239: 	&load_hosts_tab() if (!$loaded);
                   8240: 
1.838     albertel 8241: 	my ($lonid) = @_;
                   8242: 	return $hostname{$lonid};
                   8243:     }
1.845     albertel 8244: 
1.838     albertel 8245:     sub all_hostnames {
1.852     albertel 8246: 	&load_hosts_tab() if (!$loaded);
                   8247: 
1.838     albertel 8248: 	return %hostname;
                   8249:     }
1.845     albertel 8250: 
1.888     albertel 8251:     sub all_names {
                   8252: 	&load_hosts_tab() if (!$loaded);
                   8253: 
                   8254: 	return %name_to_host;
                   8255:     }
                   8256: 
1.845     albertel 8257:     sub is_library {
1.852     albertel 8258: 	&load_hosts_tab() if (!$loaded);
                   8259: 
1.845     albertel 8260: 	return exists($libserv{$_[0]});
                   8261:     }
                   8262: 
                   8263:     sub all_library {
1.852     albertel 8264: 	&load_hosts_tab() if (!$loaded);
                   8265: 
1.845     albertel 8266: 	return %libserv;
                   8267:     }
                   8268: 
1.841     albertel 8269:     sub get_servers {
1.852     albertel 8270: 	&load_hosts_tab() if (!$loaded);
                   8271: 
1.841     albertel 8272: 	my ($domain,$type) = @_;
                   8273: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8274: 	                                          : %hostname;
                   8275: 	my %result;
1.842     albertel 8276: 	if (ref($domain) eq 'ARRAY') {
                   8277: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8278: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8279: 		    $result{$host} = $hostname;
                   8280: 		}
                   8281: 	    }
                   8282: 	} else {
                   8283: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8284: 		if ($hostdom{$host} eq $domain) {
                   8285: 		    $result{$host} = $hostname;
                   8286: 		}
1.841     albertel 8287: 	    }
                   8288: 	}
                   8289: 	return %result;
                   8290:     }
1.845     albertel 8291: 
1.844     albertel 8292:     sub host_domain {
1.852     albertel 8293: 	&load_hosts_tab() if (!$loaded);
                   8294: 
1.844     albertel 8295: 	my ($lonid) = @_;
                   8296: 	return $hostdom{$lonid};
                   8297:     }
                   8298: 
1.841     albertel 8299:     sub all_domains {
1.852     albertel 8300: 	&load_hosts_tab() if (!$loaded);
                   8301: 
1.841     albertel 8302: 	my %seen;
                   8303: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8304: 	return @uniq;
                   8305:     }
1.1       albertel 8306: }
                   8307: 
1.847     albertel 8308: { 
                   8309:     my %iphost;
1.856     albertel 8310:     my %name_to_ip;
                   8311:     my %lonid_to_ip;
1.869     albertel 8312: 
1.847     albertel 8313:     sub get_hosts_from_ip {
                   8314: 	my ($ip) = @_;
                   8315: 	my %iphosts = &get_iphost();
                   8316: 	if (ref($iphosts{$ip})) {
                   8317: 	    return @{$iphosts{$ip}};
                   8318: 	}
                   8319: 	return;
1.839     albertel 8320:     }
1.864     albertel 8321:     
                   8322:     sub reset_hosts_ip_info {
                   8323: 	undef(%iphost);
                   8324: 	undef(%name_to_ip);
                   8325: 	undef(%lonid_to_ip);
                   8326:     }
1.856     albertel 8327: 
                   8328:     sub get_host_ip {
                   8329: 	my ($lonid) = @_;
                   8330: 	if (exists($lonid_to_ip{$lonid})) {
                   8331: 	    return $lonid_to_ip{$lonid};
                   8332: 	}
                   8333: 	my $name=&hostname($lonid);
                   8334:    	my $ip = gethostbyname($name);
                   8335: 	return if (!$ip || length($ip) ne 4);
                   8336: 	$ip=inet_ntoa($ip);
                   8337: 	$name_to_ip{$name}   = $ip;
                   8338: 	$lonid_to_ip{$lonid} = $ip;
                   8339: 	return $ip;
                   8340:     }
1.847     albertel 8341:     
                   8342:     sub get_iphost {
1.869     albertel 8343: 	my ($ignore_cache) = @_;
1.894     albertel 8344: 
1.869     albertel 8345: 	if (!$ignore_cache) {
                   8346: 	    if (%iphost) {
                   8347: 		return %iphost;
                   8348: 	    }
                   8349: 	    my ($ip_info,$cached)=
                   8350: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8351: 	    if ($cached) {
                   8352: 		%iphost      = %{$ip_info->[0]};
                   8353: 		%name_to_ip  = %{$ip_info->[1]};
                   8354: 		%lonid_to_ip = %{$ip_info->[2]};
                   8355: 		return %iphost;
                   8356: 	    }
                   8357: 	}
1.894     albertel 8358: 
                   8359: 	# get yesterday's info for fallback
                   8360: 	my %old_name_to_ip;
                   8361: 	my ($ip_info,$cached)=
                   8362: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8363: 	if ($cached) {
                   8364: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8365: 	}
                   8366: 
1.888     albertel 8367: 	my %name_to_host = &all_names();
                   8368: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8369: 	    my $ip;
                   8370: 	    if (!exists($name_to_ip{$name})) {
                   8371: 		$ip = gethostbyname($name);
                   8372: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8373: 		    if (defined($old_name_to_ip{$name})) {
                   8374: 			$ip = $old_name_to_ip{$name};
                   8375: 			&logthis("Can't find $name defaulting to old $ip");
                   8376: 		    } else {
                   8377: 			&logthis("Name $name no IP found");
                   8378: 			next;
                   8379: 		    }
                   8380: 		} else {
                   8381: 		    $ip=inet_ntoa($ip);
1.847     albertel 8382: 		}
                   8383: 		$name_to_ip{$name} = $ip;
                   8384: 	    } else {
                   8385: 		$ip = $name_to_ip{$name};
1.653     albertel 8386: 	    }
1.888     albertel 8387: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8388: 		$lonid_to_ip{$id} = $ip;
                   8389: 	    }
                   8390: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8391: 	}
1.869     albertel 8392: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8393: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8394: 				      48*60*60);
1.869     albertel 8395: 
1.847     albertel 8396: 	return %iphost;
1.598     albertel 8397:     }
                   8398: }
                   8399: 
1.862     albertel 8400: BEGIN {
                   8401: 
                   8402: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8403:     unless ($readit) {
                   8404: {
                   8405:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8406:     %perlvar = (%perlvar,%{$configvars});
                   8407: }
                   8408: 
                   8409: 
1.1       albertel 8410: # ------------------------------------------------------ Read spare server file
                   8411: {
1.448     albertel 8412:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8413: 
                   8414:     while (my $configline=<$config>) {
                   8415:        chomp($configline);
1.284     matthew  8416:        if ($configline) {
1.784     albertel 8417: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8418: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8419: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8420:        }
                   8421:     }
1.448     albertel 8422:     close($config);
1.1       albertel 8423: }
1.11      www      8424: # ------------------------------------------------------------ Read permissions
                   8425: {
1.448     albertel 8426:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8427: 
                   8428:     while (my $configline=<$config>) {
1.448     albertel 8429: 	chomp($configline);
                   8430: 	if ($configline) {
                   8431: 	    my ($role,$perm)=split(/ /,$configline);
                   8432: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8433: 	}
1.11      www      8434:     }
1.448     albertel 8435:     close($config);
1.11      www      8436: }
                   8437: 
                   8438: # -------------------------------------------- Read plain texts for permissions
                   8439: {
1.448     albertel 8440:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8441: 
                   8442:     while (my $configline=<$config>) {
1.448     albertel 8443: 	chomp($configline);
                   8444: 	if ($configline) {
1.742     raeburn  8445: 	    my ($short,@plain)=split(/:/,$configline);
                   8446:             %{$prp{$short}} = ();
                   8447: 	    if (@plain > 0) {
                   8448:                 $prp{$short}{'std'} = $plain[0];
                   8449:                 for (my $i=1; $i<@plain; $i++) {
                   8450:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8451:                 }
                   8452:             }
1.448     albertel 8453: 	}
1.135     www      8454:     }
1.448     albertel 8455:     close($config);
1.135     www      8456: }
                   8457: 
                   8458: # ---------------------------------------------------------- Read package table
                   8459: {
1.448     albertel 8460:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8461: 
                   8462:     while (my $configline=<$config>) {
1.483     albertel 8463: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8464: 	chomp($configline);
                   8465: 	my ($short,$plain)=split(/:/,$configline);
                   8466: 	my ($pack,$name)=split(/\&/,$short);
                   8467: 	if ($plain ne '') {
                   8468: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8469: 	    $packagetab{$short}=$plain; 
                   8470: 	}
1.11      www      8471:     }
1.448     albertel 8472:     close($config);
1.329     matthew  8473: }
                   8474: 
                   8475: # ------------- set up temporary directory
                   8476: {
                   8477:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8478: 
1.11      www      8479: }
                   8480: 
1.794     albertel 8481: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8482: 				'compress_threshold'=> 20_000,
                   8483:  			        });
1.185     www      8484: 
1.281     www      8485: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8486: $dumpcount=0;
1.22      www      8487: 
1.163     harris41 8488: &logtouch();
1.672     albertel 8489: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8490: $readit=1;
1.564     albertel 8491:     {
                   8492: 	use integer;
                   8493: 	my $test=(2**32)+1;
1.568     albertel 8494: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8495: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8496:     }
1.195     www      8497: }
1.1       albertel 8498: }
1.179     www      8499: 
1.1       albertel 8500: 1;
1.191     harris41 8501: __END__
                   8502: 
1.243     albertel 8503: =pod
                   8504: 
1.191     harris41 8505: =head1 NAME
                   8506: 
1.243     albertel 8507: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8508: 
                   8509: =head1 SYNOPSIS
                   8510: 
1.243     albertel 8511: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8512: 
                   8513:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8514: 
1.243     albertel 8515: Common parameters:
                   8516: 
                   8517: =over 4
                   8518: 
                   8519: =item *
                   8520: 
                   8521: $uname : an internal username (if $cname expecting a course Id specifically)
                   8522: 
                   8523: =item *
                   8524: 
                   8525: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8526: 
                   8527: =item *
                   8528: 
                   8529: $symb : a resource instance identifier
                   8530: 
                   8531: =item *
                   8532: 
                   8533: $namespace : the name of a .db file that contains the data needed or
                   8534: being set.
                   8535: 
                   8536: =back
                   8537: 
1.394     bowersj2 8538: =head1 OVERVIEW
1.191     harris41 8539: 
1.394     bowersj2 8540: lonnet provides subroutines which interact with the
                   8541: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8542: about classes, users, and resources.
1.243     albertel 8543: 
                   8544: For many of these objects you can also use this to store data about
                   8545: them or modify them in various ways.
1.191     harris41 8546: 
1.394     bowersj2 8547: =head2 Symbs
1.191     harris41 8548: 
1.394     bowersj2 8549: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8550: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8551: map, the resource number of the resource in the map, and the URL of
                   8552: the resource itself. The latter is somewhat redundant, but might help
                   8553: if maps change.
                   8554: 
                   8555: An example is
                   8556: 
                   8557:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8558: 
                   8559: The respective map entry is
                   8560: 
                   8561:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8562:   title="Problem 2">
                   8563:  </resource>
                   8564: 
                   8565: Symbs are used by the random number generator, as well as to store and
                   8566: restore data specific to a certain instance of for example a problem.
                   8567: 
                   8568: =head2 Storing And Retrieving Data
                   8569: 
                   8570: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8571: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8572: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8573: is is the non-critical message twin of cstore. These functions are for
                   8574: handlers to store a perl hash to a user's permanent data space in an
                   8575: easy manner, and to retrieve it again on another call. It is expected
                   8576: that a handler would use this once at the beginning to retrieve data,
                   8577: and then again once at the end to send only the new data back.
                   8578: 
                   8579: The data is stored in the user's data directory on the user's
                   8580: homeserver under the ID of the course.
                   8581: 
                   8582: The hash that is returned by restore will have all of the previous
                   8583: value for all of the elements of the hash.
                   8584: 
                   8585: Example:
                   8586: 
                   8587:  #creating a hash
                   8588:  my %hash;
                   8589:  $hash{'foo'}='bar';
                   8590: 
                   8591:  #storing it
                   8592:  &Apache::lonnet::cstore(\%hash);
                   8593: 
                   8594:  #changing a value
                   8595:  $hash{'foo'}='notbar';
                   8596: 
                   8597:  #adding a new value
                   8598:  $hash{'bar'}='foo';
                   8599:  &Apache::lonnet::cstore(\%hash);
                   8600: 
                   8601:  #retrieving the hash
                   8602:  my %history=&Apache::lonnet::restore();
                   8603: 
                   8604:  #print the hash
                   8605:  foreach my $key (sort(keys(%history))) {
                   8606:    print("\%history{$key} = $history{$key}");
                   8607:  }
                   8608: 
                   8609: Will print out:
1.191     harris41 8610: 
1.394     bowersj2 8611:  %history{1:foo} = bar
                   8612:  %history{1:keys} = foo:timestamp
                   8613:  %history{1:timestamp} = 990455579
                   8614:  %history{2:bar} = foo
                   8615:  %history{2:foo} = notbar
                   8616:  %history{2:keys} = foo:bar:timestamp
                   8617:  %history{2:timestamp} = 990455580
                   8618:  %history{bar} = foo
                   8619:  %history{foo} = notbar
                   8620:  %history{timestamp} = 990455580
                   8621:  %history{version} = 2
                   8622: 
                   8623: Note that the special hash entries C<keys>, C<version> and
                   8624: C<timestamp> were added to the hash. C<version> will be equal to the
                   8625: total number of versions of the data that have been stored. The
                   8626: C<timestamp> attribute will be the UNIX time the hash was
                   8627: stored. C<keys> is available in every historical section to list which
                   8628: keys were added or changed at a specific historical revision of a
                   8629: hash.
                   8630: 
                   8631: B<Warning>: do not store the hash that restore returns directly. This
                   8632: will cause a mess since it will restore the historical keys as if the
                   8633: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8634: 
1.394     bowersj2 8635: Calling convention:
1.191     harris41 8636: 
1.394     bowersj2 8637:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8638:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8639: 
1.394     bowersj2 8640: For more detailed information, see lonnet specific documentation.
1.191     harris41 8641: 
1.394     bowersj2 8642: =head1 RETURN MESSAGES
1.191     harris41 8643: 
1.394     bowersj2 8644: =over 4
1.191     harris41 8645: 
1.394     bowersj2 8646: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8647: 
1.394     bowersj2 8648: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8649: when the connection is brought back up
1.191     harris41 8650: 
1.394     bowersj2 8651: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8652: for later delivery
1.191     harris41 8653: 
1.394     bowersj2 8654: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8655: 
1.394     bowersj2 8656: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8657: that was requested
1.191     harris41 8658: 
1.243     albertel 8659: =back
1.191     harris41 8660: 
1.243     albertel 8661: =head1 PUBLIC SUBROUTINES
1.191     harris41 8662: 
1.243     albertel 8663: =head2 Session Environment Functions
1.191     harris41 8664: 
1.243     albertel 8665: =over 4
1.191     harris41 8666: 
1.394     bowersj2 8667: =item * 
                   8668: X<appenv()>
                   8669: B<appenv(%hash)>: the value of %hash is written to
                   8670: the user envirnoment file, and will be restored for each access this
1.620     albertel 8671: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8672: process
1.191     harris41 8673: 
                   8674: =item *
1.394     bowersj2 8675: X<delenv()>
                   8676: B<delenv($regexp)>: removes all items from the session
                   8677: environment file that matches the regular expression in $regexp. The
1.620     albertel 8678: values are also delted from the current processes %env.
1.191     harris41 8679: 
1.795     albertel 8680: =item * get_env_multiple($name) 
                   8681: 
                   8682: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8683: values may be defined and end up as an array ref.
                   8684: 
                   8685: returns an array of values
                   8686: 
1.243     albertel 8687: =back
                   8688: 
                   8689: =head2 User Information
1.191     harris41 8690: 
1.243     albertel 8691: =over 4
1.191     harris41 8692: 
                   8693: =item *
1.394     bowersj2 8694: X<queryauthenticate()>
                   8695: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8696: authentication scheme
                   8697: 
                   8698: =item *
1.394     bowersj2 8699: X<authenticate()>
                   8700: B<authenticate($uname,$upass,$udom)>: try to
                   8701: authenticate user from domain's lib servers (first use the current
                   8702: one). C<$upass> should be the users password.
1.191     harris41 8703: 
                   8704: =item *
1.394     bowersj2 8705: X<homeserver()>
                   8706: B<homeserver($uname,$udom)>: find the server which has
                   8707: the user's directory and files (there must be only one), this caches
                   8708: the answer, and also caches if there is a borken connection.
1.191     harris41 8709: 
                   8710: =item *
1.394     bowersj2 8711: X<idget()>
                   8712: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8713: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8714: username, and only 1 username per ID in a specific domain) (returns
                   8715: hash: id=>name,id=>name)
1.191     harris41 8716: 
                   8717: =item *
1.394     bowersj2 8718: X<idrget()>
                   8719: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8720: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8721: 
                   8722: =item *
1.394     bowersj2 8723: X<idput()>
                   8724: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8725: 
                   8726: =item *
1.394     bowersj2 8727: X<rolesinit()>
                   8728: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8729: 
                   8730: =item *
1.551     albertel 8731: X<getsection()>
                   8732: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8733: course $cname, return section name/number or '' for "not in course"
                   8734: and '-1' for "no section"
                   8735: 
                   8736: =item *
1.394     bowersj2 8737: X<userenvironment()>
                   8738: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8739: passed in @what from the requested user's environment, returns a hash
                   8740: 
1.858     raeburn  8741: =item * 
                   8742: X<userlog_query()>
1.859     albertel 8743: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8744: activity.log file. %filters defines filters applied when parsing the
                   8745: log file. These can be start or end timestamps, or the type of action
                   8746: - log to look for Login or Logout events, check for Checkin or
                   8747: Checkout, role for role selection. The response is in the form
                   8748: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8749: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8750: 
1.243     albertel 8751: =back
                   8752: 
                   8753: =head2 User Roles
                   8754: 
                   8755: =over 4
                   8756: 
                   8757: =item *
                   8758: 
1.810     raeburn  8759: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8760:  F: full access
                   8761:  U,I,K: authentication modes (cxx only)
                   8762:  '': forbidden
                   8763:  1: user needs to choose course
                   8764:  2: browse allowed
1.766     albertel 8765:  A: passphrase authentication needed
1.243     albertel 8766: 
                   8767: =item *
                   8768: 
                   8769: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8770: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8771: and course level
                   8772: 
                   8773: =item *
                   8774: 
                   8775: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8776: explanation of a user role term
                   8777: 
1.832     raeburn  8778: =item *
                   8779: 
1.858     raeburn  8780: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8781: All arguments are optional. Returns a hash of a roles, either for
                   8782: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8783: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8784: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8785: and value is set to colon-separated start and end times for the role.
                   8786: If no username and domain are specified, will default to current
                   8787: user/domain. Types, roles, and roledoms are references to arrays,
                   8788: of role statuses (active, future or previous), roles 
                   8789: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8790: to restrict the list of roles reported. If no array ref is 
                   8791: provided for types, will default to return only active roles.
1.834     albertel 8792: 
1.243     albertel 8793: =back
                   8794: 
                   8795: =head2 User Modification
                   8796: 
                   8797: =over 4
                   8798: 
                   8799: =item *
                   8800: 
                   8801: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8802: user for the level given by URL.  Optional start and end dates (leave empty
                   8803: string or zero for "no date")
1.191     harris41 8804: 
                   8805: =item *
                   8806: 
1.243     albertel 8807: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8808: change a users, password, possible return values are: ok,
                   8809: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8810: refused
1.191     harris41 8811: 
                   8812: =item *
                   8813: 
1.243     albertel 8814: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8815: 
                   8816: =item *
                   8817: 
1.243     albertel 8818: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8819: modify user
1.191     harris41 8820: 
                   8821: =item *
                   8822: 
1.286     matthew  8823: modifystudent
                   8824: 
                   8825: modify a students enrollment and identification information.
                   8826: The course id is resolved based on the current users environment.  
                   8827: This means the envoking user must be a course coordinator or otherwise
                   8828: associated with a course.
                   8829: 
1.297     matthew  8830: This call is essentially a wrapper for lonnet::modifyuser and
                   8831: lonnet::modify_student_enrollment
1.286     matthew  8832: 
                   8833: Inputs: 
                   8834: 
                   8835: =over 4
                   8836: 
                   8837: =item B<$udom> Students loncapa domain
                   8838: 
                   8839: =item B<$uname> Students loncapa login name
                   8840: 
                   8841: =item B<$uid> Students id/student number
                   8842: 
                   8843: =item B<$umode> Students authentication mode
                   8844: 
                   8845: =item B<$upass> Students password
                   8846: 
                   8847: =item B<$first> Students first name
                   8848: 
                   8849: =item B<$middle> Students middle name
                   8850: 
                   8851: =item B<$last> Students last name
                   8852: 
                   8853: =item B<$gene> Students generation
                   8854: 
                   8855: =item B<$usec> Students section in course
                   8856: 
                   8857: =item B<$end> Unix time of the roles expiration
                   8858: 
                   8859: =item B<$start> Unix time of the roles start date
                   8860: 
                   8861: =item B<$forceid> If defined, allow $uid to be changed
                   8862: 
                   8863: =item B<$desiredhome> server to use as home server for student
                   8864: 
                   8865: =back
1.297     matthew  8866: 
                   8867: =item *
                   8868: 
                   8869: modify_student_enrollment
                   8870: 
                   8871: Change a students enrollment status in a class.  The environment variable
                   8872: 'role.request.course' must be defined for this function to proceed.
                   8873: 
                   8874: Inputs:
                   8875: 
                   8876: =over 4
                   8877: 
                   8878: =item $udom, students domain
                   8879: 
                   8880: =item $uname, students name
                   8881: 
                   8882: =item $uid, students user id
                   8883: 
                   8884: =item $first, students first name
                   8885: 
                   8886: =item $middle
                   8887: 
                   8888: =item $last
                   8889: 
                   8890: =item $gene
                   8891: 
                   8892: =item $usec
                   8893: 
                   8894: =item $end
                   8895: 
                   8896: =item $start
                   8897: 
                   8898: =back
                   8899: 
1.191     harris41 8900: 
                   8901: =item *
                   8902: 
1.243     albertel 8903: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8904: custom role; give a custom role to a user for the level given by URL.  Specify
                   8905: name and domain of role author, and role name
1.191     harris41 8906: 
                   8907: =item *
                   8908: 
1.243     albertel 8909: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8910: 
                   8911: =item *
                   8912: 
1.243     albertel 8913: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8914: 
                   8915: =back
                   8916: 
                   8917: =head2 Course Infomation
                   8918: 
                   8919: =over 4
1.191     harris41 8920: 
                   8921: =item *
                   8922: 
1.631     albertel 8923: coursedescription($courseid) : returns a hash of information about the
                   8924: specified course id, including all environment settings for the
                   8925: course, the description of the course will be in the hash under the
                   8926: key 'description'
1.191     harris41 8927: 
                   8928: =item *
                   8929: 
1.624     albertel 8930: resdata($name,$domain,$type,@which) : request for current parameter
                   8931: setting for a specific $type, where $type is either 'course' or 'user',
                   8932: @what should be a list of parameters to ask about. This routine caches
                   8933: answers for 5 minutes.
1.243     albertel 8934: 
1.877     foxr     8935: =item *
                   8936: 
                   8937: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8938: data base, returning a hash that is keyed by the resource name and has
                   8939: values that are the resource value.  I believe that the timestamps and
                   8940: versions are also returned.
                   8941: 
                   8942: 
1.243     albertel 8943: =back
                   8944: 
                   8945: =head2 Course Modification
                   8946: 
                   8947: =over 4
1.191     harris41 8948: 
                   8949: =item *
                   8950: 
1.243     albertel 8951: writecoursepref($courseid,%prefs) : write preferences (environment
                   8952: database) for a course
1.191     harris41 8953: 
                   8954: =item *
                   8955: 
1.243     albertel 8956: createcourse($udom,$description,$url) : make/modify course
                   8957: 
                   8958: =back
                   8959: 
                   8960: =head2 Resource Subroutines
                   8961: 
                   8962: =over 4
1.191     harris41 8963: 
                   8964: =item *
                   8965: 
1.243     albertel 8966: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8967: 
                   8968: =item *
                   8969: 
1.243     albertel 8970: repcopy($filename) : subscribes to the requested file, and attempts to
                   8971: replicate from the owning library server, Might return
1.607     raeburn  8972: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8973: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8974: resource. Expects the local filesystem pathname
                   8975: (/home/httpd/html/res/....)
                   8976: 
                   8977: =back
                   8978: 
                   8979: =head2 Resource Information
                   8980: 
                   8981: =over 4
1.191     harris41 8982: 
                   8983: =item *
                   8984: 
1.243     albertel 8985: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8986: a vairety of different possible values, $varname should be a request
                   8987: string, and the other parameters can be used to specify who and what
                   8988: one is asking about.
                   8989: 
                   8990: Possible values for $varname are environment.lastname (or other item
                   8991: from the envirnment hash), user.name (or someother aspect about the
                   8992: user), resource.0.maxtries (or some other part and parameter of a
                   8993: resource)
1.204     albertel 8994: 
                   8995: =item *
                   8996: 
1.243     albertel 8997: directcondval($number) : get current value of a condition; reads from a state
                   8998: string
1.204     albertel 8999: 
                   9000: =item *
                   9001: 
1.243     albertel 9002: condval($condidx) : value of condition index based on state
1.204     albertel 9003: 
                   9004: =item *
                   9005: 
1.243     albertel 9006: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9007: resource's metadata, $what should be either a specific key, or either
                   9008: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9009: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9010: 
                   9011: this function automatically caches all requests
1.191     harris41 9012: 
                   9013: =item *
                   9014: 
1.243     albertel 9015: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9016: network of library servers; returns file handle of where SQL and regex results
                   9017: will be stored for query
1.191     harris41 9018: 
                   9019: =item *
                   9020: 
1.243     albertel 9021: symbread($filename) : return symbolic list entry (filename argument optional);
                   9022: returns the data handle
1.191     harris41 9023: 
                   9024: =item *
                   9025: 
1.243     albertel 9026: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9027: a possible symb for the URL in $thisfn, and if is an encryypted
                   9028: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9029: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9030: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9031: 
1.191     harris41 9032: 
                   9033: =item *
                   9034: 
1.243     albertel 9035: symbclean($symb) : removes versions numbers from a symb, returns the
                   9036: cleaned symb
1.191     harris41 9037: 
                   9038: =item *
                   9039: 
1.243     albertel 9040: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9041: course map, user must be in a course for it to work.
1.191     harris41 9042: 
                   9043: =item *
                   9044: 
1.243     albertel 9045: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9046: 
                   9047: =item *
                   9048: 
1.243     albertel 9049: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9050: a random seed, all arguments are optional, if they aren't sent it uses the
                   9051: environment to derive them. Note: if symb isn't sent and it can't get one
                   9052: from &symbread it will use the current time as its return value
1.191     harris41 9053: 
                   9054: =item *
                   9055: 
1.243     albertel 9056: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9057: unfakeable, receipt
1.191     harris41 9058: 
                   9059: =item *
                   9060: 
1.620     albertel 9061: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9062: 
                   9063: =item *
                   9064: 
1.243     albertel 9065: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9066: 
                   9067: =item *
                   9068: 
1.243     albertel 9069: 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 9070: 
                   9071: =item *
                   9072: 
1.243     albertel 9073: 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 9074: 
                   9075: =item *
                   9076: 
1.243     albertel 9077: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9078: 
                   9079: =item *
                   9080: 
1.243     albertel 9081: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9082: forcing spreadsheet to reevaluate the resource scores next time.
                   9083: 
                   9084: =back
                   9085: 
                   9086: =head2 Storing/Retreiving Data
                   9087: 
                   9088: =over 4
1.191     harris41 9089: 
                   9090: =item *
                   9091: 
1.243     albertel 9092: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9093: for this url; hashref needs to be given and should be a \%hashname; the
                   9094: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9095: be derived from the env
1.191     harris41 9096: 
                   9097: =item *
                   9098: 
1.243     albertel 9099: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9100: uses critical subroutine
1.191     harris41 9101: 
                   9102: =item *
                   9103: 
1.243     albertel 9104: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9105: all args are optional
1.191     harris41 9106: 
                   9107: =item *
                   9108: 
1.717     albertel 9109: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9110: dumps the complete (or key matching regexp) namespace into a hash
                   9111: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9112: normally &store()ed into
                   9113: 
                   9114: $range should be either an integer '100' (give me the first 100
                   9115:                                            matching records)
                   9116:               or be  two integers sperated by a - with no spaces
                   9117:                  '30-50' (give me the 30th through the 50th matching
                   9118:                           records)
                   9119: 
                   9120: 
                   9121: =item *
                   9122: 
                   9123: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9124: replaces a &store() version of data with a replacement set of data
                   9125: for a particular resource in a namespace passed in the $storehash hash 
                   9126: reference
                   9127: 
                   9128: =item *
                   9129: 
1.243     albertel 9130: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9131: works very similar to store/cstore, but all data is stored in a
                   9132: temporary location and can be reset using tmpreset, $storehash should
                   9133: be a hash reference, returns nothing on success
1.191     harris41 9134: 
                   9135: =item *
                   9136: 
1.243     albertel 9137: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9138: similar to restore, but all data is stored in a temporary location and
                   9139: can be reset using tmpreset. Returns a hash of values on success,
                   9140: error string otherwise.
1.191     harris41 9141: 
                   9142: =item *
                   9143: 
1.243     albertel 9144: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9145: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9146: 
                   9147: =item *
                   9148: 
1.243     albertel 9149: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9150: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9151: 
                   9152: =item *
                   9153: 
1.243     albertel 9154: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9155: namesp ($udom and $uname are optional)
1.191     harris41 9156: 
                   9157: =item *
                   9158: 
1.702     albertel 9159: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9160: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9161: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9162: 
1.702     albertel 9163: $range should be either an integer '100' (give me the first 100
                   9164:                                            matching records)
                   9165:               or be  two integers sperated by a - with no spaces
                   9166:                  '30-50' (give me the 30th through the 50th matching
                   9167:                           records)
1.449     matthew  9168: =item *
                   9169: 
                   9170: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9171: $store can be a scalar, an array reference, or if the amount to be 
                   9172: incremented is > 1, a hash reference.
                   9173: 
                   9174: ($udom and $uname are optional)
1.191     harris41 9175: 
                   9176: =item *
                   9177: 
1.243     albertel 9178: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9179: ($udom and $uname are optional)
1.191     harris41 9180: 
                   9181: =item *
                   9182: 
1.243     albertel 9183: cput($namespace,$storehash,$udom,$uname) : critical put
                   9184: ($udom and $uname are optional)
1.191     harris41 9185: 
                   9186: =item *
                   9187: 
1.748     albertel 9188: newput($namespace,$storehash,$udom,$uname) :
                   9189: 
                   9190: Attempts to store the items in the $storehash, but only if they don't
                   9191: currently exist, if this succeeds you can be certain that you have 
                   9192: successfully created a new key value pair in the $namespace db.
                   9193: 
                   9194: 
                   9195: Args:
                   9196:  $namespace: name of database to store values to
                   9197:  $storehash: hashref to store to the db
                   9198:  $udom: (optional) domain of user containing the db
                   9199:  $uname: (optional) name of user caontaining the db
                   9200: 
                   9201: Returns:
                   9202:  'ok' -> succeeded in storing all keys of $storehash
                   9203:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9204:                         least <key> already existed in the db (other
                   9205:                         requested keys may also already exist)
                   9206:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9207:  'con_lost' -> unable to contact request server
                   9208:  'refused' -> action was not allowed by remote machine
                   9209: 
                   9210: 
                   9211: =item *
                   9212: 
1.243     albertel 9213: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9214: reference filled in from namesp (encrypts the return communication)
                   9215: ($udom and $uname are optional)
1.191     harris41 9216: 
                   9217: =item *
                   9218: 
1.243     albertel 9219: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9220: critical subroutine
                   9221: 
1.806     raeburn  9222: =item *
                   9223: 
1.860     raeburn  9224: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9225: array reference filled in from namespace found in domain level on either
                   9226: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9227: 
                   9228: =item *
                   9229: 
1.860     raeburn  9230: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9231: domain level either on specified domain server ($uhome) or primary domain 
                   9232: server ($udom and $uhome are optional)
1.806     raeburn  9233: 
1.243     albertel 9234: =back
                   9235: 
                   9236: =head2 Network Status Functions
                   9237: 
                   9238: =over 4
1.191     harris41 9239: 
                   9240: =item *
                   9241: 
                   9242: dirlist($uri) : return directory list based on URI
                   9243: 
                   9244: =item *
                   9245: 
1.243     albertel 9246: spareserver() : find server with least workload from spare.tab
                   9247: 
                   9248: =back
                   9249: 
                   9250: =head2 Apache Request
                   9251: 
                   9252: =over 4
1.191     harris41 9253: 
                   9254: =item *
                   9255: 
1.243     albertel 9256: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9257: localhost, posts hash
                   9258: 
                   9259: =back
                   9260: 
                   9261: =head2 Data to String to Data
                   9262: 
                   9263: =over 4
1.191     harris41 9264: 
                   9265: =item *
                   9266: 
1.243     albertel 9267: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9268: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9269: 
                   9270: =item *
                   9271: 
1.243     albertel 9272: hashref2str($hashref) : convert a hashref into a string complete with
                   9273: escaping and '=' and '&' separators, supports elements that are
                   9274: arrayrefs and hashrefs
1.191     harris41 9275: 
                   9276: =item *
                   9277: 
1.243     albertel 9278: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9279: with escaping and '&' separators, supports elements that are arrayrefs
                   9280: and hashrefs
1.191     harris41 9281: 
                   9282: =item *
                   9283: 
1.243     albertel 9284: str2hash($string) : convert string to hash using unescaping and
                   9285: splitting on '=' and '&', supports elements that are arrayrefs and
                   9286: hashrefs
1.191     harris41 9287: 
                   9288: =item *
                   9289: 
1.243     albertel 9290: str2array($string) : convert string to hash using unescaping and
                   9291: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9292: 
                   9293: =back
                   9294: 
                   9295: =head2 Logging Routines
                   9296: 
                   9297: =over 4
                   9298: 
                   9299: These routines allow one to make log messages in the lonnet.log and
                   9300: lonnet.perm logfiles.
1.191     harris41 9301: 
                   9302: =item *
                   9303: 
1.243     albertel 9304: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9305: 
                   9306: =item *
                   9307: 
1.243     albertel 9308: logthis() : append message to the normal lonnet.log file, it gets
                   9309: preiodically rolled over and deleted.
1.191     harris41 9310: 
                   9311: =item *
                   9312: 
1.243     albertel 9313: logperm() : append a permanent message to lonnet.perm.log, this log
                   9314: file never gets deleted by any automated portion of the system, only
                   9315: messages of critical importance should go in here.
                   9316: 
                   9317: =back
                   9318: 
                   9319: =head2 General File Helper Routines
                   9320: 
                   9321: =over 4
1.191     harris41 9322: 
                   9323: =item *
                   9324: 
1.481     raeburn  9325: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9326: (a) files in /uploaded
                   9327:   (i) If a local copy of the file exists - 
                   9328:       compares modification date of local copy with last-modified date for 
                   9329:       definitive version stored on home server for course. If local copy is 
                   9330:       stale, requests a new version from the home server and stores it. 
                   9331:       If the original has been removed from the home server, then local copy 
                   9332:       is unlinked.
                   9333:   (ii) If local copy does not exist -
                   9334:       requests the file from the home server and stores it. 
                   9335:   
                   9336:   If $caller is 'uploadrep':  
                   9337:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9338:     for request for files originally uploaded via DOCS. 
                   9339:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9340:   
                   9341:   Otherwise:
                   9342:      This indicates a call from the content generation phase of the request.
                   9343:      -  returns the entire contents of the file or -1.
                   9344:      
                   9345: (b) files in /res
                   9346:    - returns the entire contents of a file or -1; 
                   9347:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9348: 
1.712     albertel 9349: 
                   9350: =item *
                   9351: 
                   9352: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9353:                   reference
                   9354: 
                   9355: returns either a stat() list of data about the file or an empty list
                   9356: if the file doesn't exist or couldn't find out about it (connection
                   9357: problems or user unknown)
                   9358: 
1.191     harris41 9359: =item *
                   9360: 
1.243     albertel 9361: filelocation($dir,$file) : returns file system location of a file
                   9362: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9363: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9364: and a file of ../bob will become /a/bob)
1.191     harris41 9365: 
                   9366: =item *
                   9367: 
                   9368: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9369: filelocation except for hrefs
                   9370: 
                   9371: =item *
                   9372: 
                   9373: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9374: 
1.243     albertel 9375: =back
                   9376: 
1.608     albertel 9377: =head2 Usererfile file routines (/uploaded*)
                   9378: 
                   9379: =over 4
                   9380: 
                   9381: =item *
                   9382: 
                   9383: userfileupload(): main rotine for putting a file in a user or course's
                   9384:                   filespace, arguments are,
                   9385: 
1.620     albertel 9386:  formname - required - this is the name of the element in $env where the
1.608     albertel 9387:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9388:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9389:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9390:  coursedoc - if true, store the file in the course of the active role
                   9391:              of the current user
                   9392:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9393:          if undefined, it will be placed in "unknown"
                   9394: 
                   9395:  (This routine calls clean_filename() to remove any dangerous
                   9396:  characters from the filename, and then calls finuserfileupload() to
                   9397:  complete the transaction)
                   9398: 
                   9399:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9400:  and /adm/notfound.html if unsuccessful
                   9401: 
                   9402: =item *
                   9403: 
                   9404: clean_filename(): routine for cleaing a filename up for storage in
                   9405:                  userfile space, argument is:
                   9406: 
                   9407:  filename - proposed filename
                   9408: 
                   9409: returns: the new clean filename
                   9410: 
                   9411: =item *
                   9412: 
                   9413: finishuserfileupload(): routine that creaes and sends the file to
                   9414: userspace, probably shouldn't be called directly
                   9415: 
                   9416:   docuname: username or courseid of destination for the file
                   9417:   docudom: domain of user/course of destination for the file
                   9418:   formname: same as for userfileupload()
                   9419:   fname: filename (inculding subdirectories) for the file
                   9420: 
                   9421:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9422:  and /adm/notfound.html if unsuccessful
                   9423: 
                   9424: =item *
                   9425: 
                   9426: renameuserfile(): renames an existing userfile to a new name
                   9427: 
                   9428:   Args:
                   9429:    docuname: username or courseid of destination for the file
                   9430:    docudom: domain of user/course of destination for the file
                   9431:    old: current file name (including any subdirs under userfiles)
                   9432:    new: desired file name (including any subdirs under userfiles)
                   9433: 
                   9434: =item *
                   9435: 
                   9436: mkdiruserfile(): creates a directory is a userfiles dir
                   9437: 
                   9438:   Args:
                   9439:    docuname: username or courseid of destination for the file
                   9440:    docudom: domain of user/course of destination for the file
                   9441:    dir: dir to create (including any subdirs under userfiles)
                   9442: 
                   9443: =item *
                   9444: 
                   9445: removeuserfile(): removes a file that exists in userfiles
                   9446: 
                   9447:   Args:
                   9448:    docuname: username or courseid of destination for the file
                   9449:    docudom: domain of user/course of destination for the file
                   9450:    fname: filname to delete (including any subdirs under userfiles)
                   9451: 
                   9452: =item *
                   9453: 
                   9454: removeuploadedurl(): convience function for removeuserfile()
                   9455: 
                   9456:   Args:
                   9457:    url:  a full /uploaded/... url to delete
                   9458: 
1.747     albertel 9459: =item * 
                   9460: 
                   9461: get_portfile_permissions():
                   9462:   Args:
                   9463:     domain: domain of user or course contain the portfolio files
                   9464:     user: name of user or num of course contain the portfolio files
                   9465:   Returns:
                   9466:     hashref of a dump of the proper file_permissions.db
                   9467:    
                   9468: 
                   9469: =item * 
                   9470: 
                   9471: get_access_controls():
                   9472: 
                   9473: Args:
                   9474:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9475:   group: (optional) the group you want the files associated with
                   9476:   file: (optional) the file you want access info on
                   9477: 
                   9478: Returns:
1.749     raeburn  9479:     a hash (keys are file names) of hashes containing
                   9480:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9481:         values are XML containing access control settings (see below) 
1.747     albertel 9482: 
                   9483: Internal notes:
                   9484: 
1.749     raeburn  9485:  access controls are stored in file_permissions.db as key=value pairs.
                   9486:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9487:         where scope -> public,guest,course,group,domains or users.
                   9488:               end -> UNIX time for end of access (0 -> no end date)
                   9489:               start -> UNIX time for start of access
                   9490: 
                   9491:     value -> XML description of access control
                   9492:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9493:             <start></start>
                   9494:             <end></end>
                   9495: 
                   9496:             <password></password>  for scope type = guest
                   9497: 
                   9498:             <domain></domain>     for scope type = course or group
                   9499:             <number></number>
                   9500:             <roles id="">
                   9501:              <role></role>
                   9502:              <access></access>
                   9503:              <section></section>
                   9504:              <group></group>
                   9505:             </roles>
                   9506: 
                   9507:             <dom></dom>         for scope type = domains
                   9508: 
                   9509:             <users>             for scope type = users
                   9510:              <user>
                   9511:               <uname></uname>
                   9512:               <udom></udom>
                   9513:              </user>
                   9514:             </users>
                   9515:            </scope> 
                   9516:               
                   9517:  Access data is also aggregated for each file in an additional key=value pair:
                   9518:  key -> path to file/file_name\0accesscontrol 
                   9519:  value -> reference to hash
                   9520:           hash contains key = value pairs
                   9521:           where key = uniqueID:scope_end_start
                   9522:                 value = UNIX time record was last updated
                   9523: 
                   9524:           Used to improve speed of look-ups of access controls for each file.  
                   9525:  
                   9526:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9527: 
                   9528: modify_access_controls():
                   9529: 
                   9530: Modifies access controls for a portfolio file
                   9531: Args
                   9532: 1. file name
                   9533: 2. reference to hash of required changes,
                   9534: 3. domain
                   9535: 4. username
                   9536:   where domain,username are the domain of the portfolio owner 
                   9537:   (either a user or a course) 
                   9538: 
                   9539: Returns:
                   9540: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9541: 2. result of deletions ('ok' or 'error', with error message).
                   9542: 3. reference to hash of any new or updated access controls.
                   9543: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9544:    key = integer (inbound ID)
                   9545:    value = uniqueID  
1.747     albertel 9546: 
1.608     albertel 9547: =back
                   9548: 
1.243     albertel 9549: =head2 HTTP Helper Routines
                   9550: 
                   9551: =over 4
                   9552: 
1.191     harris41 9553: =item *
                   9554: 
                   9555: escape() : unpack non-word characters into CGI-compatible hex codes
                   9556: 
                   9557: =item *
                   9558: 
                   9559: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9560: 
1.243     albertel 9561: =back
                   9562: 
                   9563: =head1 PRIVATE SUBROUTINES
                   9564: 
                   9565: =head2 Underlying communication routines (Shouldn't call)
                   9566: 
                   9567: =over 4
                   9568: 
                   9569: =item *
                   9570: 
                   9571: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9572: 
                   9573: =item *
                   9574: 
                   9575: reply() : uses subreply to send a message to remote machine, logs all failures
                   9576: 
                   9577: =item *
                   9578: 
                   9579: critical() : passes a critical message to another server; if cannot
                   9580: get through then place message in connection buffer directory and
                   9581: returns con_delayed, if incapable of saving message, returns
                   9582: con_failed
                   9583: 
                   9584: =item *
                   9585: 
                   9586: reconlonc() : tries to reconnect lonc client processes.
                   9587: 
                   9588: =back
                   9589: 
                   9590: =head2 Resource Access Logging
                   9591: 
                   9592: =over 4
                   9593: 
                   9594: =item *
                   9595: 
                   9596: flushcourselogs() : flush (save) buffer logs and access logs
                   9597: 
                   9598: =item *
                   9599: 
                   9600: courselog($what) : save message for course in hash
                   9601: 
                   9602: =item *
                   9603: 
                   9604: courseacclog($what) : save message for course using &courselog().  Perform
                   9605: special processing for specific resource types (problems, exams, quizzes, etc).
                   9606: 
1.191     harris41 9607: =item *
                   9608: 
                   9609: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9610: as a PerlChildExitHandler
1.243     albertel 9611: 
                   9612: =back
                   9613: 
                   9614: =head2 Other
                   9615: 
                   9616: =over 4
                   9617: 
                   9618: =item *
                   9619: 
                   9620: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9621: 
                   9622: =back
                   9623: 
                   9624: =cut
1.877     foxr     9625: 

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