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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.943   ! raeburn     4: # $Id: lonnet.pm,v 1.942 2008/02/21 10:04:35 foxr 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: sub userload {
                    517:     my $numusers=0;
                    518:     {
                    519: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    520: 	my $filename;
                    521: 	my $curtime=time;
                    522: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  523: 	    next if ($filename eq '.' || $filename eq '..');
                    524: 	    next if ($filename =~ /publicuser_\d+\.id/);
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 {
1.923     raeburn  1050:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  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')) {
1.923     raeburn  1058:                 my $response;
                   1059:                 if ($item eq 'username') {                
                   1060:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1061:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1062:                                               $homeserver));
1.923     raeburn  1063:                 } elsif ($item eq 'id') {
                   1064:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1065:                                               ':'.&escape($id).':'.$rulestr,
                   1066:                                               $homeserver));
1.943   ! raeburn  1067:                 } elsif ($item eq 'selfenroll') {
        !          1068:                     $response=&unescape(&reply('instselfenrollcheck:'.
        !          1069:                                                &escape($udom).':'.&escape($uname).
        !          1070:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1071:                 }
1.912     raeburn  1072:                 if ($response ne 'refused') {
                   1073:                     my @pairs=split(/\&/,$response);
                   1074:                     foreach my $item (@pairs) {
                   1075:                         my ($key,$value)=split(/=/,$item,2);
                   1076:                         $key = &unescape($key);
                   1077:                         next if ($key =~ /^error: 2 /);
                   1078:                         $returnhash{$key}=&thaw_unescape($value);
                   1079:                     }
                   1080:                 }
                   1081:             }
                   1082:         }
                   1083:     }
                   1084:     return %returnhash;
                   1085: }
                   1086: 
                   1087: sub inst_userrules {
1.923     raeburn  1088:     my ($udom,$check) = @_;
1.912     raeburn  1089:     my (%ruleshash,@ruleorder);
                   1090:     if ($udom ne '') {
                   1091:         my $homeserver=&domain($udom,'primary');
                   1092:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1093:             my $response;
                   1094:             if ($check eq 'id') {
                   1095:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1096:                                  $homeserver);
1.943   ! raeburn  1097:             } elsif ($check eq 'email') {
        !          1098:                 $response=&reply('instemailrules:'.&escape($udom),
        !          1099:                                  $homeserver);
1.923     raeburn  1100:             } else {
                   1101:                 $response=&reply('instuserrules:'.&escape($udom),
                   1102:                                  $homeserver);
                   1103:             }
1.912     raeburn  1104:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1105:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1106:                 ($response ne 'no_such_host')) {
                   1107:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1108:                 my @pairs=split(/\&/,$hashitems);
                   1109:                 foreach my $item (@pairs) {
                   1110:                     my ($key,$value)=split(/=/,$item,2);
                   1111:                     $key = &unescape($key);
                   1112:                     next if ($key =~ /^error: 2 /);
                   1113:                     $ruleshash{$key}=&thaw_unescape($value);
                   1114:                 }
                   1115:                 my @esc_order = split(/\&/,$orderitems);
                   1116:                 foreach my $item (@esc_order) {
                   1117:                     push(@ruleorder,&unescape($item));
                   1118:                 }
                   1119:             }
                   1120:         }
                   1121:     }
                   1122:     return (\%ruleshash,\@ruleorder);
                   1123: }
                   1124: 
1.943   ! raeburn  1125: # ------------------------- Get Authentication and Language Defaults for Domain
        !          1126: 
        !          1127: sub get_domain_defaults {
        !          1128:     my ($domain) = @_;
        !          1129:     my $cachetime = 60*60*24;
        !          1130:     my ($defauthtype,$defautharg,$deflang);
        !          1131:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
        !          1132:     if (defined($cached)) {
        !          1133:         if (ref($result) eq 'HASH') {
        !          1134:             return %{$result};
        !          1135:         }
        !          1136:     }
        !          1137:     my %domdefaults;
        !          1138:     my %domconfig =
        !          1139:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
        !          1140:     if (ref($domconfig{'defaults'}) eq 'HASH') {
        !          1141:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
        !          1142:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
        !          1143:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
        !          1144:     } else {
        !          1145:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
        !          1146:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
        !          1147:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
        !          1148:     }
        !          1149:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
        !          1150:                                   $cachetime);
        !          1151:     return %domdefaults;
        !          1152: }
        !          1153: 
1.344     www      1154: # --------------------------------------------------- Assign a key to a student
                   1155: 
                   1156: sub assign_access_key {
1.364     www      1157: #
                   1158: # a valid key looks like uname:udom#comments
                   1159: # comments are being appended
                   1160: #
1.498     www      1161:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1162:     $kdom=
1.620     albertel 1163:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1164:     $knum=
1.620     albertel 1165:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1166:     $cdom=
1.620     albertel 1167:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1168:     $cnum=
1.620     albertel 1169:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1170:     $udom=$env{'user.name'} unless (defined($udom));
                   1171:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1172:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1173:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1174:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1175:                                                   # assigned to this person
                   1176:                                                   # - this should not happen,
1.345     www      1177:                                                   # unless something went wrong
                   1178:                                                   # the first time around
                   1179: # ready to assign
1.364     www      1180:         $logentry=$1.'; '.$logentry;
1.496     www      1181:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1182:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1183: # key now belongs to user
1.346     www      1184: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1185:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                   1186:                 &appenv('environment.'.$envkey => $ckey);
                   1187:                 return 'ok';
                   1188:             } else {
                   1189:                 return 
                   1190:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1191: 	    }
                   1192:         } else {
                   1193:             return 'error: Could not assign key, try again later.';
                   1194:         }
1.364     www      1195:     } elsif (!$existing{$ckey}) {
1.345     www      1196: # the key does not exist
                   1197: 	return 'error: The key does not exist';
                   1198:     } else {
                   1199: # the key is somebody else's
                   1200: 	return 'error: The key is already in use';
                   1201:     }
1.344     www      1202: }
                   1203: 
1.364     www      1204: # ------------------------------------------ put an additional comment on a key
                   1205: 
                   1206: sub comment_access_key {
                   1207: #
                   1208: # a valid key looks like uname:udom#comments
                   1209: # comments are being appended
                   1210: #
                   1211:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1212:     $cdom=
1.620     albertel 1213:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1214:     $cnum=
1.620     albertel 1215:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1216:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1217:     if ($existing{$ckey}) {
                   1218:         $existing{$ckey}.='; '.$logentry;
                   1219: # ready to assign
1.367     www      1220:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1221:                                                  $cdom,$cnum) eq 'ok') {
                   1222: 	    return 'ok';
                   1223:         } else {
                   1224: 	    return 'error: Count not store comment.';
                   1225:         }
                   1226:     } else {
                   1227: # the key does not exist
                   1228: 	return 'error: The key does not exist';
                   1229:     }
                   1230: }
                   1231: 
1.344     www      1232: # ------------------------------------------------------ Generate a set of keys
                   1233: 
                   1234: sub generate_access_keys {
1.364     www      1235:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1236:     $cdom=
1.620     albertel 1237:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1238:     $cnum=
1.620     albertel 1239:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1240:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1241:     unless (($cdom) && ($cnum)) { return 0; }
                   1242:     if ($number>10000) { return 0; }
                   1243:     sleep(2); # make sure don't get same seed twice
                   1244:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1245:     my $total=0;
                   1246:     for (my $i=1;$i<=$number;$i++) {
                   1247:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1248:                   sprintf("%lx",int(100000*rand)).'-'.
                   1249:                   sprintf("%lx",int(100000*rand));
                   1250:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1251:        $newkey=~s/0/h/g; # and also 0 and O
                   1252:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1253:        if ($existing{$newkey}) {
                   1254:            $i--;
                   1255:        } else {
1.364     www      1256: 	  if (&put('accesskeys',
                   1257:               { $newkey => '# generated '.localtime().
1.620     albertel 1258:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1259:                            '; '.$logentry },
                   1260: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1261:               $total++;
                   1262: 	  }
                   1263:        }
                   1264:     }
1.620     albertel 1265:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1266:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1267:     return $total;
                   1268: }
                   1269: 
                   1270: # ------------------------------------------------------- Validate an accesskey
                   1271: 
                   1272: sub validate_access_key {
                   1273:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1274:     $cdom=
1.620     albertel 1275:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1276:     $cnum=
1.620     albertel 1277:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1278:     $udom=$env{'user.domain'} unless (defined($udom));
                   1279:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1280:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1281:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1282: }
                   1283: 
                   1284: # ------------------------------------- Find the section of student in a course
1.652     albertel 1285: sub devalidate_getsection_cache {
                   1286:     my ($udom,$unam,$courseid)=@_;
                   1287:     my $hashid="$udom:$unam:$courseid";
                   1288:     &devalidate_cache_new('getsection',$hashid);
                   1289: }
1.298     matthew  1290: 
1.815     albertel 1291: sub courseid_to_courseurl {
                   1292:     my ($courseid) = @_;
                   1293:     #already url style courseid
                   1294:     return $courseid if ($courseid =~ m{^/});
                   1295: 
                   1296:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1297: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1298: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1299: 	return "/$cdom/$cnum";
                   1300:     }
                   1301: 
                   1302:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1303:     if (exists($courseinfo{'num'})) {
                   1304: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1305:     }
                   1306: 
                   1307:     return undef;
                   1308: }
                   1309: 
1.298     matthew  1310: sub getsection {
                   1311:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1312:     my $cachetime=1800;
1.551     albertel 1313: 
                   1314:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1315:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1316:     if (defined($cached)) { return $result; }
                   1317: 
1.298     matthew  1318:     my %Pending; 
                   1319:     my %Expired;
                   1320:     #
                   1321:     # Each role can either have not started yet (pending), be active, 
                   1322:     #    or have expired.
                   1323:     #
                   1324:     # If there is an active role, we are done.
                   1325:     #
                   1326:     # If there is more than one role which has not started yet, 
                   1327:     #     choose the one which will start sooner
                   1328:     # If there is one role which has not started yet, return it.
                   1329:     #
                   1330:     # If there is more than one expired role, choose the one which ended last.
                   1331:     # If there is a role which has expired, return it.
                   1332:     #
1.815     albertel 1333:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1334:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1335:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1336:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1337:         my $section=$1;
                   1338:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1339:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1340:         my $now=time;
1.548     albertel 1341:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1342:             $Expired{$end}=$section;
                   1343:             next;
                   1344:         }
1.548     albertel 1345:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1346:             $Pending{$start}=$section;
                   1347:             next;
                   1348:         }
1.599     albertel 1349:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1350:     }
                   1351:     #
                   1352:     # Presumedly there will be few matching roles from the above
                   1353:     # loop and the sorting time will be negligible.
                   1354:     if (scalar(keys(%Pending))) {
                   1355:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1356:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1357:     } 
                   1358:     if (scalar(keys(%Expired))) {
                   1359:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1360:         my $time = pop(@sorted);
1.599     albertel 1361:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1362:     }
1.599     albertel 1363:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1364: }
1.70      www      1365: 
1.599     albertel 1366: sub save_cache {
                   1367:     &purge_remembered();
1.722     albertel 1368:     #&Apache::loncommon::validate_page();
1.620     albertel 1369:     undef(%env);
1.780     albertel 1370:     undef($env_loaded);
1.599     albertel 1371: }
1.452     albertel 1372: 
1.599     albertel 1373: my $to_remember=-1;
                   1374: my %remembered;
                   1375: my %accessed;
                   1376: my $kicks=0;
                   1377: my $hits=0;
1.849     albertel 1378: sub make_key {
                   1379:     my ($name,$id) = @_;
1.872     albertel 1380:     if (length($id) > 65 
                   1381: 	&& length(&escape($id)) > 200) {
                   1382: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1383:     }
1.849     albertel 1384:     return &escape($name.':'.$id);
                   1385: }
                   1386: 
1.599     albertel 1387: sub devalidate_cache_new {
                   1388:     my ($name,$id,$debug) = @_;
                   1389:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1390:     $id=&make_key($name,$id);
1.599     albertel 1391:     $memcache->delete($id);
                   1392:     delete($remembered{$id});
                   1393:     delete($accessed{$id});
                   1394: }
                   1395: 
                   1396: sub is_cached_new {
                   1397:     my ($name,$id,$debug) = @_;
1.849     albertel 1398:     $id=&make_key($name,$id);
1.599     albertel 1399:     if (exists($remembered{$id})) {
                   1400: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1401: 	$accessed{$id}=[&gettimeofday()];
                   1402: 	$hits++;
                   1403: 	return ($remembered{$id},1);
                   1404:     }
                   1405:     my $value = $memcache->get($id);
                   1406:     if (!(defined($value))) {
                   1407: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1408: 	return (undef,undef);
1.416     albertel 1409:     }
1.599     albertel 1410:     if ($value eq '__undef__') {
                   1411: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1412: 	$value=undef;
                   1413:     }
                   1414:     &make_room($id,$value,$debug);
                   1415:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1416:     return ($value,1);
                   1417: }
                   1418: 
                   1419: sub do_cache_new {
                   1420:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1421:     $id=&make_key($name,$id);
1.599     albertel 1422:     my $setvalue=$value;
                   1423:     if (!defined($setvalue)) {
                   1424: 	$setvalue='__undef__';
                   1425:     }
1.623     albertel 1426:     if (!defined($time) ) {
                   1427: 	$time=600;
                   1428:     }
1.599     albertel 1429:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1430:     my $result = $memcache->set($id,$setvalue,$time);
                   1431:     if (! $result) {
1.872     albertel 1432: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1433: 	$memcache->disconnect_all();
1.872     albertel 1434:     }
1.600     albertel 1435:     # need to make a copy of $value
1.919     albertel 1436:     &make_room($id,$value,$debug);
1.599     albertel 1437:     return $value;
                   1438: }
                   1439: 
                   1440: sub make_room {
                   1441:     my ($id,$value,$debug)=@_;
1.919     albertel 1442: 
                   1443:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1444:                                     : $value;
1.599     albertel 1445:     if ($to_remember<0) { return; }
                   1446:     $accessed{$id}=[&gettimeofday()];
                   1447:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1448:     my $to_kick;
                   1449:     my $max_time=0;
                   1450:     foreach my $other (keys(%accessed)) {
                   1451: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1452: 	    $to_kick=$other;
                   1453: 	    $max_time=&tv_interval($accessed{$other});
                   1454: 	}
                   1455:     }
                   1456:     delete($remembered{$to_kick});
                   1457:     delete($accessed{$to_kick});
                   1458:     $kicks++;
                   1459:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1460:     return;
                   1461: }
                   1462: 
1.599     albertel 1463: sub purge_remembered {
1.604     albertel 1464:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1465:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1466:     undef(%remembered);
                   1467:     undef(%accessed);
1.428     albertel 1468: }
1.70      www      1469: # ------------------------------------- Read an entry from a user's environment
                   1470: 
                   1471: sub userenvironment {
                   1472:     my ($udom,$unam,@what)=@_;
                   1473:     my %returnhash=();
                   1474:     my @answer=split(/\&/,
                   1475:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1476:                       &homeserver($unam,$udom)));
                   1477:     my $i;
                   1478:     for ($i=0;$i<=$#what;$i++) {
                   1479: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1480:     }
                   1481:     return %returnhash;
1.1       albertel 1482: }
                   1483: 
1.617     albertel 1484: # ---------------------------------------------------------- Get a studentphoto
                   1485: sub studentphoto {
                   1486:     my ($udom,$unam,$ext) = @_;
                   1487:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1488:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1489:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1490:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1491:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1492:             } else {
                   1493:                 my ($result,$perm_reqd)=
1.707     albertel 1494: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1495:                 if ($result eq 'ok') {
                   1496:                     if (!($perm_reqd eq 'yes')) {
                   1497:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1498:                     }
                   1499:                 }
                   1500:             }
                   1501:         }
                   1502:     } else {
                   1503:         my ($result,$perm_reqd) = 
1.707     albertel 1504: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1505:         if ($result eq 'ok') {
                   1506:             if (!($perm_reqd eq 'yes')) {
                   1507:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1508:             }
                   1509:         }
                   1510:     }
                   1511:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1512: }
                   1513: 
                   1514: sub retrievestudentphoto {
                   1515:     my ($udom,$unam,$ext,$type) = @_;
                   1516:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1517:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1518:     if ($ret eq 'ok') {
                   1519:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1520:         if ($type eq 'thumbnail') {
                   1521:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1522:         }
                   1523:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1524:         return $tokenurl;
                   1525:     } else {
                   1526:         if ($type eq 'thumbnail') {
                   1527:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1528:         } else { 
                   1529:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1530:         }
1.617     albertel 1531:     }
                   1532: }
                   1533: 
1.263     www      1534: # -------------------------------------------------------------------- New chat
                   1535: 
                   1536: sub chatsend {
1.724     raeburn  1537:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1538:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1539:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1540:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1541:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1542: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1543: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1544: }
                   1545: 
                   1546: # ------------------------------------------ Find current version of a resource
                   1547: 
                   1548: sub getversion {
                   1549:     my $fname=&clutter(shift);
                   1550:     unless ($fname=~/^\/res\//) { return -1; }
                   1551:     return &currentversion(&filelocation('',$fname));
                   1552: }
                   1553: 
                   1554: sub currentversion {
                   1555:     my $fname=shift;
1.599     albertel 1556:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1557:     if (defined($cached)) { return $result; }
1.292     www      1558:     my $author=$fname;
                   1559:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1560:     my ($udom,$uname)=split(/\//,$author);
                   1561:     my $home=homeserver($uname,$udom);
                   1562:     if ($home eq 'no_host') { 
                   1563:         return -1; 
                   1564:     }
                   1565:     my $answer=reply("currentversion:$fname",$home);
                   1566:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1567: 	return -1;
                   1568:     }
1.599     albertel 1569:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1570: }
                   1571: 
1.1       albertel 1572: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1573: 
1.1       albertel 1574: sub subscribe {
                   1575:     my $fname=shift;
1.761     raeburn  1576:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1577:     $fname=~s/[\n\r]//g;
1.1       albertel 1578:     my $author=$fname;
                   1579:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1580:     my ($udom,$uname)=split(/\//,$author);
                   1581:     my $home=homeserver($uname,$udom);
1.335     albertel 1582:     if ($home eq 'no_host') {
                   1583:         return 'not_found';
1.1       albertel 1584:     }
                   1585:     my $answer=reply("sub:$fname",$home);
1.64      www      1586:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1587: 	$answer.=' by '.$home;
                   1588:     }
1.1       albertel 1589:     return $answer;
                   1590: }
                   1591:     
1.8       www      1592: # -------------------------------------------------------------- Replicate file
                   1593: 
                   1594: sub repcopy {
                   1595:     my $filename=shift;
1.23      www      1596:     $filename=~s/\/+/\//g;
1.607     raeburn  1597:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1598:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1599:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1600: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1601: 	return &repcopy_userfile($filename);
                   1602:     }
1.532     albertel 1603:     $filename=~s/[\n\r]//g;
1.8       www      1604:     my $transname="$filename.in.transfer";
1.828     www      1605: # FIXME: this should flock
1.607     raeburn  1606:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1607:     my $remoteurl=subscribe($filename);
1.64      www      1608:     if ($remoteurl =~ /^con_lost by/) {
                   1609: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1610:            return 'unavailable';
1.8       www      1611:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1612: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1613: 	   return 'not_found';
1.64      www      1614:     } elsif ($remoteurl =~ /^rejected by/) {
                   1615: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1616:            return 'forbidden';
1.20      www      1617:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1618:            return 'ok';
1.8       www      1619:     } else {
1.290     www      1620:         my $author=$filename;
                   1621:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1622:         my ($udom,$uname)=split(/\//,$author);
                   1623:         my $home=homeserver($uname,$udom);
                   1624:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1625:            my @parts=split(/\//,$filename);
                   1626:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1627:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1628:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1629: 	       return 'bad_request';
1.8       www      1630:            }
                   1631:            my $count;
                   1632:            for ($count=5;$count<$#parts;$count++) {
                   1633:                $path.="/$parts[$count]";
                   1634:                if ((-e $path)!=1) {
                   1635: 		   mkdir($path,0777);
                   1636:                }
                   1637:            }
                   1638:            my $ua=new LWP::UserAgent;
                   1639:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1640:            my $response=$ua->request($request,$transname);
                   1641:            if ($response->is_error()) {
                   1642: 	       unlink($transname);
                   1643:                my $message=$response->status_line;
1.672     albertel 1644:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1645:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1646:                return 'unavailable';
1.8       www      1647:            } else {
1.16      www      1648: 	       if ($remoteurl!~/\.meta$/) {
                   1649:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1650:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1651:                   if ($mresponse->is_error()) {
                   1652: 		      unlink($filename.'.meta');
                   1653:                       &logthis(
1.672     albertel 1654:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1655:                   }
                   1656: 	       }
1.8       www      1657:                rename($transname,$filename);
1.607     raeburn  1658:                return 'ok';
1.8       www      1659:            }
1.290     www      1660:        }
1.8       www      1661:     }
1.330     www      1662: }
                   1663: 
                   1664: # ------------------------------------------------ Get server side include body
                   1665: sub ssi_body {
1.381     albertel 1666:     my ($filelink,%form)=@_;
1.606     matthew  1667:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1668:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1669:     }
1.330     www      1670:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1671:                                      &ssi($filelink,%form));
1.778     albertel 1672:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1673:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1674:     $output=~s/\<\/body\s*\>.*?$//si;
1.330     www      1675:     return $output;
1.8       www      1676: }
                   1677: 
1.15      www      1678: # --------------------------------------------------------- Server Side Include
                   1679: 
1.782     albertel 1680: sub absolute_url {
                   1681:     my ($host_name) = @_;
                   1682:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1683:     if ($host_name eq '') {
                   1684: 	$host_name = $ENV{'SERVER_NAME'};
                   1685:     }
                   1686:     return $protocol.$host_name;
                   1687: }
                   1688: 
1.942     foxr     1689: #
                   1690: #   Server side include.
                   1691: # Parameters:
                   1692: #  fn     Possibly encrypted resource name/id.
                   1693: #  form   Hash that describes how the rendering should be done
                   1694: #         and other things.
                   1695: #  r      Optional reference that will be given the response.
                   1696: #         This is mostly provided so that the caller can implement
                   1697: #         error detection, recovery and retry policies.
                   1698: #     
                   1699: # Returns:
                   1700: #    The content of the response.
1.15      www      1701: sub ssi {
                   1702: 
1.942     foxr     1703:     my ($fn,%form, $r)=@_;
1.15      www      1704: 
                   1705:     my $ua=new LWP::UserAgent;
1.23      www      1706:     
                   1707:     my $request;
1.711     albertel 1708: 
                   1709:     $form{'no_update_last_known'}=1;
1.895     albertel 1710:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1711:     if (%form) {
1.782     albertel 1712:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1713:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1714:     } else {
1.782     albertel 1715:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1716:     }
                   1717: 
1.15      www      1718:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1719:     my $response=$ua->request($request);
                   1720: 
1.942     foxr     1721:     if ($r) {
                   1722: 	$$r = $response;
                   1723:     }
                   1724: 
1.324     www      1725:     return $response->content;
                   1726: }
                   1727: 
                   1728: sub externalssi {
                   1729:     my ($url)=@_;
                   1730:     my $ua=new LWP::UserAgent;
                   1731:     my $request=new HTTP::Request('GET',$url);
                   1732:     my $response=$ua->request($request);
1.15      www      1733:     return $response->content;
                   1734: }
1.254     www      1735: 
1.492     albertel 1736: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1737: 
                   1738: sub allowuploaded {
                   1739:     my ($srcurl,$url)=@_;
                   1740:     $url=&clutter(&declutter($url));
                   1741:     my $dir=$url;
                   1742:     $dir=~s/\/[^\/]+$//;
                   1743:     my %httpref=();
                   1744:     my $httpurl=&hreflocation('',$url);
                   1745:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1746:     &Apache::lonnet::appenv(%httpref);
1.254     www      1747: }
1.477     raeburn  1748: 
1.478     albertel 1749: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1750: # input: action, courseID, current domain, intended
1.637     raeburn  1751: #        path to file, source of file, instruction to parse file for objects,
                   1752: #        ref to hash for embedded objects,
                   1753: #        ref to hash for codebase of java objects.
                   1754: #
1.485     raeburn  1755: # output: url to file (if action was uploaddoc), 
                   1756: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1757: #
1.478     albertel 1758: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1759: # course.
1.477     raeburn  1760: #
1.478     albertel 1761: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1762: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1763: #          course's home server.
1.477     raeburn  1764: #
1.478     albertel 1765: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1766: #          be copied from $source (current location) to 
                   1767: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1768: #         and will then be copied to
                   1769: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1770: #         course's home server.
1.485     raeburn  1771: #
1.481     raeburn  1772: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1773: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1774: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1775: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1776: #         in course's home server.
1.637     raeburn  1777: #
1.477     raeburn  1778: 
                   1779: sub process_coursefile {
1.638     albertel 1780:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1781:     my $fetchresult;
1.638     albertel 1782:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1783:     if ($action eq 'propagate') {
1.638     albertel 1784:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1785: 			     $home);
1.481     raeburn  1786:     } else {
1.477     raeburn  1787:         my $fpath = '';
                   1788:         my $fname = $file;
1.478     albertel 1789:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1790:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1791:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1792:         if ($action eq 'copy') {
                   1793:             if ($source eq '') {
                   1794:                 $fetchresult = 'no source file';
                   1795:                 return $fetchresult;
                   1796:             } else {
                   1797:                 my $destination = $filepath.'/'.$fname;
                   1798:                 rename($source,$destination);
                   1799:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1800:                                  $home);
1.481     raeburn  1801:             }
                   1802:         } elsif ($action eq 'uploaddoc') {
                   1803:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1804:             print $fh $env{'form.'.$source};
1.481     raeburn  1805:             close($fh);
1.637     raeburn  1806:             if ($parser eq 'parse') {
                   1807:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1808:                 unless ($parse_result eq 'ok') {
                   1809:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1810:                 }
                   1811:             }
1.477     raeburn  1812:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1813:                                  $home);
1.481     raeburn  1814:             if ($fetchresult eq 'ok') {
                   1815:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1816:             } else {
                   1817:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1818:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1819:                 return '/adm/notfound.html';
                   1820:             }
1.477     raeburn  1821:         }
                   1822:     }
1.485     raeburn  1823:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1824:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1825:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1826:     }
                   1827:     return $fetchresult;
                   1828: }
                   1829: 
1.637     raeburn  1830: sub build_filepath {
                   1831:     my ($fpath) = @_;
                   1832:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1833:     unless ($fpath eq '') {
                   1834:         my @parts=split('/',$fpath);
                   1835:         foreach my $part (@parts) {
                   1836:             $filepath.= '/'.$part;
                   1837:             if ((-e $filepath)!=1) {
                   1838:                 mkdir($filepath,0777);
                   1839:             }
                   1840:         }
                   1841:     }
                   1842:     return $filepath;
                   1843: }
                   1844: 
                   1845: sub store_edited_file {
1.638     albertel 1846:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1847:     my $file = $primary_url;
                   1848:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1849:     my $fpath = '';
                   1850:     my $fname = $file;
                   1851:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1852:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1853:     my $filepath = &build_filepath($fpath);
                   1854:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1855:     print $fh $content;
                   1856:     close($fh);
1.638     albertel 1857:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1858:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1859: 			  $home);
1.637     raeburn  1860:     if ($$fetchresult eq 'ok') {
                   1861:         return '/uploaded/'.$fpath.'/'.$fname;
                   1862:     } else {
1.638     albertel 1863:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1864: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1865:         return '/adm/notfound.html';
                   1866:     }
                   1867: }
                   1868: 
1.531     albertel 1869: sub clean_filename {
1.831     albertel 1870:     my ($fname,$args)=@_;
1.315     www      1871: # Replace Windows backslashes by forward slashes
1.257     www      1872:     $fname=~s/\\/\//g;
1.831     albertel 1873:     if (!$args->{'keep_path'}) {
                   1874:         # Get rid of everything but the actual filename
                   1875: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1876:     }
1.315     www      1877: # Replace spaces by underscores
                   1878:     $fname=~s/\s+/\_/g;
                   1879: # Replace all other weird characters by nothing
1.831     albertel 1880:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1881: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1882: # numbers
                   1883:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1884:     return $fname;
                   1885: }
                   1886: 
1.608     albertel 1887: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1888: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1889: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1890: #        $coursedoc - if true up to the current course
                   1891: #                     if false
                   1892: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1893: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1894: #        $allfiles - reference to hash for embedded objects
                   1895: #        $codebase - reference to hash for codebase of java objects
                   1896: #        $desuname - username for permanent storage of uploaded file
                   1897: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1898: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1899: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1900: # 
1.686     albertel 1901: # output: url of file in userspace, or error: <message> 
                   1902: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1903: 
                   1904: 
1.531     albertel 1905: sub userfileupload {
1.860     raeburn  1906:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1907:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1908:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1909:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1910:     $fname=&clean_filename($fname);
1.315     www      1911: # See if there is anything left
1.257     www      1912:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1913:     chop($env{'form.'.$formname});
1.523     raeburn  1914:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1915:         my $now = time;
                   1916:         my $filepath = 'tmp/helprequests/'.$now;
                   1917:         my @parts=split(/\//,$filepath);
                   1918:         my $fullpath = $perlvar{'lonDaemons'};
                   1919:         for (my $i=0;$i<@parts;$i++) {
                   1920:             $fullpath .= '/'.$parts[$i];
                   1921:             if ((-e $fullpath)!=1) {
                   1922:                 mkdir($fullpath,0777);
                   1923:             }
                   1924:         }
                   1925:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1926:         print $fh $env{'form.'.$formname};
1.523     raeburn  1927:         close($fh);
1.741     raeburn  1928:         return $fullpath.'/'.$fname;
                   1929:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1930:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1931:                        '_'.$env{'user.domain'}.'/pending';
                   1932:         my @parts=split(/\//,$filepath);
                   1933:         my $fullpath = $perlvar{'lonDaemons'};
                   1934:         for (my $i=0;$i<@parts;$i++) {
                   1935:             $fullpath .= '/'.$parts[$i];
                   1936:             if ((-e $fullpath)!=1) {
                   1937:                 mkdir($fullpath,0777);
                   1938:             }
                   1939:         }
                   1940:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1941:         print $fh $env{'form.'.$formname};
                   1942:         close($fh);
                   1943:         return $fullpath.'/'.$fname;
1.523     raeburn  1944:     }
1.719     banghart 1945:     
1.258     www      1946: # Create the directory if not present
1.493     albertel 1947:     $fname="$subdir/$fname";
1.259     www      1948:     if ($coursedoc) {
1.638     albertel 1949: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1950: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1951:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1952:             return &finishuserfileupload($docuname,$docudom,
                   1953: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1954: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1955:         } else {
1.620     albertel 1956:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1957:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1958: 				       $fname,$formname,$parser,
                   1959: 				       $allfiles,$codebase);
1.481     raeburn  1960:         }
1.719     banghart 1961:     } elsif (defined($destuname)) {
                   1962:         my $docuname=$destuname;
                   1963:         my $docudom=$destudom;
1.860     raeburn  1964: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1965: 				     $parser,$allfiles,$codebase,
                   1966:                                      $thumbwidth,$thumbheight);
1.719     banghart 1967:         
1.259     www      1968:     } else {
1.638     albertel 1969:         my $docuname=$env{'user.name'};
                   1970:         my $docudom=$env{'user.domain'};
1.714     raeburn  1971:         if (exists($env{'form.group'})) {
                   1972:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1973:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1974:         }
1.860     raeburn  1975: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1976: 				     $parser,$allfiles,$codebase,
                   1977:                                      $thumbwidth,$thumbheight);
1.259     www      1978:     }
1.271     www      1979: }
                   1980: 
                   1981: sub finishuserfileupload {
1.860     raeburn  1982:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1983:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1984:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1985:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1986:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1987:     $file=$fname;
                   1988:     if ($fname=~m|/|) {
                   1989:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1990: 	$path.=$fnamepath.'/';
                   1991:     }
1.259     www      1992:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1993:     my $count;
                   1994:     for ($count=4;$count<=$#parts;$count++) {
                   1995:         $filepath.="/$parts[$count]";
                   1996:         if ((-e $filepath)!=1) {
                   1997: 	    mkdir($filepath,0777);
                   1998:         }
                   1999:     }
                   2000: # Save the file
                   2001:     {
1.701     albertel 2002: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2003: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2004: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2005: 	    return '/adm/notfound.html';
                   2006: 	}
                   2007: 	if (!print FH ($env{'form.'.$formname})) {
                   2008: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2009: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2010: 	    return '/adm/notfound.html';
                   2011: 	}
1.570     albertel 2012: 	close(FH);
1.258     www      2013:     }
1.637     raeburn  2014:     if ($parser eq 'parse') {
1.638     albertel 2015:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2016: 						   $codebase);
1.637     raeburn  2017:         unless ($parse_result eq 'ok') {
1.638     albertel 2018:             &logthis('Failed to parse '.$filepath.$file.
                   2019: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2020:         }
                   2021:     }
1.860     raeburn  2022:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2023:         my $input = $filepath.'/'.$file;
                   2024:         my $output = $filepath.'/'.'tn-'.$file;
                   2025:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2026:         system("convert -sample $thumbsize $input $output");
                   2027:         if (-e $filepath.'/'.'tn-'.$file) {
                   2028:             $fetchthumb  = 1; 
                   2029:         }
                   2030:     }
1.858     raeburn  2031:  
1.259     www      2032: # Notify homeserver to grep it
                   2033: #
1.638     albertel 2034:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2035:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2036:     if ($fetchresult eq 'ok') {
1.860     raeburn  2037:         if ($fetchthumb) {
                   2038:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2039:             if ($thumbresult ne 'ok') {
                   2040:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2041:                          $docuhome.': '.$thumbresult);
                   2042:             }
                   2043:         }
1.259     www      2044: #
1.258     www      2045: # Return the URL to it
1.494     albertel 2046:         return '/uploaded/'.$path.$file;
1.263     www      2047:     } else {
1.494     albertel 2048:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2049: 		 ': '.$fetchresult);
1.263     www      2050:         return '/adm/notfound.html';
1.858     raeburn  2051:     }
1.493     albertel 2052: }
                   2053: 
1.637     raeburn  2054: sub extract_embedded_items {
1.648     raeburn  2055:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2056:     my @state = ();
                   2057:     my %javafiles = (
                   2058:                       codebase => '',
                   2059:                       code => '',
                   2060:                       archive => ''
                   2061:                     );
                   2062:     my %mediafiles = (
                   2063:                       src => '',
                   2064:                       movie => '',
                   2065:                      );
1.648     raeburn  2066:     my $p;
                   2067:     if ($content) {
                   2068:         $p = HTML::LCParser->new($content);
                   2069:     } else {
                   2070:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2071:     }
1.641     albertel 2072:     while (my $t=$p->get_token()) {
1.640     albertel 2073: 	if ($t->[0] eq 'S') {
                   2074: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2075: 	    push(@state, $tagname);
1.648     raeburn  2076:             if (lc($tagname) eq 'allow') {
                   2077:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2078:             }
1.640     albertel 2079: 	    if (lc($tagname) eq 'img') {
                   2080: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2081: 	    }
1.886     albertel 2082: 	    if (lc($tagname) eq 'a') {
                   2083: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2084: 	    }
1.645     raeburn  2085:             if (lc($tagname) eq 'script') {
                   2086:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2087:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2088:                 } else {
                   2089:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2090:                 }
                   2091:             }
                   2092:             if (lc($tagname) eq 'link') {
                   2093:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2094:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2095:                 }
                   2096:             }
1.640     albertel 2097: 	    if (lc($tagname) eq 'object' ||
                   2098: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2099: 		foreach my $item (keys(%javafiles)) {
                   2100: 		    $javafiles{$item} = '';
                   2101: 		}
                   2102: 	    }
                   2103: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2104: 		my $name = lc($attr->{'name'});
                   2105: 		foreach my $item (keys(%javafiles)) {
                   2106: 		    if ($name eq $item) {
                   2107: 			$javafiles{$item} = $attr->{'value'};
                   2108: 			last;
                   2109: 		    }
                   2110: 		}
                   2111: 		foreach my $item (keys(%mediafiles)) {
                   2112: 		    if ($name eq $item) {
                   2113: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2114: 			last;
                   2115: 		    }
                   2116: 		}
                   2117: 	    }
                   2118: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2119: 		foreach my $item (keys(%javafiles)) {
                   2120: 		    if ($attr->{$item}) {
                   2121: 			$javafiles{$item} = $attr->{$item};
                   2122: 			last;
                   2123: 		    }
                   2124: 		}
                   2125: 		foreach my $item (keys(%mediafiles)) {
                   2126: 		    if ($attr->{$item}) {
                   2127: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2128: 			last;
                   2129: 		    }
                   2130: 		}
                   2131: 	    }
                   2132: 	} elsif ($t->[0] eq 'E') {
                   2133: 	    my ($tagname) = ($t->[1]);
                   2134: 	    if ($javafiles{'codebase'} ne '') {
                   2135: 		$javafiles{'codebase'} .= '/';
                   2136: 	    }  
                   2137: 	    if (lc($tagname) eq 'applet' ||
                   2138: 		lc($tagname) eq 'object' ||
                   2139: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2140: 		) {
                   2141: 		foreach my $item (keys(%javafiles)) {
                   2142: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2143: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2144: 			&add_filetype($allfiles,$file,$item);
                   2145: 		    }
                   2146: 		}
                   2147: 	    } 
                   2148: 	    pop @state;
                   2149: 	}
                   2150:     }
1.637     raeburn  2151:     return 'ok';
                   2152: }
                   2153: 
1.639     albertel 2154: sub add_filetype {
                   2155:     my ($allfiles,$file,$type)=@_;
                   2156:     if (exists($allfiles->{$file})) {
                   2157: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2158: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2159: 	}
                   2160:     } else {
                   2161: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2162:     }
                   2163: }
                   2164: 
1.493     albertel 2165: sub removeuploadedurl {
                   2166:     my ($url)=@_;
                   2167:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2168:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2169: }
                   2170: 
                   2171: sub removeuserfile {
                   2172:     my ($docuname,$docudom,$fname)=@_;
                   2173:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2174:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2175:     if ($result eq 'ok') {
                   2176:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2177:             my $metafile = $fname.'.meta';
                   2178:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2179: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2180:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2181:             my $sqlresult = 
1.823     albertel 2182:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2183:                                         'portfolio_metadata',$group,
                   2184:                                         'delete');
1.798     raeburn  2185:         }
                   2186:     }
                   2187:     return $result;
1.257     www      2188: }
1.15      www      2189: 
1.530     albertel 2190: sub mkdiruserfile {
                   2191:     my ($docuname,$docudom,$dir)=@_;
                   2192:     my $home=&homeserver($docuname,$docudom);
                   2193:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2194: }
                   2195: 
1.531     albertel 2196: sub renameuserfile {
                   2197:     my ($docuname,$docudom,$old,$new)=@_;
                   2198:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2199:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2200:                         &escape("$old").':'.&escape("$new"),$home);
                   2201:     if ($result eq 'ok') {
                   2202:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2203:             my $oldmeta = $old.'.meta';
                   2204:             my $newmeta = $new.'.meta';
                   2205:             my $metaresult = 
                   2206:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2207: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2208:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2209:             my $sqlresult = 
1.823     albertel 2210:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2211:                                         'portfolio_metadata',$group,
                   2212:                                         'delete');
1.798     raeburn  2213:         }
                   2214:     }
                   2215:     return $result;
1.531     albertel 2216: }
                   2217: 
1.14      www      2218: # ------------------------------------------------------------------------- Log
                   2219: 
                   2220: sub log {
                   2221:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2222:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2223: }
                   2224: 
                   2225: # ------------------------------------------------------------------ Course Log
1.352     www      2226: #
                   2227: # This routine flushes several buffers of non-mission-critical nature
                   2228: #
1.157     www      2229: 
                   2230: sub flushcourselogs {
1.352     www      2231:     &logthis('Flushing log buffers');
                   2232: #
                   2233: # course logs
                   2234: # This is a log of all transactions in a course, which can be used
                   2235: # for data mining purposes
                   2236: #
                   2237: # It also collects the courseid database, which lists last transaction
                   2238: # times and course titles for all courseids
                   2239: #
                   2240:     my %courseidbuffer=();
1.921     raeburn  2241:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2242:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2243: 		          &escape($courselogs{$crsid}),
                   2244: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2245: 	    delete $courselogs{$crsid};
                   2246:         } else {
                   2247:             &logthis('Failed to flush log buffer for '.$crsid);
                   2248:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2249:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2250:                         " exceeded maximum size, deleting.</font>");
                   2251:                delete $courselogs{$crsid};
                   2252:             }
1.352     www      2253:         }
1.920     raeburn  2254:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2255:             'description' => $coursedescrbuf{$crsid},
                   2256:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2257:             'type'        => $coursetypebuf{$crsid},
                   2258:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2259:         };
1.191     harris41 2260:     }
1.352     www      2261: #
                   2262: # Write course id database (reverse lookup) to homeserver of courses 
                   2263: # Is used in pickcourse
                   2264: #
1.840     albertel 2265:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2266:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2267:                                     $courseidbuffer{$crs_home},
                   2268:                                     $crs_home,'timeonly');
1.352     www      2269:     }
                   2270: #
                   2271: # File accesses
                   2272: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2273: #
1.449     matthew  2274:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2275:         if ($entry =~ /___count$/) {
                   2276:             my ($dom,$name);
1.807     albertel 2277:             ($dom,$name,undef)=
1.811     albertel 2278: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2279:             if (! defined($dom) || $dom eq '' || 
                   2280:                 ! defined($name) || $name eq '') {
1.620     albertel 2281:                 my $cid = $env{'request.course.id'};
                   2282:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2283:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2284:             }
1.450     matthew  2285:             my $value = $accesshash{$entry};
                   2286:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2287:             my %temphash=($url => $value);
1.449     matthew  2288:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2289:             if ($result eq 'ok') {
                   2290:                 delete $accesshash{$entry};
                   2291:             } elsif ($result eq 'unknown_cmd') {
                   2292:                 # Target server has old code running on it.
1.450     matthew  2293:                 my %temphash=($entry => $value);
1.449     matthew  2294:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2295:                     delete $accesshash{$entry};
                   2296:                 }
                   2297:             }
                   2298:         } else {
1.811     albertel 2299:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2300:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2301:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2302:                 delete $accesshash{$entry};
                   2303:             }
1.185     www      2304:         }
1.191     harris41 2305:     }
1.352     www      2306: #
                   2307: # Roles
                   2308: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2309: #
1.800     albertel 2310:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2311:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2312: 	    split(/\:/,$entry);
                   2313:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2314:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2315:                 $rudom,$runame) eq 'ok') {
                   2316: 	    delete $userrolehash{$entry};
                   2317:         }
                   2318:     }
1.662     raeburn  2319: #
                   2320: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2321: #
                   2322:     my %domrolebuffer = ();
                   2323:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2324:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2325:         if ($domrolebuffer{$rudom}) {
                   2326:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2327:                       '='.&escape($domainrolehash{$entry});
                   2328:         } else {
                   2329:             $domrolebuffer{$rudom}.=&escape($entry).
                   2330:                       '='.&escape($domainrolehash{$entry});
                   2331:         }
                   2332:         delete $domainrolehash{$entry};
                   2333:     }
                   2334:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2335: 	my %servers = &get_servers($dom,'library');
                   2336: 	foreach my $tryserver (keys(%servers)) {
                   2337: 	    unless (&reply('domroleput:'.$dom.':'.
                   2338: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2339: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2340: 	    }
1.662     raeburn  2341:         }
                   2342:     }
1.186     www      2343:     $dumpcount++;
1.157     www      2344: }
                   2345: 
                   2346: sub courselog {
                   2347:     my $what=shift;
1.158     www      2348:     $what=time.':'.$what;
1.620     albertel 2349:     unless ($env{'request.course.id'}) { return ''; }
                   2350:     $coursedombuf{$env{'request.course.id'}}=
                   2351:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2352:     $coursenumbuf{$env{'request.course.id'}}=
                   2353:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2354:     $coursehombuf{$env{'request.course.id'}}=
                   2355:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2356:     $coursedescrbuf{$env{'request.course.id'}}=
                   2357:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2358:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2359:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2360:     $courseownerbuf{$env{'request.course.id'}}=
                   2361:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2362:     $coursetypebuf{$env{'request.course.id'}}=
                   2363:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2364:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2365: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2366:     } else {
1.620     albertel 2367: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2368:     }
1.620     albertel 2369:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2370: 	&flushcourselogs();
                   2371:     }
1.158     www      2372: }
                   2373: 
                   2374: sub courseacclog {
                   2375:     my $fnsymb=shift;
1.620     albertel 2376:     unless ($env{'request.course.id'}) { return ''; }
                   2377:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2378:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2379:         $what.=':POST';
1.583     matthew  2380:         # FIXME: Probably ought to escape things....
1.800     albertel 2381: 	foreach my $key (keys(%env)) {
                   2382:             if ($key=~/^form\.(.*)/) {
                   2383: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2384:             }
1.191     harris41 2385:         }
1.583     matthew  2386:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2387:         # FIXME: We should not be depending on a form parameter that someone
                   2388:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2389:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2390:             $what.= ':POST';
                   2391:             # FIXME: Probably ought to escape things....
                   2392:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2393:                                  'crsdiscuss') {
1.620     albertel 2394:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2395:             }
                   2396:         }
1.158     www      2397:     }
                   2398:     &courselog($what);
1.149     www      2399: }
                   2400: 
1.185     www      2401: sub countacc {
                   2402:     my $url=&declutter(shift);
1.458     matthew  2403:     return if (! defined($url) || $url eq '');
1.620     albertel 2404:     unless ($env{'request.course.id'}) { return ''; }
                   2405:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2406:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2407:     $accesshash{$key}++;
1.185     www      2408: }
1.349     www      2409: 
1.361     www      2410: sub linklog {
                   2411:     my ($from,$to)=@_;
                   2412:     $from=&declutter($from);
                   2413:     $to=&declutter($to);
                   2414:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2415:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2416: }
                   2417:   
1.349     www      2418: sub userrolelog {
                   2419:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2420:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2421:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2422:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2423:         ($trole=~/^ta/)) {
1.350     www      2424:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2425:        $userrolehash
                   2426:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2427:                     =$tend.':'.$tstart;
1.662     raeburn  2428:     }
1.898     albertel 2429:     if (($env{'request.role'} =~ /dc\./) &&
                   2430: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2431: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2432: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2433:        $userrolehash
                   2434:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2435:                     =$tend.':'.$tstart;
                   2436:     }
1.662     raeburn  2437:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2438:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2439:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2440:         ($trole=~/^sc/)) {
                   2441:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2442:        $domainrolehash
                   2443:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2444:                     = $tend.':'.$tstart;
                   2445:     }
1.351     www      2446: }
                   2447: 
                   2448: sub get_course_adv_roles {
                   2449:     my $cid=shift;
1.620     albertel 2450:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2451:     my %coursehash=&coursedescription($cid);
1.470     www      2452:     my %nothide=();
1.800     albertel 2453:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2454:         if ($user !~ /:/) {
                   2455: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2456:         } else {
                   2457:             $nothide{$user}=1;
                   2458:         }
1.470     www      2459:     }
1.351     www      2460:     my %returnhash=();
                   2461:     my %dumphash=
                   2462:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2463:     my $now=time;
1.800     albertel 2464:     foreach my $entry (keys %dumphash) {
                   2465: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2466:         if (($tstart) && ($tstart<0)) { next; }
                   2467:         if (($tend) && ($tend<$now)) { next; }
                   2468:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2469:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2470: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2471: 	if ((&privileged($username,$domain)) && 
                   2472: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2473: 	if ($role eq 'cr') { next; }
1.351     www      2474:         my $key=&plaintext($role);
                   2475:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2476:         if ($returnhash{$key}) {
                   2477: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2478:         } else {
                   2479:             $returnhash{$key}=$username.':'.$domain;
                   2480:         }
1.400     www      2481:      }
                   2482:     return %returnhash;
                   2483: }
                   2484: 
                   2485: sub get_my_roles {
1.937     raeburn  2486:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2487:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2488:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2489:     my (%dumphash,%nothide);
1.858     raeburn  2490:     if ($context eq 'userroles') { 
                   2491:         %dumphash = &dump('roles',$udom,$uname);
                   2492:     } else {
                   2493:         %dumphash=
1.400     www      2494:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2495:         if ($hidepriv) {
                   2496:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2497:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2498:                 if ($user !~ /:/) {
                   2499:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2500:                 } else {
                   2501:                     $nothide{$user} = 1;
                   2502:                 }
                   2503:             }
                   2504:         }
1.858     raeburn  2505:     }
1.400     www      2506:     my %returnhash=();
                   2507:     my $now=time;
1.800     albertel 2508:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2509:         my ($role,$tend,$tstart);
                   2510:         if ($context eq 'userroles') {
                   2511: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2512:         } else {
                   2513:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2514:         }
1.400     www      2515:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2516:         my $status = 'active';
1.939     raeburn  2517:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2518:             $status = 'previous';
                   2519:         } 
                   2520:         if (($tstart) && ($now<$tstart)) {
                   2521:             $status = 'future';
                   2522:         }
                   2523:         if (ref($types) eq 'ARRAY') {
                   2524:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2525:                 next;
                   2526:             } 
                   2527:         } else {
                   2528:             if ($status ne 'active') {
                   2529:                 next;
                   2530:             }
                   2531:         }
1.867     raeburn  2532:         my ($rolecode,$username,$domain,$section,$area);
                   2533:         if ($context eq 'userroles') {
                   2534:             ($area,$rolecode) = split(/_/,$entry);
                   2535:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2536:         } else {
                   2537:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2538:         }
1.832     raeburn  2539:         if (ref($roledoms) eq 'ARRAY') {
                   2540:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2541:                 next;
                   2542:             }
                   2543:         }
                   2544:         if (ref($roles) eq 'ARRAY') {
                   2545:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2546:                 if ($role =~ /^cr\//) {
                   2547:                     if (!grep(/^cr$/,@{$roles})) {
                   2548:                         next;
                   2549:                     }
                   2550:                 } else {
                   2551:                     next;
                   2552:                 }
1.832     raeburn  2553:             }
1.867     raeburn  2554:         }
1.937     raeburn  2555:         if ($hidepriv) {
                   2556:             if ((&privileged($username,$domain)) &&
                   2557:                 (!$nothide{$username.':'.$domain})) { 
                   2558:                 next;
                   2559:             }
                   2560:         }
1.933     raeburn  2561:         if ($withsec) {
                   2562:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2563:                 $tstart.':'.$tend;
                   2564:         } else {
                   2565:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2566:         }
1.832     raeburn  2567:     }
1.373     www      2568:     return %returnhash;
1.399     www      2569: }
                   2570: 
                   2571: # ----------------------------------------------------- Frontpage Announcements
                   2572: #
                   2573: #
                   2574: 
                   2575: sub postannounce {
                   2576:     my ($server,$text)=@_;
1.844     albertel 2577:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2578:     unless ($text=~/\w/) { $text=''; }
                   2579:     return &reply('setannounce:'.&escape($text),$server);
                   2580: }
                   2581: 
                   2582: sub getannounce {
1.448     albertel 2583: 
                   2584:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2585: 	my $announcement='';
1.800     albertel 2586: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2587: 	close($fh);
1.399     www      2588: 	if ($announcement=~/\w/) { 
                   2589: 	    return 
                   2590:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2591:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2592: 	} else {
                   2593: 	    return '';
                   2594: 	}
                   2595:     } else {
                   2596: 	return '';
                   2597:     }
1.351     www      2598: }
1.353     www      2599: 
                   2600: # ---------------------------------------------------------- Course ID routines
                   2601: # Deal with domain's nohist_courseid.db files
                   2602: #
                   2603: 
                   2604: sub courseidput {
1.921     raeburn  2605:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2606:     my $outcome;
                   2607:     if ($caller eq 'timeonly') {
                   2608:         my $cids = '';
                   2609:         foreach my $item (keys(%$storehash)) {
                   2610:             $cids.=&escape($item).'&';
                   2611:         }
                   2612:         $cids=~s/\&$//;
                   2613:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2614:                           $coursehome);       
                   2615:     } else {
                   2616:         my $items = '';
                   2617:         foreach my $item (keys(%$storehash)) {
                   2618:             $items.= &escape($item).'='.
                   2619:                      &freeze_escape($$storehash{$item}).'&';
                   2620:         }
                   2621:         $items=~s/\&$//;
                   2622:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2623:                           $coursehome);
1.918     raeburn  2624:     }
                   2625:     if ($outcome eq 'unknown_cmd') {
                   2626:         my $what;
                   2627:         foreach my $cid (keys(%$storehash)) {
                   2628:             $what .= &escape($cid).'=';
1.921     raeburn  2629:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2630:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2631:             }
                   2632:             $what =~ s/\:$/&/;
                   2633:         }
                   2634:         $what =~ s/\&$//;  
                   2635:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2636:     } else {
                   2637:         return $outcome;
                   2638:     }
1.353     www      2639: }
                   2640: 
                   2641: sub courseiddump {
1.921     raeburn  2642:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
                   2643:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.918     raeburn  2644:     my $as_hash = 1;
                   2645:     my %returnhash;
                   2646:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2647:     my %libserv = &all_library();
                   2648:     foreach my $tryserver (keys(%libserv)) {
                   2649:         if ( (  $hostidflag == 1 
                   2650: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2651: 	     || (!defined($hostidflag)) ) {
                   2652: 
1.918     raeburn  2653: 	    if (($domfilter eq '') ||
                   2654: 		(&host_domain($tryserver) eq $domfilter)) {
                   2655:                 my $rep = 
                   2656:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2657:                          $sincefilter.':'.&escape($descfilter).':'.
                   2658:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2659:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.921     raeburn  2660:                          ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
1.918     raeburn  2661:                 my @pairs=split(/\&/,$rep);
                   2662:                 foreach my $item (@pairs) {
                   2663:                     my ($key,$value)=split(/\=/,$item,2);
                   2664:                     $key = &unescape($key);
                   2665:                     next if ($key =~ /^error: 2 /);
                   2666:                     my $result = &thaw_unescape($value);
                   2667:                     if (ref($result) eq 'HASH') {
                   2668:                         $returnhash{$key}=$result;
                   2669:                     } else {
1.921     raeburn  2670:                         my @responses = split(/:/,$value);
                   2671:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2672:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2673:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2674:                         }
                   2675:                     } 
1.353     www      2676:                 }
                   2677:             }
                   2678:         }
                   2679:     }
                   2680:     return %returnhash;
                   2681: }
                   2682: 
1.658     raeburn  2683: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2684: 
                   2685: sub dcmailput {
1.685     raeburn  2686:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2687:     my $status = &Apache::lonnet::critical(
1.740     www      2688:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2689:        &escape($message),$server);
1.662     raeburn  2690:     return $status;
                   2691: }
                   2692: 
1.658     raeburn  2693: sub dcmaildump {
                   2694:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2695:     my %returnhash=();
1.846     albertel 2696: 
                   2697:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2698:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2699:                                                          &escape($enddate).':';
                   2700: 	my @esc_senders=map { &escape($_)} @$senders;
                   2701: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2702: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2703:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2704:             if (($key) && ($value)) {
                   2705:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2706:             }
                   2707:         }
                   2708:     }
                   2709:     return %returnhash;
                   2710: }
1.662     raeburn  2711: # ---------------------------------------------------------- Domain roles
                   2712: 
                   2713: sub get_domain_roles {
                   2714:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2715:     if (undef($startdate) || $startdate eq '') {
                   2716:         $startdate = '.';
                   2717:     }
                   2718:     if (undef($enddate) || $enddate eq '') {
                   2719:         $enddate = '.';
                   2720:     }
1.922     raeburn  2721:     my $rolelist;
                   2722:     if (ref($roles) eq 'ARRAY') {
                   2723:         $rolelist = join(':',@{$roles});
                   2724:     }
1.662     raeburn  2725:     my %personnel = ();
1.841     albertel 2726: 
                   2727:     my %servers = &get_servers($dom,'library');
                   2728:     foreach my $tryserver (keys(%servers)) {
                   2729: 	%{$personnel{$tryserver}}=();
                   2730: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2731: 					    &escape($startdate).':'.
                   2732: 					    &escape($enddate).':'.
                   2733: 					    &escape($rolelist), $tryserver))) {
                   2734: 	    my ($key,$value) = split(/\=/,$line,2);
                   2735: 	    if (($key) && ($value)) {
                   2736: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2737: 	    }
                   2738: 	}
1.662     raeburn  2739:     }
                   2740:     return %personnel;
                   2741: }
1.658     raeburn  2742: 
1.149     www      2743: # ----------------------------------------------------------- Check out an item
                   2744: 
1.504     albertel 2745: sub get_first_access {
                   2746:     my ($type,$argsymb)=@_;
1.790     albertel 2747:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2748:     if ($argsymb) { $symb=$argsymb; }
                   2749:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2750:     if ($type eq 'course') {
                   2751: 	$res='course';
                   2752:     } elsif ($type eq 'map') {
1.588     albertel 2753: 	$res=&symbread($map);
                   2754:     } else {
                   2755: 	$res=$symb;
                   2756:     }
                   2757:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2758:     return $times{"$courseid\0$res"};
1.504     albertel 2759: }
                   2760: 
                   2761: sub set_first_access {
                   2762:     my ($type)=@_;
1.790     albertel 2763:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2764:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2765:     if ($type eq 'course') {
                   2766: 	$res='course';
                   2767:     } elsif ($type eq 'map') {
1.588     albertel 2768: 	$res=&symbread($map);
                   2769:     } else {
                   2770: 	$res=$symb;
                   2771:     }
                   2772:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2773:     if (!$firstaccess) {
1.588     albertel 2774: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2775:     }
                   2776:     return 'already_set';
1.504     albertel 2777: }
                   2778: 
1.149     www      2779: sub checkout {
                   2780:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2781:     my $now=time;
                   2782:     my $lonhost=$perlvar{'lonHostID'};
                   2783:     my $infostr=&escape(
1.234     www      2784:                  'CHECKOUTTOKEN&'.
1.149     www      2785:                  $tuname.'&'.
                   2786:                  $tudom.'&'.
                   2787:                  $tcrsid.'&'.
                   2788:                  $symb.'&'.
                   2789: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2790:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2791:     if ($token=~/^error\:/) { 
1.672     albertel 2792:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2793:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2794:                  "</font>");
                   2795:         return ''; 
                   2796:     }
                   2797: 
1.149     www      2798:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2799:     $token=~tr/a-z/A-Z/;
                   2800: 
1.153     www      2801:     my %infohash=('resource.0.outtoken' => $token,
                   2802:                   'resource.0.checkouttime' => $now,
                   2803:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2804: 
                   2805:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2806:        return '';
1.151     www      2807:     } else {
1.672     albertel 2808:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2809:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2810:                  "</font>");
1.149     www      2811:     }    
                   2812: 
                   2813:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2814:                          &escape('Checkout '.$infostr.' - '.
                   2815:                                                  $token)) ne 'ok') {
                   2816: 	return '';
1.151     www      2817:     } else {
1.672     albertel 2818:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2819:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2820:                  "</font>");
1.149     www      2821:     }
1.151     www      2822:     return $token;
1.149     www      2823: }
                   2824: 
                   2825: # ------------------------------------------------------------ Check in an item
                   2826: 
                   2827: sub checkin {
                   2828:     my $token=shift;
1.150     www      2829:     my $now=time;
                   2830:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2831:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2832:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2833:     $dtoken=~s/\W/\_/g;
1.234     www      2834:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2835:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2836: 
1.154     www      2837:     unless (($tuname) && ($tudom)) {
                   2838:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2839:         return '';
                   2840:     }
                   2841:     
                   2842:     unless (&allowed('mgr',$tcrsid)) {
                   2843:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2844:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2845:         return '';
                   2846:     }
                   2847: 
1.153     www      2848:     my %infohash=('resource.0.intoken' => $token,
                   2849:                   'resource.0.checkintime' => $now,
                   2850:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2851: 
                   2852:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2853:        return '';
                   2854:     }    
                   2855: 
                   2856:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2857:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2858: 	return '';
                   2859:     }
                   2860: 
                   2861:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2862: }
                   2863: 
                   2864: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2865: 
                   2866: sub expirespread {
                   2867:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2868:     my $cid=$env{'request.course.id'}; 
1.110     www      2869:     if ($cid) {
                   2870:        my $now=time;
                   2871:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2872:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2873:                             $env{'course.'.$cid.'.num'}.
1.110     www      2874: 	        	    ':nohist_expirationdates:'.
                   2875:                             &escape($key).'='.$now,
1.620     albertel 2876:                             $env{'course.'.$cid.'.home'})
1.110     www      2877:     }
                   2878:     return 'ok';
1.14      www      2879: }
                   2880: 
1.109     www      2881: # ----------------------------------------------------- Devalidate Spreadsheets
                   2882: 
                   2883: sub devalidate {
1.325     www      2884:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2885:     my $cid=$env{'request.course.id'}; 
1.109     www      2886:     if ($cid) {
1.391     matthew  2887:         # delete the stored spreadsheets for
                   2888:         # - the student level sheet of this user in course's homespace
                   2889:         # - the assessment level sheet for this resource 
                   2890:         #   for this user in user's homespace
1.553     albertel 2891: 	# - current conditional state info
1.325     www      2892: 	my $key=$uname.':'.$udom.':';
1.109     www      2893:         my $status=
1.299     matthew  2894: 	    &del('nohist_calculatedsheets',
1.391     matthew  2895: 		 [$key.'studentcalc:'],
1.620     albertel 2896: 		 $env{'course.'.$cid.'.domain'},
                   2897: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2898: 		.' '.
                   2899: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2900: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2901:         unless ($status eq 'ok ok') {
                   2902:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2903:                     $uname.' at '.$udom.' for '.
1.109     www      2904: 		    $symb.': '.$status);
1.133     albertel 2905:         }
1.553     albertel 2906: 	&delenv('user.state.'.$cid);
1.109     www      2907:     }
                   2908: }
                   2909: 
1.265     albertel 2910: sub get_scalar {
                   2911:     my ($string,$end) = @_;
                   2912:     my $value;
                   2913:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2914: 	$value = $1;
                   2915:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2916: 	$value = $1;
                   2917:     }
                   2918:     return &unescape($value);
                   2919: }
                   2920: 
                   2921: sub array2str {
                   2922:   my (@array) = @_;
                   2923:   my $result=&arrayref2str(\@array);
                   2924:   $result=~s/^__ARRAY_REF__//;
                   2925:   $result=~s/__END_ARRAY_REF__$//;
                   2926:   return $result;
                   2927: }
                   2928: 
1.204     albertel 2929: sub arrayref2str {
                   2930:   my ($arrayref) = @_;
1.265     albertel 2931:   my $result='__ARRAY_REF__';
1.204     albertel 2932:   foreach my $elem (@$arrayref) {
1.265     albertel 2933:     if(ref($elem) eq 'ARRAY') {
                   2934:       $result.=&arrayref2str($elem).'&';
                   2935:     } elsif(ref($elem) eq 'HASH') {
                   2936:       $result.=&hashref2str($elem).'&';
                   2937:     } elsif(ref($elem)) {
                   2938:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2939:     } else {
                   2940:       $result.=&escape($elem).'&';
                   2941:     }
                   2942:   }
                   2943:   $result=~s/\&$//;
1.265     albertel 2944:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2945:   return $result;
                   2946: }
                   2947: 
1.168     albertel 2948: sub hash2str {
1.204     albertel 2949:   my (%hash) = @_;
                   2950:   my $result=&hashref2str(\%hash);
1.265     albertel 2951:   $result=~s/^__HASH_REF__//;
                   2952:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2953:   return $result;
                   2954: }
                   2955: 
                   2956: sub hashref2str {
                   2957:   my ($hashref)=@_;
1.265     albertel 2958:   my $result='__HASH_REF__';
1.800     albertel 2959:   foreach my $key (sort(keys(%$hashref))) {
                   2960:     if (ref($key) eq 'ARRAY') {
                   2961:       $result.=&arrayref2str($key).'=';
                   2962:     } elsif (ref($key) eq 'HASH') {
                   2963:       $result.=&hashref2str($key).'=';
                   2964:     } elsif (ref($key)) {
1.265     albertel 2965:       $result.='=';
1.800     albertel 2966:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2967:     } else {
1.800     albertel 2968: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2969:     }
                   2970: 
1.800     albertel 2971:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2972:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2973:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2974:       $result.=&hashref2str($hashref->{$key}).'&';
                   2975:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2976:        $result.='&';
1.800     albertel 2977:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2978:     } else {
1.800     albertel 2979:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2980:     }
                   2981:   }
1.168     albertel 2982:   $result=~s/\&$//;
1.265     albertel 2983:   $result .= '__END_HASH_REF__';
1.168     albertel 2984:   return $result;
                   2985: }
                   2986: 
                   2987: sub str2hash {
1.265     albertel 2988:     my ($string)=@_;
                   2989:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2990:     return %$hash;
                   2991: }
                   2992: 
                   2993: sub str2hashref {
1.168     albertel 2994:   my ($string) = @_;
1.265     albertel 2995: 
                   2996:   my %hash;
                   2997: 
                   2998:   if($string !~ /^__HASH_REF__/) {
                   2999:       if (! ($string eq '' || !defined($string))) {
                   3000: 	  $hash{'error'}='Not hash reference';
                   3001:       }
                   3002:       return (\%hash, $string);
                   3003:   }
                   3004: 
                   3005:   $string =~ s/^__HASH_REF__//;
                   3006: 
                   3007:   while($string !~ /^__END_HASH_REF__/) {
                   3008:       #key
                   3009:       my $key='';
                   3010:       if($string =~ /^__HASH_REF__/) {
                   3011:           ($key, $string)=&str2hashref($string);
                   3012:           if(defined($key->{'error'})) {
                   3013:               $hash{'error'}='Bad data';
                   3014:               return (\%hash, $string);
                   3015:           }
                   3016:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3017:           ($key, $string)=&str2arrayref($string);
                   3018:           if($key->[0] eq 'Array reference error') {
                   3019:               $hash{'error'}='Bad data';
                   3020:               return (\%hash, $string);
                   3021:           }
                   3022:       } else {
                   3023:           $string =~ s/^(.*?)=//;
1.267     albertel 3024: 	  $key=&unescape($1);
1.265     albertel 3025:       }
                   3026:       $string =~ s/^=//;
                   3027: 
                   3028:       #value
                   3029:       my $value='';
                   3030:       if($string =~ /^__HASH_REF__/) {
                   3031:           ($value, $string)=&str2hashref($string);
                   3032:           if(defined($value->{'error'})) {
                   3033:               $hash{'error'}='Bad data';
                   3034:               return (\%hash, $string);
                   3035:           }
                   3036:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3037:           ($value, $string)=&str2arrayref($string);
                   3038:           if($value->[0] eq 'Array reference error') {
                   3039:               $hash{'error'}='Bad data';
                   3040:               return (\%hash, $string);
                   3041:           }
                   3042:       } else {
                   3043: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3044:       }
                   3045:       $string =~ s/^&//;
                   3046: 
                   3047:       $hash{$key}=$value;
1.204     albertel 3048:   }
1.265     albertel 3049: 
                   3050:   $string =~ s/^__END_HASH_REF__//;
                   3051: 
                   3052:   return (\%hash, $string);
1.204     albertel 3053: }
                   3054: 
                   3055: sub str2array {
1.265     albertel 3056:     my ($string)=@_;
                   3057:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3058:     return @$array;
                   3059: }
                   3060: 
                   3061: sub str2arrayref {
1.204     albertel 3062:   my ($string) = @_;
1.265     albertel 3063:   my @array;
                   3064: 
                   3065:   if($string !~ /^__ARRAY_REF__/) {
                   3066:       if (! ($string eq '' || !defined($string))) {
                   3067: 	  $array[0]='Array reference error';
                   3068:       }
                   3069:       return (\@array, $string);
                   3070:   }
                   3071: 
                   3072:   $string =~ s/^__ARRAY_REF__//;
                   3073: 
                   3074:   while($string !~ /^__END_ARRAY_REF__/) {
                   3075:       my $value='';
                   3076:       if($string =~ /^__HASH_REF__/) {
                   3077:           ($value, $string)=&str2hashref($string);
                   3078:           if(defined($value->{'error'})) {
                   3079:               $array[0] ='Array reference error';
                   3080:               return (\@array, $string);
                   3081:           }
                   3082:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3083:           ($value, $string)=&str2arrayref($string);
                   3084:           if($value->[0] eq 'Array reference error') {
                   3085:               $array[0] ='Array reference error';
                   3086:               return (\@array, $string);
                   3087:           }
                   3088:       } else {
                   3089: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3090:       }
                   3091:       $string =~ s/^&//;
                   3092: 
                   3093:       push(@array, $value);
1.191     harris41 3094:   }
1.265     albertel 3095: 
                   3096:   $string =~ s/^__END_ARRAY_REF__//;
                   3097: 
                   3098:   return (\@array, $string);
1.168     albertel 3099: }
                   3100: 
1.167     albertel 3101: # -------------------------------------------------------------------Temp Store
                   3102: 
1.168     albertel 3103: sub tmpreset {
                   3104:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3105:   if (!$symb) {
                   3106:     $symb=&symbread();
1.620     albertel 3107:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3108:   }
                   3109:   $symb=escape($symb);
                   3110: 
1.620     albertel 3111:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3112:   $namespace=~s/\//\_/g;
                   3113:   $namespace=~s/\W//g;
                   3114: 
1.620     albertel 3115:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3116:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3117:   if ($domain eq 'public' && $stuname eq 'public') {
                   3118:       $stuname=$ENV{'REMOTE_ADDR'};
                   3119:   }
1.168     albertel 3120:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3121:   my %hash;
                   3122:   if (tie(%hash,'GDBM_File',
                   3123: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3124: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3125:     foreach my $key (keys %hash) {
1.180     albertel 3126:       if ($key=~ /:$symb/) {
1.168     albertel 3127: 	delete($hash{$key});
                   3128:       }
                   3129:     }
                   3130:   }
                   3131: }
                   3132: 
1.167     albertel 3133: sub tmpstore {
1.168     albertel 3134:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3135: 
                   3136:   if (!$symb) {
                   3137:     $symb=&symbread();
1.620     albertel 3138:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3139:   }
                   3140:   $symb=escape($symb);
                   3141: 
                   3142:   if (!$namespace) {
                   3143:     # I don't think we would ever want to store this for a course.
                   3144:     # it seems this will only be used if we don't have a course.
1.620     albertel 3145:     #$namespace=$env{'request.course.id'};
1.168     albertel 3146:     #if (!$namespace) {
1.620     albertel 3147:       $namespace=$env{'request.state'};
1.168     albertel 3148:     #}
                   3149:   }
                   3150:   $namespace=~s/\//\_/g;
                   3151:   $namespace=~s/\W//g;
1.620     albertel 3152:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3153:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3154:   if ($domain eq 'public' && $stuname eq 'public') {
                   3155:       $stuname=$ENV{'REMOTE_ADDR'};
                   3156:   }
1.168     albertel 3157:   my $now=time;
                   3158:   my %hash;
                   3159:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3160:   if (tie(%hash,'GDBM_File',
                   3161: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3162: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3163:     $hash{"version:$symb"}++;
                   3164:     my $version=$hash{"version:$symb"};
                   3165:     my $allkeys=''; 
                   3166:     foreach my $key (keys(%$storehash)) {
                   3167:       $allkeys.=$key.':';
1.591     albertel 3168:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3169:     }
                   3170:     $hash{"$version:$symb:timestamp"}=$now;
                   3171:     $allkeys.='timestamp';
                   3172:     $hash{"$version:keys:$symb"}=$allkeys;
                   3173:     if (untie(%hash)) {
                   3174:       return 'ok';
                   3175:     } else {
                   3176:       return "error:$!";
                   3177:     }
                   3178:   } else {
                   3179:     return "error:$!";
                   3180:   }
                   3181: }
1.167     albertel 3182: 
1.168     albertel 3183: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3184: 
1.168     albertel 3185: sub tmprestore {
                   3186:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3187: 
1.168     albertel 3188:   if (!$symb) {
                   3189:     $symb=&symbread();
1.620     albertel 3190:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3191:   }
                   3192:   $symb=escape($symb);
                   3193: 
1.620     albertel 3194:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3195: 
1.620     albertel 3196:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3197:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3198:   if ($domain eq 'public' && $stuname eq 'public') {
                   3199:       $stuname=$ENV{'REMOTE_ADDR'};
                   3200:   }
1.168     albertel 3201:   my %returnhash;
                   3202:   $namespace=~s/\//\_/g;
                   3203:   $namespace=~s/\W//g;
                   3204:   my %hash;
                   3205:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3206:   if (tie(%hash,'GDBM_File',
                   3207: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3208: 	  &GDBM_READER(),0640)) {
1.168     albertel 3209:     my $version=$hash{"version:$symb"};
                   3210:     $returnhash{'version'}=$version;
                   3211:     my $scope;
                   3212:     for ($scope=1;$scope<=$version;$scope++) {
                   3213:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3214:       my @keys=split(/:/,$vkeys);
                   3215:       my $key;
                   3216:       $returnhash{"$scope:keys"}=$vkeys;
                   3217:       foreach $key (@keys) {
1.591     albertel 3218: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3219: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3220:       }
                   3221:     }
1.168     albertel 3222:     if (!(untie(%hash))) {
                   3223:       return "error:$!";
                   3224:     }
                   3225:   } else {
                   3226:     return "error:$!";
                   3227:   }
                   3228:   return %returnhash;
1.167     albertel 3229: }
                   3230: 
1.9       www      3231: # ----------------------------------------------------------------------- Store
                   3232: 
                   3233: sub store {
1.124     www      3234:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3235:     my $home='';
                   3236: 
1.168     albertel 3237:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3238: 
1.213     www      3239:     $symb=&symbclean($symb);
1.122     albertel 3240:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3241: 
1.620     albertel 3242:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3243:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3244: 
                   3245:     &devalidate($symb,$stuname,$domain);
1.109     www      3246: 
                   3247:     $symb=escape($symb);
1.187     www      3248:     if (!$namespace) { 
1.620     albertel 3249:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3250:           return ''; 
                   3251:        } 
                   3252:     }
1.620     albertel 3253:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3254: 
                   3255:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3256:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3257: 
1.12      www      3258:     my $namevalue='';
1.800     albertel 3259:     foreach my $key (keys(%$storehash)) {
                   3260:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3261:     }
1.12      www      3262:     $namevalue=~s/\&$//;
1.187     www      3263:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3264:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3265: }
                   3266: 
1.47      www      3267: # -------------------------------------------------------------- Critical Store
                   3268: 
                   3269: sub cstore {
1.124     www      3270:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3271:     my $home='';
                   3272: 
1.168     albertel 3273:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3274: 
1.213     www      3275:     $symb=&symbclean($symb);
1.122     albertel 3276:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3277: 
1.620     albertel 3278:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3279:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3280: 
                   3281:     &devalidate($symb,$stuname,$domain);
1.109     www      3282: 
                   3283:     $symb=escape($symb);
1.187     www      3284:     if (!$namespace) { 
1.620     albertel 3285:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3286:           return ''; 
                   3287:        } 
                   3288:     }
1.620     albertel 3289:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3290: 
                   3291:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3292:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3293: 
1.47      www      3294:     my $namevalue='';
1.800     albertel 3295:     foreach my $key (keys(%$storehash)) {
                   3296:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3297:     }
1.47      www      3298:     $namevalue=~s/\&$//;
1.187     www      3299:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3300:     return critical
                   3301:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3302: }
                   3303: 
1.9       www      3304: # --------------------------------------------------------------------- Restore
                   3305: 
                   3306: sub restore {
1.124     www      3307:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3308:     my $home='';
                   3309: 
1.168     albertel 3310:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3311: 
1.122     albertel 3312:     if (!$symb) {
                   3313:       unless ($symb=escape(&symbread())) { return ''; }
                   3314:     } else {
1.213     www      3315:       $symb=&escape(&symbclean($symb));
1.122     albertel 3316:     }
1.188     www      3317:     if (!$namespace) { 
1.620     albertel 3318:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3319:           return ''; 
                   3320:        } 
                   3321:     }
1.620     albertel 3322:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3323:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3324:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3325:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3326: 
1.12      www      3327:     my %returnhash=();
1.800     albertel 3328:     foreach my $line (split(/\&/,$answer)) {
                   3329: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3330:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3331:     }
1.75      www      3332:     my $version;
                   3333:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3334:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3335:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3336:        }
1.75      www      3337:     }
1.13      www      3338:     return %returnhash;
1.34      www      3339: }
                   3340: 
                   3341: # ---------------------------------------------------------- Course Description
                   3342: 
                   3343: sub coursedescription {
1.731     albertel 3344:     my ($courseid,$args)=@_;
1.34      www      3345:     $courseid=~s/^\///;
1.49      www      3346:     $courseid=~s/\_/\//g;
1.34      www      3347:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3348:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3349:     my $normalid=$cdomain.'_'.$cnum;
                   3350:     # need to always cache even if we get errors otherwise we keep 
                   3351:     # trying and trying and trying to get the course description.
                   3352:     my %envhash=();
                   3353:     my %returnhash=();
1.731     albertel 3354:     
                   3355:     my $expiretime=600;
                   3356:     if ($env{'request.course.id'} eq $normalid) {
                   3357: 	$expiretime=120;
                   3358:     }
                   3359: 
                   3360:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3361:     if (!$args->{'freshen_cache'}
                   3362: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3363: 	foreach my $key (keys(%env)) {
                   3364: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3365: 	    my ($setting) = $1;
                   3366: 	    $returnhash{$setting} = $env{$key};
                   3367: 	}
                   3368: 	return %returnhash;
                   3369:     }
                   3370: 
                   3371:     # get the data agin
                   3372:     if (!$args->{'one_time'}) {
                   3373: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3374:     }
1.811     albertel 3375: 
1.34      www      3376:     if ($chome ne 'no_host') {
1.302     albertel 3377:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3378:        if (!exists($returnhash{'con_lost'})) {
                   3379:            $returnhash{'home'}= $chome;
                   3380: 	   $returnhash{'domain'} = $cdomain;
                   3381: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3382:            if (!defined($returnhash{'type'})) {
                   3383:                $returnhash{'type'} = 'Course';
                   3384:            }
1.130     albertel 3385:            while (my ($name,$value) = each %returnhash) {
1.53      www      3386:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3387:            }
1.270     www      3388:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3389:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3390: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3391:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3392:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3393:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3394:        }
                   3395:     }
1.731     albertel 3396:     if (!$args->{'one_time'}) {
                   3397: 	&appenv(%envhash);
                   3398:     }
1.302     albertel 3399:     return %returnhash;
1.461     www      3400: }
                   3401: 
                   3402: # -------------------------------------------------See if a user is privileged
                   3403: 
                   3404: sub privileged {
                   3405:     my ($username,$domain)=@_;
                   3406:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3407: 			&homeserver($username,$domain));
                   3408:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3409:     my $now=time;
                   3410:     if ($rolesdump ne '') {
1.800     albertel 3411:         foreach my $entry (split(/&/,$rolesdump)) {
                   3412: 	    if ($entry!~/^rolesdef_/) {
                   3413: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3414: 		$area=~s/\_\w\w$//;
                   3415: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3416: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3417: 		    my $active=1;
                   3418: 		    if ($tend) {
                   3419: 			if ($tend<$now) { $active=0; }
                   3420: 		    }
                   3421: 		    if ($tstart) {
                   3422: 			if ($tstart>$now) { $active=0; }
                   3423: 		    }
                   3424: 		    if ($active) { return 1; }
                   3425: 		}
                   3426: 	    }
                   3427: 	}
                   3428:     }
                   3429:     return 0;
1.9       www      3430: }
1.1       albertel 3431: 
1.103     harris41 3432: # -------------------------------------------------------- Get user privileges
1.11      www      3433: 
                   3434: sub rolesinit {
                   3435:     my ($domain,$username,$authhost)=@_;
                   3436:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3437:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3438:     my %allroles=();
1.678     raeburn  3439:     my %allgroups=();   
1.11      www      3440:     my $now=time;
1.743     albertel 3441:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3442:     my $group_privs;
1.11      www      3443: 
                   3444:     if ($rolesdump ne '') {
1.800     albertel 3445:         foreach my $entry (split(/&/,$rolesdump)) {
                   3446: 	  if ($entry!~/^rolesdef_/) {
                   3447:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3448: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3449:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3450: 	    if ($role=~/^cr/) { 
1.807     albertel 3451: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3452: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3453: 		    ($tend,$tstart)=split('_',$trest);
                   3454: 		} else {
                   3455: 		    $trole=$role;
                   3456: 		}
1.678     raeburn  3457:             } elsif ($role =~ m|^gr/|) {
                   3458:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3459:                 ($trole,$group_privs) = split(/\//,$trole);
                   3460:                 $group_privs = &unescape($group_privs);
1.587     albertel 3461: 	    } else {
                   3462: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3463: 	    }
1.743     albertel 3464: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3465: 					 $username);
                   3466: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3467:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3468:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3469:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3470: 		my $spec=$trole.'.'.$area;
                   3471: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3472: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3473:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3474:                 } elsif ($trole eq 'gr') {
                   3475:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3476: 		} else {
1.567     raeburn  3477:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3478: 		}
1.12      www      3479:             }
1.662     raeburn  3480:           }
1.191     harris41 3481:         }
1.743     albertel 3482:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3483:         $userroles{'user.adv'}    = $adv;
                   3484: 	$userroles{'user.author'} = $author;
1.620     albertel 3485:         $env{'user.adv'}=$adv;
1.11      www      3486:     }
1.743     albertel 3487:     return \%userroles;  
1.11      www      3488: }
                   3489: 
1.567     raeburn  3490: sub set_arearole {
                   3491:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3492: # log the associated role with the area
                   3493:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3494:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3495: }
                   3496: 
                   3497: sub custom_roleprivs {
                   3498:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3499:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3500:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3501:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3502:         my ($rdummy,$roledef)=
                   3503:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3504:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3505:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3506:             if (defined($syspriv)) {
                   3507:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3508:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3509:             }
                   3510:             if ($tdomain ne '') {
                   3511:                 if (defined($dompriv)) {
                   3512:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3513:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3514:                 }
                   3515:                 if (($trest ne '') && (defined($coursepriv))) {
                   3516:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3517:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3518:                 }
                   3519:             }
                   3520:         }
                   3521:     }
                   3522: }
                   3523: 
1.678     raeburn  3524: sub group_roleprivs {
                   3525:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3526:     my $access = 1;
                   3527:     my $now = time;
                   3528:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3529:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3530:     if ($access) {
1.811     albertel 3531:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3532:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3533:     }
                   3534: }
1.567     raeburn  3535: 
                   3536: sub standard_roleprivs {
                   3537:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3538:     if (defined($pr{$trole.':s'})) {
                   3539:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3540:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3541:     }
                   3542:     if ($tdomain ne '') {
                   3543:         if (defined($pr{$trole.':d'})) {
                   3544:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3545:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3546:         }
                   3547:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3548:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3549:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3550:         }
                   3551:     }
                   3552: }
                   3553: 
                   3554: sub set_userprivs {
1.678     raeburn  3555:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3556:     my $author=0;
                   3557:     my $adv=0;
1.678     raeburn  3558:     my %grouproles = ();
                   3559:     if (keys(%{$allgroups}) > 0) {
                   3560:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3561:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3562:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3563:                 $trole = $1;
                   3564:                 $area = $2;
1.681     raeburn  3565:                 $sec = $3;
                   3566:                 $extendedarea = $area.$sec;
                   3567:                 if (exists($$allgroups{$area})) {
                   3568:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3569:                         my $spec = $trole.'.'.$extendedarea;
                   3570:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3571:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3572:                     }
                   3573:                 }
                   3574:             }
                   3575:         }
                   3576:     }
1.800     albertel 3577:     foreach my $group (keys(%grouproles)) {
                   3578:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3579:     }
1.800     albertel 3580:     foreach my $role (keys(%{$allroles})) {
                   3581:         my %thesepriv;
1.941     raeburn  3582:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3583:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3584:             if ($item ne '') {
                   3585:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3586:                 if ($restrictions eq '') {
                   3587:                     $thesepriv{$privilege}='F';
                   3588:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3589:                     $thesepriv{$privilege}.=$restrictions;
                   3590:                 }
                   3591:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3592:             }
                   3593:         }
                   3594:         my $thesestr='';
1.800     albertel 3595:         foreach my $priv (keys(%thesepriv)) {
                   3596: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3597: 	}
                   3598:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3599:     }
                   3600:     return ($author,$adv);
                   3601: }
                   3602: 
1.12      www      3603: # --------------------------------------------------------------- get interface
                   3604: 
                   3605: sub get {
1.131     albertel 3606:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3607:    my $items='';
1.800     albertel 3608:    foreach my $item (@$storearr) {
                   3609:        $items.=&escape($item).'&';
1.191     harris41 3610:    }
1.12      www      3611:    $items=~s/\&$//;
1.620     albertel 3612:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3613:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3614:    my $uhome=&homeserver($uname,$udomain);
                   3615: 
1.133     albertel 3616:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3617:    my @pairs=split(/\&/,$rep);
1.273     albertel 3618:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3619:      return @pairs;
                   3620:    }
1.15      www      3621:    my %returnhash=();
1.42      www      3622:    my $i=0;
1.800     albertel 3623:    foreach my $item (@$storearr) {
                   3624:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3625:       $i++;
1.191     harris41 3626:    }
1.15      www      3627:    return %returnhash;
1.27      www      3628: }
                   3629: 
                   3630: # --------------------------------------------------------------- del interface
                   3631: 
                   3632: sub del {
1.133     albertel 3633:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3634:    my $items='';
1.800     albertel 3635:    foreach my $item (@$storearr) {
                   3636:        $items.=&escape($item).'&';
1.191     harris41 3637:    }
1.27      www      3638:    $items=~s/\&$//;
1.620     albertel 3639:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3640:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3641:    my $uhome=&homeserver($uname,$udomain);
                   3642: 
                   3643:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3644: }
                   3645: 
                   3646: # -------------------------------------------------------------- dump interface
                   3647: 
                   3648: sub dump {
1.755     albertel 3649:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3650:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3651:     if (!$uname) { $uname=$env{'user.name'}; }
                   3652:     my $uhome=&homeserver($uname,$udomain);
                   3653:     if ($regexp) {
                   3654: 	$regexp=&escape($regexp);
                   3655:     } else {
                   3656: 	$regexp='.';
                   3657:     }
                   3658:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3659:     my @pairs=split(/\&/,$rep);
                   3660:     my %returnhash=();
                   3661:     foreach my $item (@pairs) {
                   3662: 	my ($key,$value)=split(/=/,$item,2);
                   3663: 	$key = &unescape($key);
                   3664: 	next if ($key =~ /^error: 2 /);
                   3665: 	$returnhash{$key}=&thaw_unescape($value);
                   3666:     }
                   3667:     return %returnhash;
1.407     www      3668: }
                   3669: 
1.717     albertel 3670: # --------------------------------------------------------- dumpstore interface
                   3671: 
                   3672: sub dumpstore {
                   3673:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3674:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3675:    if (!$uname) { $uname=$env{'user.name'}; }
                   3676:    my $uhome=&homeserver($uname,$udomain);
                   3677:    if ($regexp) {
                   3678:        $regexp=&escape($regexp);
                   3679:    } else {
                   3680:        $regexp='.';
                   3681:    }
                   3682:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3683:    my @pairs=split(/\&/,$rep);
                   3684:    my %returnhash=();
                   3685:    foreach my $item (@pairs) {
                   3686:        my ($key,$value)=split(/=/,$item,2);
                   3687:        next if ($key =~ /^error: 2 /);
                   3688:        $returnhash{$key}=&thaw_unescape($value);
                   3689:    }
                   3690:    return %returnhash;
1.717     albertel 3691: }
                   3692: 
1.407     www      3693: # -------------------------------------------------------------- keys interface
                   3694: 
                   3695: sub getkeys {
                   3696:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3697:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3698:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3699:    my $uhome=&homeserver($uname,$udomain);
                   3700:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3701:    my @keyarray=();
1.800     albertel 3702:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3703:       next if ($key =~ /^error: 2 /);
1.800     albertel 3704:       push(@keyarray,&unescape($key));
1.407     www      3705:    }
                   3706:    return @keyarray;
1.318     matthew  3707: }
                   3708: 
1.319     matthew  3709: # --------------------------------------------------------------- currentdump
                   3710: sub currentdump {
1.328     matthew  3711:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3712:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3713:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3714:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3715:    my $uhome = &homeserver($sname,$sdom);
                   3716:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3717:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3718:    #
1.318     matthew  3719:    my %returnhash=();
1.319     matthew  3720:    #
                   3721:    if ($rep eq "unknown_cmd") { 
                   3722:        # an old lond will not know currentdump
                   3723:        # Do a dump and make it look like a currentdump
1.822     albertel 3724:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3725:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3726:        my %hash = @tmp;
                   3727:        @tmp=();
1.424     matthew  3728:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3729:    } else {
                   3730:        my @pairs=split(/\&/,$rep);
1.800     albertel 3731:        foreach my $pair (@pairs) {
                   3732:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3733:            my ($symb,$param) = split(/:/,$key);
                   3734:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3735:                                                         &thaw_unescape($value);
1.319     matthew  3736:        }
1.191     harris41 3737:    }
1.12      www      3738:    return %returnhash;
1.424     matthew  3739: }
                   3740: 
                   3741: sub convert_dump_to_currentdump{
                   3742:     my %hash = %{shift()};
                   3743:     my %returnhash;
                   3744:     # Code ripped from lond, essentially.  The only difference
                   3745:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3746:     # we might run in to problems with parameter names =~ /^v\./
                   3747:     while (my ($key,$value) = each(%hash)) {
                   3748:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3749: 	$symb  = &unescape($symb);
                   3750: 	$param = &unescape($param);
1.424     matthew  3751:         next if ($v eq 'version' || $symb eq 'keys');
                   3752:         next if (exists($returnhash{$symb}) &&
                   3753:                  exists($returnhash{$symb}->{$param}) &&
                   3754:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3755:         $returnhash{$symb}->{$param}=$value;
                   3756:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3757:     }
                   3758:     #
                   3759:     # Remove all of the keys in the hashes which keep track of
                   3760:     # the version of the parameter.
                   3761:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3762:         # use a foreach because we are going to delete from the hash.
                   3763:         foreach my $key (keys(%$param_hash)) {
                   3764:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3765:         }
                   3766:     }
                   3767:     return \%returnhash;
1.12      www      3768: }
                   3769: 
1.627     albertel 3770: # ------------------------------------------------------ critical inc interface
                   3771: 
                   3772: sub cinc {
                   3773:     return &inc(@_,'critical');
                   3774: }
                   3775: 
1.449     matthew  3776: # --------------------------------------------------------------- inc interface
                   3777: 
                   3778: sub inc {
1.627     albertel 3779:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3780:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3781:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3782:     my $uhome=&homeserver($uname,$udomain);
                   3783:     my $items='';
                   3784:     if (! ref($store)) {
                   3785:         # got a single value, so use that instead
                   3786:         $items = &escape($store).'=&';
                   3787:     } elsif (ref($store) eq 'SCALAR') {
                   3788:         $items = &escape($$store).'=&';        
                   3789:     } elsif (ref($store) eq 'ARRAY') {
                   3790:         $items = join('=&',map {&escape($_);} @{$store});
                   3791:     } elsif (ref($store) eq 'HASH') {
                   3792:         while (my($key,$value) = each(%{$store})) {
                   3793:             $items.= &escape($key).'='.&escape($value).'&';
                   3794:         }
                   3795:     }
                   3796:     $items=~s/\&$//;
1.627     albertel 3797:     if ($critical) {
                   3798: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3799:     } else {
                   3800: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3801:     }
1.449     matthew  3802: }
                   3803: 
1.12      www      3804: # --------------------------------------------------------------- put interface
                   3805: 
                   3806: sub put {
1.134     albertel 3807:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3808:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3809:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3810:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3811:    my $items='';
1.800     albertel 3812:    foreach my $item (keys(%$storehash)) {
                   3813:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3814:    }
1.12      www      3815:    $items=~s/\&$//;
1.134     albertel 3816:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3817: }
                   3818: 
1.631     albertel 3819: # ------------------------------------------------------------ newput interface
                   3820: 
                   3821: sub newput {
                   3822:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3823:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3824:    if (!$uname) { $uname=$env{'user.name'}; }
                   3825:    my $uhome=&homeserver($uname,$udomain);
                   3826:    my $items='';
                   3827:    foreach my $key (keys(%$storehash)) {
                   3828:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3829:    }
                   3830:    $items=~s/\&$//;
                   3831:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3832: }
                   3833: 
                   3834: # ---------------------------------------------------------  putstore interface
                   3835: 
1.524     raeburn  3836: sub putstore {
1.715     albertel 3837:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3838:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3839:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3840:    my $uhome=&homeserver($uname,$udomain);
                   3841:    my $items='';
1.715     albertel 3842:    foreach my $key (keys(%$storehash)) {
                   3843:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3844:    }
1.715     albertel 3845:    $items=~s/\&$//;
1.716     albertel 3846:    my $esc_symb=&escape($symb);
                   3847:    my $esc_v=&escape($version);
1.715     albertel 3848:    my $reply =
1.716     albertel 3849:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3850: 	      $uhome);
                   3851:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3852:        # gfall back to way things use to be done
1.715     albertel 3853:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3854: 			    $uname);
1.524     raeburn  3855:    }
1.715     albertel 3856:    return $reply;
                   3857: }
                   3858: 
                   3859: sub old_putstore {
1.716     albertel 3860:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3861:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3862:     if (!$uname) { $uname=$env{'user.name'}; }
                   3863:     my $uhome=&homeserver($uname,$udomain);
                   3864:     my %newstorehash;
1.800     albertel 3865:     foreach my $item (keys(%$storehash)) {
                   3866: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3867: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3868:     }
                   3869:     my $items='';
                   3870:     my %allitems = ();
1.800     albertel 3871:     foreach my $item (keys(%newstorehash)) {
                   3872: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3873: 	    my $key = $1.':keys:'.$2;
                   3874: 	    $allitems{$key} .= $3.':';
                   3875: 	}
1.800     albertel 3876: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3877:     }
1.800     albertel 3878:     foreach my $item (keys(%allitems)) {
                   3879: 	$allitems{$item} =~ s/\:$//;
                   3880: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3881:     }
                   3882:     $items=~s/\&$//;
                   3883:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3884: }
                   3885: 
1.47      www      3886: # ------------------------------------------------------ critical put interface
                   3887: 
                   3888: sub cput {
1.134     albertel 3889:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3890:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3891:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3892:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3893:    my $items='';
1.800     albertel 3894:    foreach my $item (keys(%$storehash)) {
                   3895:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3896:    }
1.47      www      3897:    $items=~s/\&$//;
1.134     albertel 3898:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3899: }
                   3900: 
                   3901: # -------------------------------------------------------------- eget interface
                   3902: 
                   3903: sub eget {
1.133     albertel 3904:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3905:    my $items='';
1.800     albertel 3906:    foreach my $item (@$storearr) {
                   3907:        $items.=&escape($item).'&';
1.191     harris41 3908:    }
1.12      www      3909:    $items=~s/\&$//;
1.620     albertel 3910:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3911:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3912:    my $uhome=&homeserver($uname,$udomain);
                   3913:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3914:    my @pairs=split(/\&/,$rep);
                   3915:    my %returnhash=();
1.42      www      3916:    my $i=0;
1.800     albertel 3917:    foreach my $item (@$storearr) {
                   3918:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3919:       $i++;
1.191     harris41 3920:    }
1.12      www      3921:    return %returnhash;
                   3922: }
                   3923: 
1.667     albertel 3924: # ------------------------------------------------------------ tmpput interface
                   3925: sub tmpput {
1.802     raeburn  3926:     my ($storehash,$server,$context)=@_;
1.667     albertel 3927:     my $items='';
1.800     albertel 3928:     foreach my $item (keys(%$storehash)) {
                   3929: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3930:     }
                   3931:     $items=~s/\&$//;
1.802     raeburn  3932:     if (defined($context)) {
                   3933:         $items .= ':'.&escape($context);
                   3934:     }
1.667     albertel 3935:     return &reply("tmpput:$items",$server);
                   3936: }
                   3937: 
                   3938: # ------------------------------------------------------------ tmpget interface
                   3939: sub tmpget {
1.688     albertel 3940:     my ($token,$server)=@_;
                   3941:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3942:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3943:     my %returnhash;
                   3944:     foreach my $item (split(/\&/,$rep)) {
                   3945: 	my ($key,$value)=split(/=/,$item);
                   3946: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3947:     }
                   3948:     return %returnhash;
                   3949: }
                   3950: 
1.688     albertel 3951: # ------------------------------------------------------------ tmpget interface
                   3952: sub tmpdel {
                   3953:     my ($token,$server)=@_;
                   3954:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3955:     return &reply("tmpdel:$token",$server);
                   3956: }
                   3957: 
1.765     albertel 3958: # -------------------------------------------------- portfolio access checking
                   3959: 
                   3960: sub portfolio_access {
1.766     albertel 3961:     my ($requrl) = @_;
1.765     albertel 3962:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3963:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3964:     if ($result) {
                   3965:         my %setters;
                   3966:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3967:             my ($startblock,$endblock) =
                   3968:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3969:             if ($startblock && $endblock) {
                   3970:                 return 'B';
                   3971:             }
                   3972:         } else {
                   3973:             my ($startblock,$endblock) =
                   3974:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3975:             if ($startblock && $endblock) {
                   3976:                 return 'B';
                   3977:             }
                   3978:         }
                   3979:     }
1.765     albertel 3980:     if ($result eq 'ok') {
1.766     albertel 3981:        return 'F';
1.765     albertel 3982:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3983:        return 'A';
1.765     albertel 3984:     }
1.766     albertel 3985:     return '';
1.765     albertel 3986: }
                   3987: 
                   3988: sub get_portfolio_access {
1.767     albertel 3989:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3990: 
                   3991:     if (!ref($access_hash)) {
                   3992: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3993: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3994: 						   $file_name);
                   3995: 	$access_hash = $access_controls{$file_name};
                   3996:     }
                   3997: 
1.765     albertel 3998:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3999:     my $now = time;
                   4000:     if (ref($access_hash) eq 'HASH') {
                   4001:         foreach my $key (keys(%{$access_hash})) {
                   4002:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4003:             if ($start > $now) {
                   4004:                 next;
                   4005:             }
                   4006:             if ($end && $end<$now) {
                   4007:                 next;
                   4008:             }
                   4009:             if ($scope eq 'public') {
                   4010:                 $public = $key;
                   4011:                 last;
                   4012:             } elsif ($scope eq 'guest') {
                   4013:                 $guest = $key;
                   4014:             } elsif ($scope eq 'domains') {
                   4015:                 push(@domains,$key);
                   4016:             } elsif ($scope eq 'users') {
                   4017:                 push(@users,$key);
                   4018:             } elsif ($scope eq 'course') {
                   4019:                 push(@courses,$key);
                   4020:             } elsif ($scope eq 'group') {
                   4021:                 push(@groups,$key);
                   4022:             }
                   4023:         }
                   4024:         if ($public) {
                   4025:             return 'ok';
                   4026:         }
                   4027:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4028:             if ($guest) {
                   4029:                 return $guest;
                   4030:             }
                   4031:         } else {
                   4032:             if (@domains > 0) {
                   4033:                 foreach my $domkey (@domains) {
                   4034:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4035:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4036:                             return 'ok';
                   4037:                         }
                   4038:                     }
                   4039:                 }
                   4040:             }
                   4041:             if (@users > 0) {
                   4042:                 foreach my $userkey (@users) {
1.865     raeburn  4043:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4044:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4045:                             if (ref($item) eq 'HASH') {
                   4046:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4047:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4048:                                     return 'ok';
                   4049:                                 }
                   4050:                             }
                   4051:                         }
                   4052:                     } 
1.765     albertel 4053:                 }
                   4054:             }
                   4055:             my %roleshash;
                   4056:             my @courses_and_groups = @courses;
                   4057:             push(@courses_and_groups,@groups); 
                   4058:             if (@courses_and_groups > 0) {
                   4059:                 my (%allgroups,%allroles); 
                   4060:                 my ($start,$end,$role,$sec,$group);
                   4061:                 foreach my $envkey (%env) {
1.811     albertel 4062:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4063:                         my $cid = $2.'_'.$3; 
                   4064:                         if ($1 eq 'gr') {
                   4065:                             $group = $4;
                   4066:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4067:                         } else {
                   4068:                             if ($4 eq '') {
                   4069:                                 $sec = 'none';
                   4070:                             } else {
                   4071:                                 $sec = $4;
                   4072:                             }
                   4073:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4074:                         }
1.811     albertel 4075:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4076:                         my $cid = $2.'_'.$3;
                   4077:                         if ($4 eq '') {
                   4078:                             $sec = 'none';
                   4079:                         } else {
                   4080:                             $sec = $4;
                   4081:                         }
                   4082:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4083:                     }
                   4084:                 }
                   4085:                 if (keys(%allroles) == 0) {
                   4086:                     return;
                   4087:                 }
                   4088:                 foreach my $key (@courses_and_groups) {
                   4089:                     my %content = %{$$access_hash{$key}};
                   4090:                     my $cnum = $content{'number'};
                   4091:                     my $cdom = $content{'domain'};
                   4092:                     my $cid = $cdom.'_'.$cnum;
                   4093:                     if (!exists($allroles{$cid})) {
                   4094:                         next;
                   4095:                     }    
                   4096:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4097:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4098:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4099:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4100:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4101:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4102:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4103:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4104:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4105:                                         if (grep/^all$/,@sections) {
                   4106:                                             return 'ok';
                   4107:                                         } else {
                   4108:                                             if (grep/^$sec$/,@sections) {
                   4109:                                                 return 'ok';
                   4110:                                             }
                   4111:                                         }
                   4112:                                     }
                   4113:                                 }
                   4114:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4115:                                     if (grep/^none$/,@groups) {
                   4116:                                         return 'ok';
                   4117:                                     }
                   4118:                                 } else {
                   4119:                                     if (grep/^all$/,@groups) {
                   4120:                                         return 'ok';
                   4121:                                     } 
                   4122:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4123:                                         if (grep/^$group$/,@groups) {
                   4124:                                             return 'ok';
                   4125:                                         }
                   4126:                                     }
                   4127:                                 } 
                   4128:                             }
                   4129:                         }
                   4130:                     }
                   4131:                 }
                   4132:             }
                   4133:             if ($guest) {
                   4134:                 return $guest;
                   4135:             }
                   4136:         }
                   4137:     }
                   4138:     return;
                   4139: }
                   4140: 
                   4141: sub course_group_datechecker {
                   4142:     my ($dates,$now,$status) = @_;
                   4143:     my ($start,$end) = split(/\./,$dates);
                   4144:     if (!$start && !$end) {
                   4145:         return 'ok';
                   4146:     }
                   4147:     if (grep/^active$/,@{$status}) {
                   4148:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4149:             return 'ok';
                   4150:         }
                   4151:     }
                   4152:     if (grep/^previous$/,@{$status}) {
                   4153:         if ($end > $now ) {
                   4154:             return 'ok';
                   4155:         }
                   4156:     }
                   4157:     if (grep/^future$/,@{$status}) {
                   4158:         if ($start > $now) {
                   4159:             return 'ok';
                   4160:         }
                   4161:     }
                   4162:     return; 
                   4163: }
                   4164: 
                   4165: sub parse_portfolio_url {
                   4166:     my ($url) = @_;
                   4167: 
                   4168:     my ($type,$udom,$unum,$group,$file_name);
                   4169:     
1.823     albertel 4170:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4171: 	$type = 1;
                   4172:         $udom = $1;
                   4173:         $unum = $2;
                   4174:         $file_name = $3;
1.823     albertel 4175:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4176: 	$type = 2;
                   4177:         $udom = $1;
                   4178:         $unum = $2;
                   4179:         $group = $3;
                   4180:         $file_name = $3.'/'.$4;
                   4181:     }
                   4182:     if (wantarray) {
                   4183: 	return ($type,$udom,$unum,$file_name,$group);
                   4184:     }
                   4185:     return $type;
                   4186: }
                   4187: 
                   4188: sub is_portfolio_url {
                   4189:     my ($url) = @_;
                   4190:     return scalar(&parse_portfolio_url($url));
                   4191: }
                   4192: 
1.798     raeburn  4193: sub is_portfolio_file {
                   4194:     my ($file) = @_;
1.820     raeburn  4195:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4196:         return 1;
                   4197:     }
                   4198:     return;
                   4199: }
                   4200: 
                   4201: 
1.341     www      4202: # ---------------------------------------------- Custom access rule evaluation
                   4203: 
                   4204: sub customaccess {
                   4205:     my ($priv,$uri)=@_;
1.807     albertel 4206:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4207:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4208:     $udom = &LONCAPA::clean_domain($udom);
                   4209:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4210:     my $access=0;
1.800     albertel 4211:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4212: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4213: 	if ($type eq 'user') {
                   4214: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4215: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4216: 		if ($tdom) {
                   4217: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4218: 		}
1.896     albertel 4219: 		if ($tuname) {
                   4220: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4221: 		}
                   4222: 		$access=($effect eq 'allow');
                   4223: 		last;
                   4224: 	    }
                   4225: 	} else {
                   4226: 	    if ($role) {
                   4227: 		if ($role ne $urole) { next; }
                   4228: 	    }
                   4229: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4230: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4231: 		if ($tdom) {
                   4232: 		    if ($tdom ne $udom) { next; }
                   4233: 		}
                   4234: 		if ($tcrs) {
                   4235: 		    if ($tcrs ne $ucrs) { next; }
                   4236: 		}
                   4237: 		if ($tsec) {
                   4238: 		    if ($tsec ne $usec) { next; }
                   4239: 		}
                   4240: 		$access=($effect eq 'allow');
                   4241: 		last;
                   4242: 	    }
                   4243: 	    if ($realm eq '' && $role eq '') {
                   4244: 		$access=($effect eq 'allow');
                   4245: 	    }
1.402     bowersj2 4246: 	}
1.341     www      4247:     }
                   4248:     return $access;
                   4249: }
                   4250: 
1.103     harris41 4251: # ------------------------------------------------- Check for a user privilege
1.12      www      4252: 
                   4253: sub allowed {
1.810     raeburn  4254:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4255:     my $ver_orguri=$uri;
1.439     www      4256:     $uri=&deversion($uri);
1.152     www      4257:     my $orguri=$uri;
1.52      www      4258:     $uri=&declutter($uri);
1.809     raeburn  4259: 
1.810     raeburn  4260:     if ($priv eq 'evb') {
                   4261: # Evade communication block restrictions for specified role in a course
                   4262:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4263:             return $1;
                   4264:         } else {
                   4265:             return;
                   4266:         }
                   4267:     }
                   4268: 
1.620     albertel 4269:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4270: # Free bre access to adm and meta resources
1.775     albertel 4271:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4272: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4273: 	&& ($priv eq 'bre')) {
1.14      www      4274: 	return 'F';
1.159     www      4275:     }
                   4276: 
1.545     banghart 4277: # Free bre access to user's own portfolio contents
1.714     raeburn  4278:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4279:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4280: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4281:         my %setters;
                   4282:         my ($startblock,$endblock) = 
                   4283:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4284:         if ($startblock && $endblock) {
                   4285:             return 'B';
                   4286:         } else {
                   4287:             return 'F';
                   4288:         }
1.545     banghart 4289:     }
                   4290: 
1.762     raeburn  4291: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4292:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4293:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4294:         if (exists($env{'request.course.id'})) {
                   4295:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4296:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4297:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4298:                 my $courseprivid=$env{'request.course.id'};
                   4299:                 $courseprivid=~s/\_/\//;
                   4300:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4301:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4302:                     return $1; 
1.762     raeburn  4303:                 } else {
                   4304:                     if ($env{'request.course.sec'}) {
                   4305:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4306:                     }
                   4307:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4308:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4309:                         return $2;
                   4310:                     }
1.714     raeburn  4311:                 }
                   4312:             }
                   4313:         }
                   4314:     }
                   4315: 
1.159     www      4316: # Free bre to public access
                   4317: 
                   4318:     if ($priv eq 'bre') {
1.238     www      4319:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4320: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4321:            return 'F'; 
                   4322:         }
1.238     www      4323:         if ($copyright eq 'priv') {
                   4324:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4325: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4326: 		return '';
                   4327:             }
                   4328:         }
                   4329:         if ($copyright eq 'domain') {
                   4330:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4331: 	    unless (($env{'user.domain'} eq $1) ||
                   4332:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4333: 		return '';
                   4334:             }
1.262     matthew  4335:         }
1.620     albertel 4336:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4337:             # Library role, so allow browsing of resources in this domain.
                   4338:             return 'F';
1.238     www      4339:         }
1.341     www      4340:         if ($copyright eq 'custom') {
                   4341: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4342:         }
1.14      www      4343:     }
1.264     matthew  4344:     # Domain coordinator is trying to create a course
1.620     albertel 4345:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4346:         # uri is the requested domain in this case.
                   4347:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4348:         # a role of dc for the domain in question.
1.620     albertel 4349:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4350:     }
1.29      www      4351: 
1.52      www      4352:     my $thisallowed='';
                   4353:     my $statecond=0;
                   4354:     my $courseprivid='';
                   4355: 
                   4356: # Course
                   4357: 
1.620     albertel 4358:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4359:        $thisallowed.=$1;
                   4360:     }
1.29      www      4361: 
1.52      www      4362: # Domain
                   4363: 
1.620     albertel 4364:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4365:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4366:        $thisallowed.=$1;
                   4367:     }
1.52      www      4368: 
                   4369: # Course: uri itself is a course
1.66      www      4370:     my $courseuri=$uri;
                   4371:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4372:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4373: 
1.620     albertel 4374:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4375:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4376:        $thisallowed.=$1;
                   4377:     }
1.29      www      4378: 
1.665     albertel 4379: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4380: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4381:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4382: 	$thisallowed='';
1.671     raeburn  4383:         my ($match)=&is_on_map($uri);
                   4384:         if ($match) {
                   4385:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4386:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4387:                 $thisallowed.=$1;
                   4388:             }
                   4389:         } else {
1.705     albertel 4390:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4391:             if ($refuri) {
                   4392:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4393:                     $thisallowed='F';
1.671     raeburn  4394:                 } else {
                   4395:                     $refuri=&declutter($refuri);
                   4396:                     my ($match) = &is_on_map($refuri);
                   4397:                     if ($match) {
                   4398:                         $thisallowed='F';
                   4399:                     }
1.669     raeburn  4400:                 }
1.671     raeburn  4401:             }
                   4402:         }
1.314     www      4403:     }
1.492     albertel 4404: 
1.766     albertel 4405:     if ($priv eq 'bre'
                   4406: 	&& $thisallowed ne 'F' 
                   4407: 	&& $thisallowed ne '2'
                   4408: 	&& &is_portfolio_url($uri)) {
                   4409: 	$thisallowed = &portfolio_access($uri);
                   4410:     }
                   4411:     
1.52      www      4412: # Full access at system, domain or course-wide level? Exit.
1.29      www      4413: 
                   4414:     if ($thisallowed=~/F/) {
                   4415: 	return 'F';
                   4416:     }
                   4417: 
1.52      www      4418: # If this is generating or modifying users, exit with special codes
1.29      www      4419: 
1.643     www      4420:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4421: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4422: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4423: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4424: 	    unless ($auname) { return $thisallowed; }
                   4425: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4426: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4427: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4428: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4429: 	}
1.52      www      4430: 	return $thisallowed;
                   4431:     }
                   4432: #
1.103     harris41 4433: # Gathered so far: system, domain and course wide privileges
1.52      www      4434: #
                   4435: # Course: See if uri or referer is an individual resource that is part of 
                   4436: # the course
                   4437: 
1.620     albertel 4438:     if ($env{'request.course.id'}) {
1.232     www      4439: 
1.620     albertel 4440:        $courseprivid=$env{'request.course.id'};
                   4441:        if ($env{'request.course.sec'}) {
                   4442:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4443:        }
                   4444:        $courseprivid=~s/\_/\//;
                   4445:        my $checkreferer=1;
1.232     www      4446:        my ($match,$cond)=&is_on_map($uri);
                   4447:        if ($match) {
                   4448:            $statecond=$cond;
1.620     albertel 4449:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4450:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4451:                $thisallowed.=$1;
                   4452:                $checkreferer=0;
                   4453:            }
1.29      www      4454:        }
1.83      www      4455:        
1.148     www      4456:        if ($checkreferer) {
1.620     albertel 4457: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4458:             unless ($refuri) {
1.800     albertel 4459:                 foreach my $key (keys(%env)) {
                   4460: 		    if ($key=~/^httpref\..*\*/) {
                   4461: 			my $pattern=$key;
1.156     www      4462:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4463:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4464:                         $pattern=~s/\//\\\//g;
1.152     www      4465:                         if ($orguri=~/$pattern/) {
1.800     albertel 4466: 			    $refuri=$env{$key};
1.148     www      4467:                         }
                   4468:                     }
1.191     harris41 4469:                 }
1.148     www      4470:             }
1.232     www      4471: 
1.148     www      4472:          if ($refuri) { 
1.152     www      4473: 	  $refuri=&declutter($refuri);
1.232     www      4474:           my ($match,$cond)=&is_on_map($refuri);
                   4475:             if ($match) {
                   4476:               my $refstatecond=$cond;
1.620     albertel 4477:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4478:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4479:                   $thisallowed.=$1;
1.53      www      4480:                   $uri=$refuri;
                   4481:                   $statecond=$refstatecond;
1.52      www      4482:               }
                   4483:           }
1.148     www      4484:         }
1.29      www      4485:        }
1.52      www      4486:    }
1.29      www      4487: 
1.52      www      4488: #
1.103     harris41 4489: # Gathered now: all privileges that could apply, and condition number
1.52      www      4490: # 
                   4491: #
                   4492: # Full or no access?
                   4493: #
1.29      www      4494: 
1.52      www      4495:     if ($thisallowed=~/F/) {
                   4496: 	return 'F';
                   4497:     }
1.29      www      4498: 
1.52      www      4499:     unless ($thisallowed) {
                   4500:         return '';
                   4501:     }
1.29      www      4502: 
1.52      www      4503: # Restrictions exist, deal with them
                   4504: #
                   4505: #   C:according to course preferences
                   4506: #   R:according to resource settings
                   4507: #   L:unless locked
                   4508: #   X:according to user session state
                   4509: #
                   4510: 
                   4511: # Possibly locked functionality, check all courses
1.54      www      4512: # Locks might take effect only after 10 minutes cache expiration for other
                   4513: # courses, and 2 minutes for current course
1.52      www      4514: 
                   4515:     my $envkey;
                   4516:     if ($thisallowed=~/L/) {
1.620     albertel 4517:         foreach $envkey (keys %env) {
1.54      www      4518:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4519:                my $courseid=$2;
                   4520:                my $roleid=$1.'.'.$2;
1.92      www      4521:                $courseid=~s/^\///;
1.54      www      4522:                my $expiretime=600;
1.620     albertel 4523:                if ($env{'request.role'} eq $roleid) {
1.54      www      4524: 		  $expiretime=120;
                   4525:                }
                   4526: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4527:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4528:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4529: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4530:                }
1.620     albertel 4531:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4532:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4533: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4534:                        &log($env{'user.domain'},$env{'user.name'},
                   4535:                             $env{'user.home'},
1.57      www      4536:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4537:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4538:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4539: 		       return '';
                   4540:                    }
                   4541:                }
1.620     albertel 4542:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4543:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4544: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4545:                        &log($env{'user.domain'},$env{'user.name'},
                   4546:                             $env{'user.home'},
1.57      www      4547:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4548:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4549:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4550: 		       return '';
                   4551:                    }
                   4552:                }
                   4553: 	   }
1.29      www      4554:        }
1.52      www      4555:     }
                   4556:    
                   4557: #
                   4558: # Rest of the restrictions depend on selected course
                   4559: #
                   4560: 
1.620     albertel 4561:     unless ($env{'request.course.id'}) {
1.766     albertel 4562: 	if ($thisallowed eq 'A') {
                   4563: 	    return 'A';
1.814     raeburn  4564:         } elsif ($thisallowed eq 'B') {
                   4565:             return 'B';
1.766     albertel 4566: 	} else {
                   4567: 	    return '1';
                   4568: 	}
1.52      www      4569:     }
1.29      www      4570: 
1.52      www      4571: #
                   4572: # Now user is definitely in a course
                   4573: #
1.53      www      4574: 
                   4575: 
                   4576: # Course preferences
                   4577: 
                   4578:    if ($thisallowed=~/C/) {
1.620     albertel 4579:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4580:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4581:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4582: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4583: 	   if ($priv ne 'pch') { 
                   4584: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4585: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4586: 			$env{'request.course.id'});
                   4587: 	   }
1.237     www      4588:            return '';
                   4589:        }
                   4590: 
1.620     albertel 4591:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4592: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4593: 	   if ($priv ne 'pch') { 
                   4594: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4595: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4596: 			$env{'request.course.id'});
                   4597: 	   }
1.54      www      4598:            return '';
                   4599:        }
1.53      www      4600:    }
                   4601: 
                   4602: # Resource preferences
                   4603: 
                   4604:    if ($thisallowed=~/R/) {
1.620     albertel 4605:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4606:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4607: 	   if ($priv ne 'pch') { 
                   4608: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4609: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4610: 	   }
                   4611: 	   return '';
1.54      www      4612:        }
1.53      www      4613:    }
1.30      www      4614: 
1.246     www      4615: # Restricted by state or randomout?
1.30      www      4616: 
1.52      www      4617:    if ($thisallowed=~/X/) {
1.620     albertel 4618:       if ($env{'acc.randomout'}) {
1.579     albertel 4619: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4620:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4621:             return ''; 
                   4622:          }
1.247     www      4623:       }
                   4624:       if (&condval($statecond)) {
1.52      www      4625: 	 return '2';
                   4626:       } else {
                   4627:          return '';
                   4628:       }
                   4629:    }
1.30      www      4630: 
1.766     albertel 4631:     if ($thisallowed eq 'A') {
                   4632: 	return 'A';
1.814     raeburn  4633:     } elsif ($thisallowed eq 'B') {
                   4634:         return 'B';
1.766     albertel 4635:     }
1.52      www      4636:    return 'F';
1.232     www      4637: }
                   4638: 
1.710     albertel 4639: sub split_uri_for_cond {
                   4640:     my $uri=&deversion(&declutter(shift));
                   4641:     my @uriparts=split(/\//,$uri);
                   4642:     my $filename=pop(@uriparts);
                   4643:     my $pathname=join('/',@uriparts);
                   4644:     return ($pathname,$filename);
                   4645: }
1.232     www      4646: # --------------------------------------------------- Is a resource on the map?
                   4647: 
                   4648: sub is_on_map {
1.710     albertel 4649:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4650:     #Trying to find the conditional for the file
1.620     albertel 4651:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4652: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4653:     if ($match) {
1.289     bowersj2 4654: 	return (1,$1);
                   4655:     } else {
1.434     www      4656: 	return (0,0);
1.289     bowersj2 4657:     }
1.12      www      4658: }
                   4659: 
1.427     www      4660: # --------------------------------------------------------- Get symb from alias
                   4661: 
                   4662: sub get_symb_from_alias {
                   4663:     my $symb=shift;
                   4664:     my ($map,$resid,$url)=&decode_symb($symb);
                   4665: # Already is a symb
                   4666:     if ($url) { return $symb; }
                   4667: # Must be an alias
                   4668:     my $aliassymb='';
                   4669:     my %bighash;
1.620     albertel 4670:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4671:                             &GDBM_READER(),0640)) {
                   4672:         my $rid=$bighash{'mapalias_'.$symb};
                   4673: 	if ($rid) {
                   4674: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4675: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4676: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4677: 	}
                   4678:         untie %bighash;
                   4679:     }
                   4680:     return $aliassymb;
                   4681: }
                   4682: 
1.12      www      4683: # ----------------------------------------------------------------- Define Role
                   4684: 
                   4685: sub definerole {
                   4686:   if (allowed('mcr','/')) {
                   4687:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4688:     foreach my $role (split(':',$sysrole)) {
                   4689: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4690:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4691:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4692: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4693:                return "refused:s:$crole&$cqual"; 
                   4694:             }
                   4695:         }
1.191     harris41 4696:     }
1.800     albertel 4697:     foreach my $role (split(':',$domrole)) {
                   4698: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4699:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4700:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4701: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4702:                return "refused:d:$crole&$cqual"; 
                   4703:             }
                   4704:         }
1.191     harris41 4705:     }
1.800     albertel 4706:     foreach my $role (split(':',$courole)) {
                   4707: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4708:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4709:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4710: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4711:                return "refused:c:$crole&$cqual"; 
                   4712:             }
                   4713:         }
1.191     harris41 4714:     }
1.620     albertel 4715:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4716:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4717: 	        "rolesdef_$rolename=".
                   4718:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4719:     return reply($command,$env{'user.home'});
1.12      www      4720:   } else {
                   4721:     return 'refused';
                   4722:   }
1.105     harris41 4723: }
                   4724: 
                   4725: # ---------------- Make a metadata query against the network of library servers
                   4726: 
                   4727: sub metadata_query {
1.244     matthew  4728:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4729:     my %rhash;
1.845     albertel 4730:     my %libserv = &all_library();
1.244     matthew  4731:     my @server_list = (defined($server_array) ? @$server_array
                   4732:                                               : keys(%libserv) );
                   4733:     for my $server (@server_list) {
1.118     harris41 4734: 	unless ($custom or $customshow) {
                   4735: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4736: 	    $rhash{$server}=$reply;
                   4737: 	}
                   4738: 	else {
                   4739: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4740: 			     &escape($custom).':'.&escape($customshow),
                   4741: 			     $server);
                   4742: 	    $rhash{$server}=$reply;
                   4743: 	}
1.112     harris41 4744:     }
1.118     harris41 4745:     return \%rhash;
1.240     www      4746: }
                   4747: 
                   4748: # ----------------------------------------- Send log queries and wait for reply
                   4749: 
                   4750: sub log_query {
                   4751:     my ($uname,$udom,$query,%filters)=@_;
                   4752:     my $uhome=&homeserver($uname,$udom);
                   4753:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4754:     my $uhost=&hostname($uhome);
1.800     albertel 4755:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4756:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4757:                        $uhome);
1.479     albertel 4758:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4759:     return get_query_reply($queryid);
                   4760: }
                   4761: 
1.818     raeburn  4762: # -------------------------- Update MySQL table for portfolio file
                   4763: 
                   4764: sub update_portfolio_table {
1.821     raeburn  4765:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4766:     my $homeserver = &homeserver($uname,$udom);
                   4767:     my $queryid=
1.821     raeburn  4768:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4769:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4770:     my $reply = &get_query_reply($queryid);
                   4771:     return $reply;
                   4772: }
                   4773: 
1.899     raeburn  4774: # -------------------------- Update MySQL allusers table
                   4775: 
                   4776: sub update_allusers_table {
                   4777:     my ($uname,$udom,$names) = @_;
                   4778:     my $homeserver = &homeserver($uname,$udom);
                   4779:     my $queryid=
                   4780:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4781:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4782:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4783:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4784:                'generation='.&escape($names->{'generation'}).'%%'.
                   4785:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4786:                'id='.&escape($names->{'id'}),$homeserver);
                   4787:     my $reply = &get_query_reply($queryid);
                   4788:     return $reply;
                   4789: }
                   4790: 
1.508     raeburn  4791: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4792: 
                   4793: sub fetch_enrollment_query {
1.511     raeburn  4794:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4795:     my $homeserver;
1.547     raeburn  4796:     my $maxtries = 1;
1.508     raeburn  4797:     if ($context eq 'automated') {
                   4798:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4799:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4800:     } else {
                   4801:         $homeserver = &homeserver($cnum,$dom);
                   4802:     }
1.838     albertel 4803:     my $host=&hostname($homeserver);
1.506     raeburn  4804:     my $cmd = '';
1.800     albertel 4805:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4806:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4807:     }
                   4808:     $cmd =~ s/%%$//;
                   4809:     $cmd = &escape($cmd);
                   4810:     my $query = 'fetchenrollment';
1.620     albertel 4811:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4812:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4813:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4814:         return 'error: '.$queryid;
                   4815:     }
1.506     raeburn  4816:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4817:     my $tries = 1;
                   4818:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4819:         $reply = &get_query_reply($queryid);
                   4820:         $tries ++;
                   4821:     }
1.526     raeburn  4822:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4823:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4824:     } else {
1.901     albertel 4825:         my @responses = split(/:/,$reply);
1.515     raeburn  4826:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4827:             foreach my $line (@responses) {
                   4828:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4829:                 $$replyref{$key} = $value;
                   4830:             }
                   4831:         } else {
1.506     raeburn  4832:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4833:             foreach my $line (@responses) {
                   4834:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4835:                 $$replyref{$key} = $value;
                   4836:                 if ($value > 0) {
1.800     albertel 4837:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4838:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4839:                         my $destname = $pathname.'/'.$filename;
                   4840:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4841:                         if ($xml_classlist =~ /^error/) {
                   4842:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4843:                         } else {
1.506     raeburn  4844:                             if ( open(FILE,">$destname") ) {
                   4845:                                 print FILE &unescape($xml_classlist);
                   4846:                                 close(FILE);
1.526     raeburn  4847:                             } else {
                   4848:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4849:                             }
                   4850:                         }
                   4851:                     }
                   4852:                 }
                   4853:             }
                   4854:         }
                   4855:         return 'ok';
                   4856:     }
                   4857:     return 'error';
                   4858: }
                   4859: 
1.242     www      4860: sub get_query_reply {
                   4861:     my $queryid=shift;
1.240     www      4862:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4863:     my $reply='';
                   4864:     for (1..100) {
                   4865: 	sleep 2;
                   4866:         if (-e $replyfile.'.end') {
1.448     albertel 4867: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4868: 		$reply = join('',<$fh>);
                   4869: 		close($fh);
1.240     www      4870: 	   } else { return 'error: reply_file_error'; }
1.242     www      4871:            return &unescape($reply);
                   4872: 	}
1.240     www      4873:     }
1.242     www      4874:     return 'timeout:'.$queryid;
1.240     www      4875: }
                   4876: 
                   4877: sub courselog_query {
1.241     www      4878: #
                   4879: # possible filters:
                   4880: # url: url or symb
                   4881: # username
                   4882: # domain
                   4883: # action: view, submit, grade
                   4884: # start: timestamp
                   4885: # end: timestamp
                   4886: #
1.240     www      4887:     my (%filters)=@_;
1.620     albertel 4888:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4889:     if ($filters{'url'}) {
                   4890: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4891:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4892:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4893:     }
1.620     albertel 4894:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4895:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4896:     return &log_query($cname,$cdom,'courselog',%filters);
                   4897: }
                   4898: 
                   4899: sub userlog_query {
1.858     raeburn  4900: #
                   4901: # possible filters:
                   4902: # action: log check role
                   4903: # start: timestamp
                   4904: # end: timestamp
                   4905: #
1.240     www      4906:     my ($uname,$udom,%filters)=@_;
                   4907:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4908: }
                   4909: 
1.506     raeburn  4910: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4911: 
                   4912: sub auto_run {
1.508     raeburn  4913:     my ($cnum,$cdom) = @_;
1.876     raeburn  4914:     my $response = 0;
                   4915:     my $settings;
                   4916:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4917:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4918:         $settings = $domconfig{'autoenroll'};
                   4919:         if ($settings->{'run'} eq '1') {
                   4920:             $response = 1;
                   4921:         }
                   4922:     } else {
1.934     raeburn  4923:         my $homeserver;
                   4924:         if (&is_course($cdom,$cnum)) {
                   4925:             $homeserver = &homeserver($cnum,$cdom);
                   4926:         } else {
                   4927:             $homeserver = &domain($cdom,'primary');
                   4928:         }
                   4929:         if ($homeserver ne 'no_host') {
                   4930:             $response = &reply('autorun:'.$cdom,$homeserver);
                   4931:         }
1.876     raeburn  4932:     }
1.506     raeburn  4933:     return $response;
                   4934: }
1.776     albertel 4935: 
1.506     raeburn  4936: sub auto_get_sections {
1.508     raeburn  4937:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4938:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4939:     my @secs = ();
1.511     raeburn  4940:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4941:     unless ($response eq 'refused') {
1.901     albertel 4942:         @secs = split(/:/,$response);
1.506     raeburn  4943:     }
                   4944:     return @secs;
                   4945: }
1.776     albertel 4946: 
1.506     raeburn  4947: sub auto_new_course {
1.508     raeburn  4948:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4949:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4950:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4951:     return $response;
                   4952: }
1.776     albertel 4953: 
1.506     raeburn  4954: sub auto_validate_courseID {
1.508     raeburn  4955:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4956:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4957:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4958:     return $response;
                   4959: }
1.776     albertel 4960: 
1.506     raeburn  4961: sub auto_create_password {
1.873     raeburn  4962:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4963:     my ($homeserver,$response);
1.506     raeburn  4964:     my $create_passwd = 0;
                   4965:     my $authchk = '';
1.873     raeburn  4966:     if ($udom =~ /^$match_domain$/) {
                   4967:         $homeserver = &domain($udom,'primary');
                   4968:     }
                   4969:     if ($homeserver eq '') {
                   4970:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4971:             $homeserver = &homeserver($cnum,$cdom);
                   4972:         }
                   4973:     }
                   4974:     if ($homeserver eq '') {
                   4975:         $authchk = 'nodomain';
1.506     raeburn  4976:     } else {
1.873     raeburn  4977:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4978:         if ($response eq 'refused') {
                   4979:             $authchk = 'refused';
                   4980:         } else {
1.901     albertel 4981:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4982:         }
1.506     raeburn  4983:     }
                   4984:     return ($authparam,$create_passwd,$authchk);
                   4985: }
                   4986: 
1.706     raeburn  4987: sub auto_photo_permission {
                   4988:     my ($cnum,$cdom,$students) = @_;
                   4989:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4990:     my ($outcome,$perm_reqd,$conditions) = 
                   4991: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4992:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4993: 	return (undef,undef);
                   4994:     }
1.706     raeburn  4995:     return ($outcome,$perm_reqd,$conditions);
                   4996: }
                   4997: 
                   4998: sub auto_checkphotos {
                   4999:     my ($uname,$udom,$pid) = @_;
                   5000:     my $homeserver = &homeserver($uname,$udom);
                   5001:     my ($result,$resulttype);
                   5002:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5003: 				   &escape($uname).':'.&escape($pid),
                   5004: 				   $homeserver));
1.709     albertel 5005:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5006: 	return (undef,undef);
                   5007:     }
1.706     raeburn  5008:     if ($outcome) {
                   5009:         ($result,$resulttype) = split(/:/,$outcome);
                   5010:     } 
                   5011:     return ($result,$resulttype);
                   5012: }
                   5013: 
                   5014: sub auto_photochoice {
                   5015:     my ($cnum,$cdom) = @_;
                   5016:     my $homeserver = &homeserver($cnum,$cdom);
                   5017:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5018: 						       &escape($cdom),
                   5019: 						       $homeserver)));
1.709     albertel 5020:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5021: 	return (undef,undef);
                   5022:     }
1.706     raeburn  5023:     return ($update,$comment);
                   5024: }
                   5025: 
                   5026: sub auto_photoupdate {
                   5027:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5028:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5029:     my $host=&hostname($homeserver);
1.706     raeburn  5030:     my $cmd = '';
                   5031:     my $maxtries = 1;
1.800     albertel 5032:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5033:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5034:     }
                   5035:     $cmd =~ s/%%$//;
                   5036:     $cmd = &escape($cmd);
                   5037:     my $query = 'institutionalphotos';
                   5038:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5039:     unless ($queryid=~/^\Q$host\E\_/) {
                   5040:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5041:         return 'error: '.$queryid;
                   5042:     }
                   5043:     my $reply = &get_query_reply($queryid);
                   5044:     my $tries = 1;
                   5045:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5046:         $reply = &get_query_reply($queryid);
                   5047:         $tries ++;
                   5048:     }
                   5049:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5050:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5051:     } else {
                   5052:         my @responses = split(/:/,$reply);
                   5053:         my $outcome = shift(@responses); 
                   5054:         foreach my $item (@responses) {
                   5055:             my ($key,$value) = split(/=/,$item);
                   5056:             $$photo{$key} = $value;
                   5057:         }
                   5058:         return $outcome;
                   5059:     }
                   5060:     return 'error';
                   5061: }
                   5062: 
1.521     raeburn  5063: sub auto_instcode_format {
1.793     albertel 5064:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5065: 	$cat_order) = @_;
1.521     raeburn  5066:     my $courses = '';
1.772     raeburn  5067:     my @homeservers;
1.521     raeburn  5068:     if ($caller eq 'global') {
1.841     albertel 5069: 	my %servers = &get_servers($codedom,'library');
                   5070: 	foreach my $tryserver (keys(%servers)) {
                   5071: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5072: 		push(@homeservers,$tryserver);
                   5073: 	    }
1.584     raeburn  5074:         }
1.521     raeburn  5075:     } else {
1.772     raeburn  5076:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5077:     }
1.793     albertel 5078:     foreach my $code (keys(%{$instcodes})) {
                   5079:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5080:     }
                   5081:     chop($courses);
1.772     raeburn  5082:     my $ok_response = 0;
                   5083:     my $response;
                   5084:     while (@homeservers > 0 && $ok_response == 0) {
                   5085:         my $server = shift(@homeservers); 
                   5086:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5087:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5088:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5089: 		split(/:/,$response);
1.772     raeburn  5090:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5091:             push(@{$codetitles},&str2array($codetitles_str));
                   5092:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5093:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5094:             $ok_response = 1;
                   5095:         }
                   5096:     }
                   5097:     if ($ok_response) {
1.521     raeburn  5098:         return 'ok';
1.772     raeburn  5099:     } else {
                   5100:         return $response;
1.521     raeburn  5101:     }
                   5102: }
                   5103: 
1.792     raeburn  5104: sub auto_instcode_defaults {
                   5105:     my ($domain,$returnhash,$code_order) = @_;
                   5106:     my @homeservers;
1.841     albertel 5107: 
                   5108:     my %servers = &get_servers($domain,'library');
                   5109:     foreach my $tryserver (keys(%servers)) {
                   5110: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5111: 	    push(@homeservers,$tryserver);
                   5112: 	}
1.792     raeburn  5113:     }
1.841     albertel 5114: 
1.792     raeburn  5115:     my $response;
1.841     albertel 5116:     foreach my $server (@homeservers) {
1.792     raeburn  5117:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5118:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5119: 	
                   5120: 	foreach my $pair (split(/\&/,$response)) {
                   5121: 	    my ($name,$value)=split(/\=/,$pair);
                   5122: 	    if ($name eq 'code_order') {
                   5123: 		@{$code_order} = split(/\&/,&unescape($value));
                   5124: 	    } else {
                   5125: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5126: 	    }
                   5127: 	}
                   5128: 	return 'ok';
1.792     raeburn  5129:     }
1.841     albertel 5130: 
                   5131:     return $response;
1.792     raeburn  5132: } 
                   5133: 
1.777     albertel 5134: sub auto_validate_class_sec {
1.918     raeburn  5135:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5136:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5137:     my $ownerlist;
                   5138:     if (ref($owners) eq 'ARRAY') {
                   5139:         $ownerlist = join(',',@{$owners});
                   5140:     } else {
                   5141:         $ownerlist = $owners;
                   5142:     }
1.773     raeburn  5143:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5144:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5145:     return $response;
                   5146: }
                   5147: 
1.679     raeburn  5148: # ------------------------------------------------------- Course Group routines
                   5149: 
                   5150: sub get_coursegroups {
1.809     raeburn  5151:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5152:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5153: }
                   5154: 
1.679     raeburn  5155: sub modify_coursegroup {
                   5156:     my ($cdom,$cnum,$groupsettings) = @_;
                   5157:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5158: }
                   5159: 
1.809     raeburn  5160: sub toggle_coursegroup_status {
                   5161:     my ($cdom,$cnum,$group,$action) = @_;
                   5162:     my ($from_namespace,$to_namespace);
                   5163:     if ($action eq 'delete') {
                   5164:         $from_namespace = 'coursegroups';
                   5165:         $to_namespace = 'deleted_groups';
                   5166:     } else {
                   5167:         $from_namespace = 'deleted_groups';
                   5168:         $to_namespace = 'coursegroups';
                   5169:     }
                   5170:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5171:     if (my $tmp = &error(%curr_group)) {
                   5172:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5173:         return ('read error',$tmp);
                   5174:     } else {
                   5175:         my %savedsettings = %curr_group; 
1.809     raeburn  5176:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5177:         my $deloutcome;
                   5178:         if ($result eq 'ok') {
1.809     raeburn  5179:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5180:         } else {
                   5181:             return ('write error',$result);
                   5182:         }
                   5183:         if ($deloutcome eq 'ok') {
                   5184:             return 'ok';
                   5185:         } else {
                   5186:             return ('delete error',$deloutcome);
                   5187:         }
                   5188:     }
                   5189: }
                   5190: 
1.679     raeburn  5191: sub modify_group_roles {
                   5192:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5193:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5194:     my $role = 'gr/'.&escape($userprivs);
                   5195:     my ($uname,$udom) = split(/:/,$user);
                   5196:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5197:     if ($result eq 'ok') {
                   5198:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5199:     }
1.679     raeburn  5200:     return $result;
                   5201: }
                   5202: 
                   5203: sub modify_coursegroup_membership {
                   5204:     my ($cdom,$cnum,$membership) = @_;
                   5205:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5206:     return $result;
                   5207: }
                   5208: 
1.682     raeburn  5209: sub get_active_groups {
                   5210:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5211:     my $now = time;
                   5212:     my %groups = ();
                   5213:     foreach my $key (keys(%env)) {
1.811     albertel 5214:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5215:             my ($start,$end) = split(/\./,$env{$key});
                   5216:             if (($end!=0) && ($end<$now)) { next; }
                   5217:             if (($start!=0) && ($start>$now)) { next; }
                   5218:             if ($1 eq $cdom && $2 eq $cnum) {
                   5219:                 $groups{$3} = $env{$key} ;
                   5220:             }
                   5221:         }
                   5222:     }
                   5223:     return %groups;
                   5224: }
                   5225: 
1.683     raeburn  5226: sub get_group_membership {
                   5227:     my ($cdom,$cnum,$group) = @_;
                   5228:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5229: }
                   5230: 
                   5231: sub get_users_groups {
                   5232:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5233:     my @usersgroups;
1.683     raeburn  5234:     my $cachetime=1800;
                   5235: 
                   5236:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5237:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5238:     if (defined($cached)) {
1.734     albertel 5239:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5240:     } else {  
                   5241:         $grouplist = '';
1.816     raeburn  5242:         my $courseurl = &courseid_to_courseurl($courseid);
                   5243:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5244:         my $access_end = $env{'course.'.$courseid.
                   5245:                               '.default_enrollment_end_date'};
                   5246:         my $now = time;
                   5247:         foreach my $key (keys(%roleshash)) {
                   5248:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5249:                 my $group = $1;
                   5250:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5251:                     my $start = $2;
                   5252:                     my $end = $1;
                   5253:                     if ($start == -1) { next; } # deleted from group
                   5254:                     if (($start!=0) && ($start>$now)) { next; }
                   5255:                     if (($end!=0) && ($end<$now)) {
                   5256:                         if ($access_end && $access_end < $now) {
                   5257:                             if ($access_end - $end < 86400) {
                   5258:                                 push(@usersgroups,$group);
1.733     raeburn  5259:                             }
                   5260:                         }
1.817     raeburn  5261:                         next;
1.733     raeburn  5262:                     }
1.817     raeburn  5263:                     push(@usersgroups,$group);
1.683     raeburn  5264:                 }
                   5265:             }
                   5266:         }
1.817     raeburn  5267:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5268:         $grouplist = join(':',@usersgroups);
                   5269:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5270:     }
1.733     raeburn  5271:     return @usersgroups;
1.683     raeburn  5272: }
                   5273: 
                   5274: sub devalidate_getgroups_cache {
                   5275:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5276:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5277: 
1.683     raeburn  5278:     my $hashid="$udom:$uname:$courseid";
                   5279:     &devalidate_cache_new('getgroups',$hashid);
                   5280: }
                   5281: 
1.12      www      5282: # ------------------------------------------------------------------ Plain Text
                   5283: 
                   5284: sub plaintext {
1.742     raeburn  5285:     my ($short,$type,$cid) = @_;
1.758     albertel 5286:     if ($short =~ /^cr/) {
                   5287: 	return (split('/',$short))[-1];
                   5288:     }
1.742     raeburn  5289:     if (!defined($cid)) {
                   5290:         $cid = $env{'request.course.id'};
                   5291:     }
                   5292:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5293:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5294:                                           '.plaintext'});
                   5295:     }
                   5296:     my %rolenames = (
                   5297:                       Course => 'std',
                   5298:                       Group => 'alt1',
                   5299:                     );
                   5300:     if (defined($type) && 
                   5301:          defined($rolenames{$type}) && 
                   5302:          defined($prp{$short}{$rolenames{$type}})) {
                   5303:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5304:     } else {
                   5305:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5306:     }
1.12      www      5307: }
                   5308: 
                   5309: # ----------------------------------------------------------------- Assign Role
                   5310: 
                   5311: sub assignrole {
1.357     www      5312:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5313:     my $mrole;
                   5314:     if ($role =~ /^cr\//) {
1.393     www      5315:         my $cwosec=$url;
1.811     albertel 5316:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5317: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5318:            &logthis('Refused custom assignrole: '.
                   5319:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5320: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5321:            return 'refused'; 
                   5322:         }
1.21      www      5323:         $mrole='cr';
1.678     raeburn  5324:     } elsif ($role =~ /^gr\//) {
                   5325:         my $cwogrp=$url;
1.811     albertel 5326:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5327:         unless (&allowed('mdg',$cwogrp)) {
                   5328:             &logthis('Refused group assignrole: '.
                   5329:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5330:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5331:             return 'refused';
                   5332:         }
                   5333:         $mrole='gr';
1.21      www      5334:     } else {
1.82      www      5335:         my $cwosec=$url;
1.811     albertel 5336:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5337:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5338:             my $refused;
                   5339:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5340:                 if (!(&allowed('c'.$role,$url))) {
                   5341:                     $refused = 1;
                   5342:                 }
                   5343:             } else {
                   5344:                 $refused = 1;
                   5345:             }
                   5346:             if ($refused) { 
                   5347:                 &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5348:                          ' '.$role.' '.$end.' '.$start.' by '.
                   5349: 	  	         $env{'user.name'}.' at '.$env{'user.domain'});
                   5350:                 return 'refused';
                   5351:             }
1.104     www      5352:         }
1.21      www      5353:         $mrole=$role;
                   5354:     }
1.620     albertel 5355:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5356:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5357:     if ($end) { $command.='_'.$end; }
1.21      www      5358:     if ($start) {
                   5359: 	if ($end) { 
1.81      www      5360:            $command.='_'.$start; 
1.21      www      5361:         } else {
1.81      www      5362:            $command.='_0_'.$start;
1.21      www      5363:         }
                   5364:     }
1.739     raeburn  5365:     my $origstart = $start;
                   5366:     my $origend = $end;
1.357     www      5367: # actually delete
                   5368:     if ($deleteflag) {
1.373     www      5369: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5370: # modify command to delete the role
1.620     albertel 5371:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5372:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5373: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5374: # set start and finish to negative values for userrolelog
                   5375:            $start=-1;
                   5376:            $end=-1;
                   5377:         }
                   5378:     }
                   5379: # send command
1.349     www      5380:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5381: # log new user role if status is ok
1.349     www      5382:     if ($answer eq 'ok') {
1.663     raeburn  5383: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5384: # for course roles, perform group memberships changes triggered by role change.
                   5385:         unless ($role =~ /^gr/) {
                   5386:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5387:                                              $origstart);
                   5388:         }
1.349     www      5389:     }
                   5390:     return $answer;
1.169     harris41 5391: }
                   5392: 
                   5393: # -------------------------------------------------- Modify user authentication
1.197     www      5394: # Overrides without validation
                   5395: 
1.169     harris41 5396: sub modifyuserauth {
                   5397:     my ($udom,$uname,$umode,$upass)=@_;
                   5398:     my $uhome=&homeserver($uname,$udom);
1.197     www      5399:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5400:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5401:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5402:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5403:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5404: 		     &escape($upass),$uhome);
1.620     albertel 5405:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5406:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5407:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5408:     &log($udom,,$uname,$uhome,
1.620     albertel 5409:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5410:                                      $env{'user.name'}.', '.$umode.
1.197     www      5411:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5412:     unless ($reply eq 'ok') {
1.197     www      5413:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5414: 	return 'error: '.$reply;
                   5415:     }   
1.170     harris41 5416:     return 'ok';
1.80      www      5417: }
                   5418: 
1.81      www      5419: # --------------------------------------------------------------- Modify a user
1.80      www      5420: 
1.81      www      5421: sub modifyuser {
1.206     matthew  5422:     my ($udom,    $uname, $uid,
                   5423:         $umode,   $upass, $first,
                   5424:         $middle,  $last,  $gene,
1.387     www      5425:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5426:     $udom= &LONCAPA::clean_domain($udom);
                   5427:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5428:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5429:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5430: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5431:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5432:                                      ' desiredhome not specified'). 
1.620     albertel 5433:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5434:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5435:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5436: # ----------------------------------------------------------------- Create User
1.406     albertel 5437:     if (($uhome eq 'no_host') && 
                   5438: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5439:         my $unhome='';
1.844     albertel 5440:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5441:             $unhome = $desiredhome;
1.620     albertel 5442: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5443: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5444:         } else { # load balancing routine for determining $unhome
1.81      www      5445:             my $loadm=10000000;
1.841     albertel 5446: 	    my %servers = &get_servers($udom,'library');
                   5447: 	    foreach my $tryserver (keys(%servers)) {
                   5448: 		my $answer=reply('load',$tryserver);
                   5449: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5450: 		    $loadm=$answer;
                   5451: 		    $unhome=$tryserver;
                   5452: 		}
1.80      www      5453: 	    }
                   5454:         }
                   5455:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5456: 	    return 'error: unable to find a home server for '.$uname.
                   5457:                    ' in domain '.$udom;
1.80      www      5458:         }
                   5459:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5460:                          &escape($upass),$unhome);
                   5461: 	unless ($reply eq 'ok') {
                   5462:             return 'error: '.$reply;
                   5463:         }   
1.230     stredwic 5464:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5465:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5466: 	    return 'error: unable verify users home machine.';
1.80      www      5467:         }
1.209     matthew  5468:     }   # End of creation of new user
1.80      www      5469: # ---------------------------------------------------------------------- Add ID
                   5470:     if ($uid) {
                   5471:        $uid=~tr/A-Z/a-z/;
                   5472:        my %uidhash=&idrget($udom,$uname);
1.196     www      5473:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5474:          && (!$forceid)) {
1.80      www      5475: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5476: 	      return 'error: user id "'.$uid.'" does not match '.
                   5477:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5478:           }
                   5479:        } else {
                   5480: 	  &idput($udom,($uname => $uid));
                   5481:        }
                   5482:     }
                   5483: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5484:     my @tmp=&get('environment',
1.899     raeburn  5485: 		   ['firstname','middlename','lastname','generation','id',
                   5486:                     'permanentemail'],
1.134     albertel 5487: 		   $udom,$uname);
1.313     matthew  5488:     my %names;
                   5489:     if ($tmp[0] =~ m/^error:.*/) { 
                   5490:         %names=(); 
                   5491:     } else {
                   5492:         %names = @tmp;
                   5493:     }
1.388     www      5494: #
                   5495: # Make sure to not trash student environment if instructor does not bother
                   5496: # to supply name and email information
                   5497: #
                   5498:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5499:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5500:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5501:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5502:     if ($email) {
                   5503:        $email=~s/[^\w\@\.\-\,]//gs;
                   5504:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5505: 			   $names{'critnotification'} = $email;
                   5506: 			   $names{'permanentemail'} = $email; }
                   5507:     }
1.899     raeburn  5508:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5509:     my $reply = &put('environment', \%names, $udom,$uname);
                   5510:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5511:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5512:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5513:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5514:              $umode.', '.$first.', '.$middle.', '.
                   5515: 	     $last.', '.$gene.' by '.
1.620     albertel 5516:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5517:     return 'ok';
1.80      www      5518: }
                   5519: 
1.81      www      5520: # -------------------------------------------------------------- Modify student
1.80      www      5521: 
1.81      www      5522: sub modifystudent {
                   5523:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5524:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5525:     if (!$cid) {
1.620     albertel 5526: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5527: 	    return 'not_in_class';
                   5528: 	}
1.80      www      5529:     }
                   5530: # --------------------------------------------------------------- Make the user
1.81      www      5531:     my $reply=&modifyuser
1.209     matthew  5532: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5533:          $desiredhome,$email);
1.80      www      5534:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5535:     # This will cause &modify_student_enrollment to get the uid from the
                   5536:     # students environment
                   5537:     $uid = undef if (!$forceid);
1.455     albertel 5538:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5539: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5540:     return $reply;
                   5541: }
                   5542: 
                   5543: sub modify_student_enrollment {
1.515     raeburn  5544:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5545:     my ($cdom,$cnum,$chome);
                   5546:     if (!$cid) {
1.620     albertel 5547: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5548: 	    return 'not_in_class';
                   5549: 	}
1.620     albertel 5550: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5551: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5552:     } else {
                   5553: 	($cdom,$cnum)=split(/_/,$cid);
                   5554:     }
1.620     albertel 5555:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5556:     if (!$chome) {
1.457     raeburn  5557: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5558:     }
1.455     albertel 5559:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5560:     # Make sure the user exists
1.81      www      5561:     my $uhome=&homeserver($uname,$udom);
                   5562:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5563: 	return 'error: no such user';
                   5564:     }
1.297     matthew  5565:     # Get student data if we were not given enough information
                   5566:     if (!defined($first)  || $first  eq '' || 
                   5567:         !defined($last)   || $last   eq '' || 
                   5568:         !defined($uid)    || $uid    eq '' || 
                   5569:         !defined($middle) || $middle eq '' || 
                   5570:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5571:         # They did not supply us with enough data to enroll the student, so
                   5572:         # we need to pick up more information.
1.297     matthew  5573:         my %tmp = &get('environment',
1.294     matthew  5574:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5575:                        ,$udom,$uname);
                   5576: 
1.800     albertel 5577:         #foreach my $key (keys(%tmp)) {
                   5578:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5579:         #}
1.294     matthew  5580:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5581:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5582:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5583:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5584:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5585:     }
1.556     albertel 5586:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5587:     my $reply=cput('classlist',
                   5588: 		   {"$uname:$udom" => 
1.515     raeburn  5589: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5590: 		   $cdom,$cnum);
1.81      www      5591:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5592: 	return 'error: '.$reply;
1.652     albertel 5593:     } else {
                   5594: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5595:     }
1.297     matthew  5596:     # Add student role to user
1.83      www      5597:     my $uurl='/'.$cid;
1.81      www      5598:     $uurl=~s/\_/\//g;
                   5599:     if ($usec) {
                   5600: 	$uurl.='/'.$usec;
                   5601:     }
                   5602:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5603: }
                   5604: 
1.556     albertel 5605: sub format_name {
                   5606:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5607:     my $name;
                   5608:     if ($first ne 'lastname') {
                   5609: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5610:     } else {
                   5611: 	if ($lastname=~/\S/) {
                   5612: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5613: 	    $name=~s/\s+,/,/;
                   5614: 	} else {
                   5615: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5616: 	}
                   5617:     }
                   5618:     $name=~s/^\s+//;
                   5619:     $name=~s/\s+$//;
                   5620:     $name=~s/\s+/ /g;
                   5621:     return $name;
                   5622: }
                   5623: 
1.84      www      5624: # ------------------------------------------------- Write to course preferences
                   5625: 
                   5626: sub writecoursepref {
                   5627:     my ($courseid,%prefs)=@_;
                   5628:     $courseid=~s/^\///;
                   5629:     $courseid=~s/\_/\//g;
                   5630:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5631:     my $chome=homeserver($cnum,$cdomain);
                   5632:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5633: 	return 'error: no such course';
                   5634:     }
                   5635:     my $cstring='';
1.800     albertel 5636:     foreach my $pref (keys(%prefs)) {
                   5637: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5638:     }
1.84      www      5639:     $cstring=~s/\&$//;
                   5640:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5641: }
                   5642: 
                   5643: # ---------------------------------------------------------- Make/modify course
                   5644: 
                   5645: sub createcourse {
1.741     raeburn  5646:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5647:         $course_owner,$crstype)=@_;
1.84      www      5648:     $url=&declutter($url);
                   5649:     my $cid='';
1.264     matthew  5650:     unless (&allowed('ccc',$udom)) {
1.84      www      5651:         return 'refused';
                   5652:     }
                   5653: # ------------------------------------------------------------------- Create ID
1.674     www      5654:    my $uname=int(1+rand(9)).
                   5655:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5656:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5657:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5658: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5659:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5660:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5661:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5662:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5663:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5664:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5665:            return 'error: unable to generate unique course-ID';
                   5666:        } 
                   5667:    }
1.264     matthew  5668: # ------------------------------------------------ Check supplied server name
1.620     albertel 5669:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5670:     if (! &is_library($course_server)) {
1.264     matthew  5671:         return 'error:bad server name '.$course_server;
                   5672:     }
1.84      www      5673: # ------------------------------------------------------------- Make the course
                   5674:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5675:                       $course_server);
1.84      www      5676:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5677:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5678:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5679: 	return 'error: no such course';
                   5680:     }
1.271     www      5681: # ----------------------------------------------------------------- Course made
1.516     raeburn  5682: # log existence
1.918     raeburn  5683:     my $newcourse = {
                   5684:                     $udom.'_'.$uname => {
1.921     raeburn  5685:                                      description => $description,
                   5686:                                      inst_code   => $inst_code,
                   5687:                                      owner       => $course_owner,
                   5688:                                      type        => $crstype,
1.918     raeburn  5689:                                                 },
                   5690:                     };
1.921     raeburn  5691:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5692: # set toplevel url
1.271     www      5693:     my $topurl=$url;
                   5694:     unless ($nonstandard) {
                   5695: # ------------------------------------------ For standard courses, make top url
                   5696:         my $mapurl=&clutter($url);
1.278     www      5697:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5698:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5699: <map>
                   5700: <resource id="1" type="start"></resource>
                   5701: <resource id="2" src="$mapurl"></resource>
                   5702: <resource id="3" type="finish"></resource>
                   5703: <link index="1" from="1" to="2"></link>
                   5704: <link index="2" from="2" to="3"></link>
                   5705: </map>
                   5706: ENDINITMAP
                   5707:         $topurl=&declutter(
1.638     albertel 5708:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5709:                           );
                   5710:     }
                   5711: # ----------------------------------------------------------- Write preferences
1.84      www      5712:     &writecoursepref($udom.'_'.$uname,
                   5713:                      ('description' => $description,
1.271     www      5714:                       'url'         => $topurl));
1.84      www      5715:     return '/'.$udom.'/'.$uname;
                   5716: }
                   5717: 
1.813     albertel 5718: sub is_course {
                   5719:     my ($cdom,$cnum) = @_;
                   5720:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.918     raeburn  5721: 				undef,'.',undef,1);
1.813     albertel 5722:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5723:         return 1;
                   5724:     }
                   5725:     return 0;
                   5726: }
                   5727: 
1.21      www      5728: # ---------------------------------------------------------- Assign Custom Role
                   5729: 
                   5730: sub assigncustomrole {
1.357     www      5731:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5732:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5733:                        $end,$start,$deleteflag);
1.21      www      5734: }
                   5735: 
                   5736: # ----------------------------------------------------------------- Revoke Role
                   5737: 
                   5738: sub revokerole {
1.357     www      5739:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5740:     my $now=time;
1.357     www      5741:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5742: }
                   5743: 
                   5744: # ---------------------------------------------------------- Revoke Custom Role
                   5745: 
                   5746: sub revokecustomrole {
1.357     www      5747:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5748:     my $now=time;
1.357     www      5749:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5750:            $deleteflag);
1.17      www      5751: }
                   5752: 
1.533     banghart 5753: # ------------------------------------------------------------ Disk usage
1.535     albertel 5754: sub diskusage {
1.533     banghart 5755:     my ($udom,$uname,$directoryRoot)=@_;
                   5756:     $directoryRoot =~ s/\/$//;
1.535     albertel 5757:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5758:     return $listing;
1.512     banghart 5759: }
                   5760: 
1.566     banghart 5761: sub is_locked {
                   5762:     my ($file_name, $domain, $user) = @_;
                   5763:     my @check;
                   5764:     my $is_locked;
                   5765:     push @check, $file_name;
1.613     albertel 5766:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5767: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5768:     my ($tmp)=keys(%locked);
                   5769:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5770:     
1.566     banghart 5771:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5772:         $is_locked = 'false';
                   5773:         foreach my $entry (@{$locked{$file_name}}) {
                   5774:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5775:                $is_locked = 'true';
                   5776:                last;
1.745     raeburn  5777:            }
                   5778:        }
1.566     banghart 5779:     } else {
                   5780:         $is_locked = 'false';
                   5781:     }
                   5782: }
                   5783: 
1.759     albertel 5784: sub declutter_portfile {
                   5785:     my ($file) = @_;
1.833     albertel 5786:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5787:     return $file;
                   5788: }
                   5789: 
1.559     banghart 5790: # ------------------------------------------------------------- Mark as Read Only
                   5791: 
                   5792: sub mark_as_readonly {
                   5793:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5794:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5795:     my ($tmp)=keys(%current_permissions);
                   5796:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5797:     foreach my $file (@{$files}) {
1.759     albertel 5798: 	$file = &declutter_portfile($file);
1.561     banghart 5799:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5800:     }
1.613     albertel 5801:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5802:     return;
                   5803: }
                   5804: 
1.572     banghart 5805: # ------------------------------------------------------------Save Selected Files
                   5806: 
                   5807: sub save_selected_files {
                   5808:     my ($user, $path, @files) = @_;
                   5809:     my $filename = $user."savedfiles";
1.573     banghart 5810:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5811:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5812:     foreach my $file (@files) {
1.620     albertel 5813:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5814:     }
                   5815:     foreach my $file (@other_files) {
1.574     banghart 5816:         print (OUT $file."\n");
1.572     banghart 5817:     }
1.574     banghart 5818:     close (OUT);
1.572     banghart 5819:     return 'ok';
                   5820: }
                   5821: 
1.574     banghart 5822: sub clear_selected_files {
                   5823:     my ($user) = @_;
                   5824:     my $filename = $user."savedfiles";
                   5825:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5826:     print (OUT undef);
                   5827:     close (OUT);
                   5828:     return ("ok");    
                   5829: }
                   5830: 
1.572     banghart 5831: sub files_in_path {
                   5832:     my ($user, $path) = @_;
                   5833:     my $filename = $user."savedfiles";
                   5834:     my %return_files;
1.574     banghart 5835:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5836:     while (my $line_in = <IN>) {
1.574     banghart 5837:         chomp ($line_in);
                   5838:         my @paths_and_file = split (m!/!, $line_in);
                   5839:         my $file_part = pop (@paths_and_file);
                   5840:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5841:         $path_part.='/';
                   5842:         my $path_and_file = $path_part.$file_part;
                   5843:         if ($path_part eq $path) {
                   5844:             $return_files{$file_part}= 'selected';
                   5845:         }
                   5846:     }
1.574     banghart 5847:     close (IN);
                   5848:     return (\%return_files);
1.572     banghart 5849: }
                   5850: 
                   5851: # called in portfolio select mode, to show files selected NOT in current directory
                   5852: sub files_not_in_path {
                   5853:     my ($user, $path) = @_;
                   5854:     my $filename = $user."savedfiles";
                   5855:     my @return_files;
                   5856:     my $path_part;
1.800     albertel 5857:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5858:     while (my $line = <IN>) {
1.572     banghart 5859:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5860:         my @paths_and_file = split(m|/|, $line);
                   5861:         my $file_part = pop(@paths_and_file);
                   5862:         chomp($file_part);
                   5863:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5864:         $path_part .= '/';
                   5865:         my $path_and_file = $path_part.$file_part;
                   5866:         if ($path_part ne $path) {
1.800     albertel 5867:             push(@return_files, ($path_and_file));
1.572     banghart 5868:         }
                   5869:     }
1.800     albertel 5870:     close(OUT);
1.574     banghart 5871:     return (@return_files);
1.572     banghart 5872: }
                   5873: 
1.745     raeburn  5874: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5875: 
1.745     raeburn  5876: sub get_portfile_permissions {
                   5877:     my ($domain,$user) = @_;
1.613     albertel 5878:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5879:     my ($tmp)=keys(%current_permissions);
                   5880:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5881:     return \%current_permissions;
                   5882: }
                   5883: 
                   5884: #---------------------------------------------Get portfolio file access controls
                   5885: 
1.749     raeburn  5886: sub get_access_controls {
1.745     raeburn  5887:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5888:     my %access;
                   5889:     my $real_file = $file;
                   5890:     $file =~ s/\.meta$//;
1.745     raeburn  5891:     if (defined($file)) {
1.749     raeburn  5892:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5893:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5894:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5895:             }
                   5896:         }
1.745     raeburn  5897:     } else {
1.749     raeburn  5898:         foreach my $key (keys(%{$current_permissions})) {
                   5899:             if ($key =~ /\0accesscontrol$/) {
                   5900:                 if (defined($group)) {
                   5901:                     if ($key !~ m-^\Q$group\E/-) {
                   5902:                         next;
                   5903:                     }
                   5904:                 }
                   5905:                 my ($fullpath) = split(/\0/,$key);
                   5906:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5907:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5908:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5909:                     }
                   5910:                 }
                   5911:             }
                   5912:         }
                   5913:     }
                   5914:     return %access;
                   5915: }
                   5916: 
                   5917: sub modify_access_controls {
                   5918:     my ($file_name,$changes,$domain,$user)=@_;
                   5919:     my ($outcome,$deloutcome);
                   5920:     my %store_permissions;
                   5921:     my %new_values;
                   5922:     my %new_control;
                   5923:     my %translation;
                   5924:     my @deletions = ();
                   5925:     my $now = time;
                   5926:     if (exists($$changes{'activate'})) {
                   5927:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5928:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5929:             my $numnew = scalar(@newitems);
                   5930:             for (my $i=0; $i<$numnew; $i++) {
                   5931:                 my $newkey = $newitems[$i];
                   5932:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5933:                 if ($newkey =~ /^\d+:/) { 
                   5934:                     $newkey =~ s/^(\d+)/$newid/;
                   5935:                     $translation{$1} = $newid;
                   5936:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5937:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5938:                     $translation{$1} = $newid;
                   5939:                 }
1.749     raeburn  5940:                 $new_values{$file_name."\0".$newkey} = 
                   5941:                                           $$changes{'activate'}{$newitems[$i]};
                   5942:                 $new_control{$newkey} = $now;
                   5943:             }
                   5944:         }
                   5945:     }
                   5946:     my %todelete;
                   5947:     my %changed_items;
                   5948:     foreach my $action ('delete','update') {
                   5949:         if (exists($$changes{$action})) {
                   5950:             if (ref($$changes{$action}) eq 'HASH') {
                   5951:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5952:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5953:                     if ($action eq 'delete') { 
                   5954:                         $todelete{$itemnum} = 1;
                   5955:                     } else {
                   5956:                         $changed_items{$itemnum} = $key;
                   5957:                     }
                   5958:                 }
1.745     raeburn  5959:             }
                   5960:         }
1.749     raeburn  5961:     }
                   5962:     # get lock on access controls for file.
                   5963:     my $lockhash = {
                   5964:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5965:                                                        ':'.$env{'user.domain'},
                   5966:                    }; 
                   5967:     my $tries = 0;
                   5968:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5969:    
                   5970:     while (($gotlock ne 'ok') && $tries <3) {
                   5971:         $tries ++;
                   5972:         sleep 1;
                   5973:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5974:     }
                   5975:     if ($gotlock eq 'ok') {
                   5976:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5977:         my ($tmp)=keys(%curr_permissions);
                   5978:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5979:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5980:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5981:             if (ref($curr_controls) eq 'HASH') {
                   5982:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5983:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5984:                     if (defined($todelete{$itemnum})) {
                   5985:                         push(@deletions,$file_name."\0".$control_item);
                   5986:                     } else {
                   5987:                         if (defined($changed_items{$itemnum})) {
                   5988:                             $new_control{$changed_items{$itemnum}} = $now;
                   5989:                             push(@deletions,$file_name."\0".$control_item);
                   5990:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5991:                         } else {
                   5992:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5993:                         }
                   5994:                     }
1.745     raeburn  5995:                 }
                   5996:             }
                   5997:         }
1.749     raeburn  5998:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5999:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6000:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6001:         #  remove lock
                   6002:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6003:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6004:         my ($file,$group);
                   6005:         if (&is_course($domain,$user)) {
                   6006:             ($group,$file) = split(/\//,$file_name,2);
                   6007:         } else {
                   6008:             $file = $file_name;
                   6009:         }
                   6010:         my $sqlresult =
                   6011:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6012:                                     $group);
1.749     raeburn  6013:     } else {
                   6014:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6015:     }
1.749     raeburn  6016:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6017: }
                   6018: 
1.827     raeburn  6019: sub make_public_indefinitely {
                   6020:     my ($requrl) = @_;
                   6021:     my $now = time;
                   6022:     my $action = 'activate';
                   6023:     my $aclnum = 0;
                   6024:     if (&is_portfolio_url($requrl)) {
                   6025:         my (undef,$udom,$unum,$file_name,$group) =
                   6026:             &parse_portfolio_url($requrl);
                   6027:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6028:         my %access_controls = &get_access_controls($current_perms,
                   6029:                                                    $group,$file_name);
                   6030:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6031:             my ($num,$scope,$end,$start) = 
                   6032:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6033:             if ($scope eq 'public') {
                   6034:                 if ($start <= $now && $end == 0) {
                   6035:                     $action = 'none';
                   6036:                 } else {
                   6037:                     $action = 'update';
                   6038:                     $aclnum = $num;
                   6039:                 }
                   6040:                 last;
                   6041:             }
                   6042:         }
                   6043:         if ($action eq 'none') {
                   6044:              return 'ok';
                   6045:         } else {
                   6046:             my %changes;
                   6047:             my $newend = 0;
                   6048:             my $newstart = $now;
                   6049:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6050:             $changes{$action}{$newkey} = {
                   6051:                 type => 'public',
                   6052:                 time => {
                   6053:                     start => $newstart,
                   6054:                     end   => $newend,
                   6055:                 },
                   6056:             };
                   6057:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6058:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6059:             return $outcome;
                   6060:         }
                   6061:     } else {
                   6062:         return 'invalid';
                   6063:     }
                   6064: }
                   6065: 
1.745     raeburn  6066: #------------------------------------------------------Get Marked as Read Only
                   6067: 
                   6068: sub get_marked_as_readonly {
                   6069:     my ($domain,$user,$what,$group) = @_;
                   6070:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6071:     my @readonly_files;
1.629     banghart 6072:     my $cmp1=$what;
                   6073:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6074:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6075:         if (defined($group)) {
                   6076:             if ($file_name !~ m-^\Q$group\E/-) {
                   6077:                 next;
                   6078:             }
                   6079:         }
1.561     banghart 6080:         if (ref($value) eq "ARRAY"){
                   6081:             foreach my $stored_what (@{$value}) {
1.629     banghart 6082:                 my $cmp2=$stored_what;
1.759     albertel 6083:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6084:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6085:                 }
1.629     banghart 6086:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6087:                     push(@readonly_files, $file_name);
1.745     raeburn  6088:                     last;
1.563     banghart 6089:                 } elsif (!defined($what)) {
                   6090:                     push(@readonly_files, $file_name);
1.745     raeburn  6091:                     last;
1.561     banghart 6092:                 }
                   6093:             }
1.745     raeburn  6094:         }
1.561     banghart 6095:     }
                   6096:     return @readonly_files;
                   6097: }
1.577     banghart 6098: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6099: 
1.577     banghart 6100: sub get_marked_as_readonly_hash {
1.745     raeburn  6101:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6102:     my %readonly_files;
1.745     raeburn  6103:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6104:         if (defined($group)) {
                   6105:             if ($file_name !~ m-^\Q$group\E/-) {
                   6106:                 next;
                   6107:             }
                   6108:         }
1.577     banghart 6109:         if (ref($value) eq "ARRAY"){
                   6110:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6111:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6112:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6113:                         if ($lock_descriptor eq 'graded') {
                   6114:                             $readonly_files{$file_name} = 'graded';
                   6115:                         } elsif ($lock_descriptor eq 'handback') {
                   6116:                             $readonly_files{$file_name} = 'handback';
                   6117:                         } else {
                   6118:                             if (!exists($readonly_files{$file_name})) {
                   6119:                                 $readonly_files{$file_name} = 'locked';
                   6120:                             }
                   6121:                         }
1.745     raeburn  6122:                     }
1.750     banghart 6123:                 } 
1.577     banghart 6124:             }
                   6125:         } 
                   6126:     }
                   6127:     return %readonly_files;
                   6128: }
1.559     banghart 6129: # ------------------------------------------------------------ Unmark as Read Only
                   6130: 
                   6131: sub unmark_as_readonly {
1.629     banghart 6132:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6133:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6134:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6135:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6136:     my $symb_crs = $what;
                   6137:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6138:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6139:     my ($tmp)=keys(%current_permissions);
                   6140:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6141:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6142:     foreach my $file (@readonly_files) {
1.759     albertel 6143: 	my $clean_file = &declutter_portfile($file);
                   6144: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6145: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6146:         my @new_locks;
                   6147:         my @del_keys;
                   6148:         if (ref($current_locks) eq "ARRAY"){
                   6149:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6150:                 my $compare=$locker;
1.749     raeburn  6151:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6152:                     $compare=join('',@{$locker});
1.746     raeburn  6153:                     if ($compare ne $symb_crs) {
                   6154:                         push(@new_locks, $locker);
                   6155:                     }
1.563     banghart 6156:                 }
                   6157:             }
1.650     albertel 6158:             if (scalar(@new_locks) > 0) {
1.563     banghart 6159:                 $current_permissions{$file} = \@new_locks;
                   6160:             } else {
                   6161:                 push(@del_keys, $file);
1.613     albertel 6162:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6163:                 delete($current_permissions{$file});
1.563     banghart 6164:             }
                   6165:         }
1.561     banghart 6166:     }
1.613     albertel 6167:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6168:     return;
                   6169: }
1.512     banghart 6170: 
1.17      www      6171: # ------------------------------------------------------------ Directory lister
                   6172: 
                   6173: sub dirlist {
1.253     stredwic 6174:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   6175: 
1.18      www      6176:     $uri=~s/^\///;
                   6177:     $uri=~s/\/$//;
1.253     stredwic 6178:     my ($udom, $uname);
                   6179:     (undef,$udom,$uname)=split(/\//,$uri);
                   6180:     if(defined($userdomain)) {
                   6181:         $udom = $userdomain;
                   6182:     }
                   6183:     if(defined($username)) {
                   6184:         $uname = $username;
                   6185:     }
                   6186: 
                   6187:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6188:     if(defined($alternateDirectoryRoot)) {
                   6189:         $dirRoot = $alternateDirectoryRoot;
                   6190:         $dirRoot =~ s/\/$//;
1.751     banghart 6191:     }
1.253     stredwic 6192: 
                   6193:     if($udom) {
                   6194:         if($uname) {
1.800     albertel 6195:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6196: 				 &homeserver($uname,$udom));
1.605     matthew  6197:             my @listing_results;
                   6198:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6199:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6200: 				  &homeserver($uname,$udom));
1.605     matthew  6201:                 @listing_results = split(/:/,$listing);
                   6202:             } else {
                   6203:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6204:             }
                   6205:             return @listing_results;
1.253     stredwic 6206:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6207:             my %allusers;
1.841     albertel 6208: 	    my %servers = &get_servers($udom,'library');
                   6209: 	    foreach my $tryserver (keys(%servers)) {
                   6210: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6211: 				     $udom, $tryserver);
                   6212: 		my @listing_results;
                   6213: 		if ($listing eq 'unknown_cmd') {
                   6214: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6215: 				      $udom, $tryserver);
                   6216: 		    @listing_results = split(/:/,$listing);
                   6217: 		} else {
                   6218: 		    @listing_results =
                   6219: 			map { &unescape($_); } split(/:/,$listing);
                   6220: 		}
                   6221: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6222: 		    $listing_results[0] ne 'empty'       &&
                   6223: 		    $listing_results[0] ne 'con_lost') {
                   6224: 		    foreach my $line (@listing_results) {
                   6225: 			my ($entry) = split(/&/,$line,2);
                   6226: 			$allusers{$entry} = 1;
                   6227: 		    }
                   6228: 		}
1.253     stredwic 6229:             }
                   6230:             my $alluserstr='';
1.800     albertel 6231:             foreach my $user (sort(keys(%allusers))) {
                   6232:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6233:             }
                   6234:             $alluserstr=~s/:$//;
                   6235:             return split(/:/,$alluserstr);
                   6236:         } else {
1.800     albertel 6237:             return ('missing user name');
1.253     stredwic 6238:         }
                   6239:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6240:         my @all_domains = sort(&all_domains());
                   6241:          foreach my $domain (@all_domains) {
                   6242:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6243:          }
                   6244:          return @all_domains;
                   6245:      } else {
1.800     albertel 6246:         return ('missing domain');
1.275     stredwic 6247:     }
                   6248: }
                   6249: 
                   6250: # --------------------------------------------- GetFileTimestamp
                   6251: # This function utilizes dirlist and returns the date stamp for
                   6252: # when it was last modified.  It will also return an error of -1
                   6253: # if an error occurs
                   6254: 
1.410     matthew  6255: ##
                   6256: ## FIXME: This subroutine assumes its caller knows something about the
                   6257: ## directory structure of the home server for the student ($root).
                   6258: ## Not a good assumption to make.  Since this is for looking up files
                   6259: ## in user directories, the full path should be constructed by lond, not
                   6260: ## whatever machine we request data from.
                   6261: ##
1.275     stredwic 6262: sub GetFileTimestamp {
                   6263:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6264:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6265:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6266:     my $subdir=$studentName.'__';
                   6267:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6268:     my $proname="$studentDomain/$subdir/$studentName";
                   6269:     $proname .= '/'.$filename;
1.375     matthew  6270:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6271:                                               $studentName, $root);
1.275     stredwic 6272:     my @stats = split('&', $fileStat);
                   6273:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6274:         # @stats contains first the filename, then the stat output
                   6275:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6276:     } else {
                   6277:         return -1;
1.253     stredwic 6278:     }
1.26      www      6279: }
                   6280: 
1.712     albertel 6281: sub stat_file {
                   6282:     my ($uri) = @_;
1.787     albertel 6283:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6284: 
1.712     albertel 6285:     my ($udom,$uname,$file,$dir);
                   6286:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6287: 	($udom,$uname,$file) =
1.811     albertel 6288: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6289: 	$file = 'userfiles/'.$file;
1.740     www      6290: 	$dir = &propath($udom,$uname);
1.712     albertel 6291:     }
                   6292:     if ($uri =~ m-^/res/-) {
                   6293: 	($udom,$uname) = 
1.807     albertel 6294: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6295: 	$file = $uri;
                   6296:     }
                   6297: 
                   6298:     if (!$udom || !$uname || !$file) {
                   6299: 	# unable to handle the uri
                   6300: 	return ();
                   6301:     }
                   6302: 
                   6303:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6304:     my @stats = split('&', $result);
1.721     banghart 6305:     
1.712     albertel 6306:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6307: 	shift(@stats); #filename is first
                   6308: 	return @stats;
                   6309:     }
                   6310:     return ();
                   6311: }
                   6312: 
1.26      www      6313: # -------------------------------------------------------- Value of a Condition
                   6314: 
1.713     albertel 6315: # gets the value of a specific preevaluated condition
                   6316: #    stored in the string  $env{user.state.<cid>}
                   6317: # or looks up a condition reference in the bighash and if if hasn't
                   6318: # already been evaluated recurses into docondval to get the value of
                   6319: # the condition, then memoizing it to 
                   6320: #   $env{user.state.<cid>.<condition>}
1.40      www      6321: sub directcondval {
                   6322:     my $number=shift;
1.620     albertel 6323:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6324: 	&Apache::lonuserstate::evalstate();
                   6325:     }
1.713     albertel 6326:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6327: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6328:     } elsif ($number =~ /^_/) {
                   6329: 	my $sub_condition;
                   6330: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6331: 		&GDBM_READER(),0640)) {
                   6332: 	    $sub_condition=$bighash{'conditions'.$number};
                   6333: 	    untie(%bighash);
                   6334: 	}
                   6335: 	my $value = &docondval($sub_condition);
                   6336: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6337: 	return $value;
                   6338:     }
1.620     albertel 6339:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6340:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6341:     } else {
                   6342:        return 2;
                   6343:     }
                   6344: }
                   6345: 
1.713     albertel 6346: # get the collection of conditions for this resource
1.26      www      6347: sub condval {
                   6348:     my $condidx=shift;
1.54      www      6349:     my $allpathcond='';
1.713     albertel 6350:     foreach my $cond (split(/\|/,$condidx)) {
                   6351: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6352: 	    $allpathcond.=
                   6353: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6354: 	}
1.191     harris41 6355:     }
1.54      www      6356:     $allpathcond=~s/\|$//;
1.713     albertel 6357:     return &docondval($allpathcond);
                   6358: }
                   6359: 
                   6360: #evaluates an expression of conditions
                   6361: sub docondval {
                   6362:     my ($allpathcond) = @_;
                   6363:     my $result=0;
                   6364:     if ($env{'request.course.id'}
                   6365: 	&& defined($allpathcond)) {
                   6366: 	my $operand='|';
                   6367: 	my @stack;
                   6368: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6369: 	    if ($chunk eq '(') {
                   6370: 		push @stack,($operand,$result);
                   6371: 	    } elsif ($chunk eq ')') {
                   6372: 		my $before=pop @stack;
                   6373: 		if (pop @stack eq '&') {
                   6374: 		    $result=$result>$before?$before:$result;
                   6375: 		} else {
                   6376: 		    $result=$result>$before?$result:$before;
                   6377: 		}
                   6378: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6379: 		$operand=$chunk;
                   6380: 	    } else {
                   6381: 		my $new=directcondval($chunk);
                   6382: 		if ($operand eq '&') {
                   6383: 		    $result=$result>$new?$new:$result;
                   6384: 		} else {
                   6385: 		    $result=$result>$new?$result:$new;
                   6386: 		}
                   6387: 	    }
                   6388: 	}
1.26      www      6389:     }
                   6390:     return $result;
1.421     albertel 6391: }
                   6392: 
                   6393: # ---------------------------------------------------- Devalidate courseresdata
                   6394: 
                   6395: sub devalidatecourseresdata {
                   6396:     my ($coursenum,$coursedomain)=@_;
                   6397:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6398:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6399: }
                   6400: 
1.763     www      6401: 
1.200     www      6402: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6403: #
                   6404: #  Parameters:
                   6405: #      $coursenum    - Number of the course.
                   6406: #      $coursedomain - Domain at which the course was created.
                   6407: #  Returns:
                   6408: #     A hash of the course parameters along (I think) with timestamps
                   6409: #     and version info.
1.877     foxr     6410: 
1.624     albertel 6411: sub get_courseresdata {
                   6412:     my ($coursenum,$coursedomain)=@_;
1.200     www      6413:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6414:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6415:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6416:     my %dumpreply;
1.417     albertel 6417:     unless (defined($cached)) {
1.624     albertel 6418: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6419: 	$result=\%dumpreply;
1.251     albertel 6420: 	my ($tmp) = keys(%dumpreply);
                   6421: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6422: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6423: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6424: 	    return $tmp;
1.416     albertel 6425: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6426: 	    $result=undef;
1.599     albertel 6427: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6428: 	}
                   6429:     }
1.624     albertel 6430:     return $result;
                   6431: }
                   6432: 
1.633     albertel 6433: sub devalidateuserresdata {
                   6434:     my ($uname,$udom)=@_;
                   6435:     my $hashid="$udom:$uname";
                   6436:     &devalidate_cache_new('userres',$hashid);
                   6437: }
                   6438: 
1.624     albertel 6439: sub get_userresdata {
                   6440:     my ($uname,$udom)=@_;
                   6441:     #most student don\'t have any data set, check if there is some data
                   6442:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6443: 
                   6444:     my $hashid="$udom:$uname";
                   6445:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6446:     if (!defined($cached)) {
                   6447: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6448: 	$result=\%resourcedata;
                   6449: 	&do_cache_new('userres',$hashid,$result,600);
                   6450:     }
                   6451:     my ($tmp)=keys(%$result);
                   6452:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6453: 	return $result;
                   6454:     }
                   6455:     #error 2 occurs when the .db doesn't exist
                   6456:     if ($tmp!~/error: 2 /) {
1.672     albertel 6457: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6458: 		 " Trying to get resource data for ".
                   6459: 		 $uname." at ".$udom.": ".
                   6460: 		 $tmp."</font>");
                   6461:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6462: 	#&EXT_cache_set($udom,$uname);
                   6463: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6464: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6465:     }
                   6466:     return $tmp;
                   6467: }
1.879     foxr     6468: #----------------------------------------------- resdata - return resource data
                   6469: #  Purpose:
                   6470: #    Return resource data for either users or for a course.
                   6471: #  Parameters:
                   6472: #     $name      - Course/user name.
                   6473: #     $domain    - Name of the domain the user/course is registered on.
                   6474: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6475: #     @which     - Array of names of resources desired.
                   6476: #  Returns:
                   6477: #     The value of the first reasource in @which that is found in the
                   6478: #     resource hash.
                   6479: #  Exceptional Conditions:
                   6480: #     If the $type passed in is not valid (not the string 'course' or 
                   6481: #     'user', an undefined  reference is returned.
                   6482: #     If none of the resources are found, an undef is returned
1.624     albertel 6483: sub resdata {
                   6484:     my ($name,$domain,$type,@which)=@_;
                   6485:     my $result;
                   6486:     if ($type eq 'course') {
                   6487: 	$result=&get_courseresdata($name,$domain);
                   6488:     } elsif ($type eq 'user') {
                   6489: 	$result=&get_userresdata($name,$domain);
                   6490:     }
                   6491:     if (!ref($result)) { return $result; }    
1.251     albertel 6492:     foreach my $item (@which) {
1.927     albertel 6493: 	if (defined($result->{$item->[0]})) {
                   6494: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6495: 	}
1.250     albertel 6496:     }
1.291     albertel 6497:     return undef;
1.200     www      6498: }
                   6499: 
1.379     matthew  6500: #
                   6501: # EXT resource caching routines
                   6502: #
                   6503: 
                   6504: sub clear_EXT_cache_status {
1.383     albertel 6505:     &delenv('cache.EXT.');
1.379     matthew  6506: }
                   6507: 
                   6508: sub EXT_cache_status {
                   6509:     my ($target_domain,$target_user) = @_;
1.383     albertel 6510:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6511:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6512:         # We know already the user has no data
                   6513:         return 1;
                   6514:     } else {
                   6515:         return 0;
                   6516:     }
                   6517: }
                   6518: 
                   6519: sub EXT_cache_set {
                   6520:     my ($target_domain,$target_user) = @_;
1.383     albertel 6521:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6522:     #&appenv($cachename => time);
1.379     matthew  6523: }
                   6524: 
1.28      www      6525: # --------------------------------------------------------- Value of a Variable
1.58      www      6526: sub EXT {
1.715     albertel 6527: 
1.395     albertel 6528:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6529:     unless ($varname) { return ''; }
1.218     albertel 6530:     #get real user name/domain, courseid and symb
                   6531:     my $courseid;
1.359     albertel 6532:     my $publicuser;
1.427     www      6533:     if ($symbparm) {
                   6534: 	$symbparm=&get_symb_from_alias($symbparm);
                   6535:     }
1.218     albertel 6536:     if (!($uname && $udom)) {
1.790     albertel 6537:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6538:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6539:     } else {
1.620     albertel 6540: 	$courseid=$env{'request.course.id'};
1.218     albertel 6541:     }
1.48      www      6542:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6543:     my $rest;
1.320     albertel 6544:     if (defined($therest[0])) {
1.48      www      6545:        $rest=join('.',@therest);
                   6546:     } else {
                   6547:        $rest='';
                   6548:     }
1.320     albertel 6549: 
1.57      www      6550:     my $qualifierrest=$qualifier;
                   6551:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6552:     my $spacequalifierrest=$space;
                   6553:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6554:     if ($realm eq 'user') {
1.48      www      6555: # --------------------------------------------------------------- user.resource
                   6556: 	if ($space eq 'resource') {
1.651     albertel 6557: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6558: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6559: 		 &&
1.744     albertel 6560: 		 ($symbparm eq &symbread()) ) {	
                   6561: 		# if we are in the middle of processing the resource the
                   6562: 		# get the value we are planning on committing
                   6563:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6564:                     return $Apache::lonhomework::results{$qualifierrest};
                   6565:                 } else {
                   6566:                     return $Apache::lonhomework::history{$qualifierrest};
                   6567:                 }
1.335     albertel 6568: 	    } else {
1.359     albertel 6569: 		my %restored;
1.620     albertel 6570: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6571: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6572: 		} else {
                   6573: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6574: 		}
1.335     albertel 6575: 		return $restored{$qualifierrest};
                   6576: 	    }
1.48      www      6577: # ----------------------------------------------------------------- user.access
                   6578:         } elsif ($space eq 'access') {
1.218     albertel 6579: 	    # FIXME - not supporting calls for a specific user
1.48      www      6580:             return &allowed($qualifier,$rest);
                   6581: # ------------------------------------------ user.preferences, user.environment
                   6582:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6583: 	    if (($uname eq $env{'user.name'}) &&
                   6584: 		($udom eq $env{'user.domain'})) {
                   6585: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6586: 	    } else {
1.359     albertel 6587: 		my %returnhash;
                   6588: 		if (!$publicuser) {
                   6589: 		    %returnhash=&userenvironment($udom,$uname,
                   6590: 						 $qualifierrest);
                   6591: 		}
1.218     albertel 6592: 		return $returnhash{$qualifierrest};
                   6593: 	    }
1.48      www      6594: # ----------------------------------------------------------------- user.course
                   6595:         } elsif ($space eq 'course') {
1.218     albertel 6596: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6597:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6598: # ------------------------------------------------------------------- user.role
                   6599:         } elsif ($space eq 'role') {
1.218     albertel 6600: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6601:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6602:             if ($qualifier eq 'value') {
                   6603: 		return $role;
                   6604:             } elsif ($qualifier eq 'extent') {
                   6605:                 return $where;
                   6606:             }
                   6607: # ----------------------------------------------------------------- user.domain
                   6608:         } elsif ($space eq 'domain') {
1.218     albertel 6609:             return $udom;
1.48      www      6610: # ------------------------------------------------------------------- user.name
                   6611:         } elsif ($space eq 'name') {
1.218     albertel 6612:             return $uname;
1.48      www      6613: # ---------------------------------------------------- Any other user namespace
1.29      www      6614:         } else {
1.359     albertel 6615: 	    my %reply;
                   6616: 	    if (!$publicuser) {
                   6617: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6618: 	    }
                   6619: 	    return $reply{$qualifierrest};
1.48      www      6620:         }
1.236     www      6621:     } elsif ($realm eq 'query') {
                   6622: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6623:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6624: 						[$spacequalifierrest]);
1.620     albertel 6625: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6626:    } elsif ($realm eq 'request') {
1.48      www      6627: # ------------------------------------------------------------- request.browser
                   6628:         if ($space eq 'browser') {
1.430     www      6629: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6630: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6631: 		    return 1;
                   6632: 		} else {
                   6633: 		    return 0;
                   6634: 		}
                   6635: 	    } else {
1.620     albertel 6636: 		return $env{'browser.'.$qualifier};
1.430     www      6637: 	    }
1.57      www      6638: # ------------------------------------------------------------ request.filename
                   6639:         } else {
1.620     albertel 6640:             return $env{'request.'.$spacequalifierrest};
1.29      www      6641:         }
1.28      www      6642:     } elsif ($realm eq 'course') {
1.48      www      6643: # ---------------------------------------------------------- course.description
1.620     albertel 6644:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6645:     } elsif ($realm eq 'resource') {
1.165     www      6646: 
1.620     albertel 6647: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6648: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6649: 	}
1.693     albertel 6650: 
                   6651: 	if ($space eq 'title') {
                   6652: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6653: 	    return &gettitle($symbparm);
                   6654: 	}
                   6655: 	
                   6656: 	if ($space eq 'map') {
                   6657: 	    my ($map) = &decode_symb($symbparm);
                   6658: 	    return &symbread($map);
                   6659: 	}
1.905     albertel 6660: 	if ($space eq 'filename') {
                   6661: 	    if ($symbparm) {
                   6662: 		return &clutter((&decode_symb($symbparm))[2]);
                   6663: 	    }
                   6664: 	    return &hreflocation('',$env{'request.filename'});
                   6665: 	}
1.693     albertel 6666: 
                   6667: 	my ($section, $group, @groups);
1.593     albertel 6668: 	my ($courselevelm,$courselevel);
1.539     albertel 6669: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6670: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6671: 
1.218     albertel 6672: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6673: 
1.60      www      6674: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6675: 	    my $symbp=$symbparm;
1.735     albertel 6676: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6677: 
                   6678: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6679: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6680: 
1.620     albertel 6681: 	    if (($env{'user.name'} eq $uname) &&
                   6682: 		($env{'user.domain'} eq $udom)) {
                   6683: 		$section=$env{'request.course.sec'};
1.733     raeburn  6684:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6685:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6686: 	    } else {
1.539     albertel 6687: 		if (! defined($usection)) {
1.551     albertel 6688: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6689: 		} else {
                   6690: 		    $section = $usection;
                   6691: 		}
1.733     raeburn  6692:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6693: 	    }
                   6694: 
                   6695: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6696: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6697: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6698: 
1.593     albertel 6699: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6700: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6701: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6702: 
1.60      www      6703: # ----------------------------------------------------------- first, check user
1.624     albertel 6704: 
                   6705: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6706: 				       ([$courselevelr,'resource'],
                   6707: 					[$courselevelm,'map'     ],
                   6708: 					[$courselevel, 'course'  ]));
1.931     albertel 6709: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6710: 
1.594     albertel 6711: # ------------------------------------------------ second, check some of course
1.684     raeburn  6712:             my $coursereply;
1.691     raeburn  6713:             if (@groups > 0) {
                   6714:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6715:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6716:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6717:             }
1.96      www      6718: 
1.684     raeburn  6719: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6720: 				  $env{'course.'.$courseid.'.domain'},
                   6721: 				  'course',
                   6722: 				  ([$seclevelr,   'resource'],
                   6723: 				   [$seclevelm,   'map'     ],
                   6724: 				   [$seclevel,    'course'  ],
                   6725: 				   [$courselevelr,'resource']));
                   6726: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6727: 
1.60      www      6728: # ------------------------------------------------------ third, check map parms
1.218     albertel 6729: 	    my %parmhash=();
                   6730: 	    my $thisparm='';
                   6731: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6732: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6733: 		    &GDBM_READER(),0640)) {
1.218     albertel 6734: 		$thisparm=$parmhash{$symbparm};
                   6735: 		untie(%parmhash);
                   6736: 	    }
1.927     albertel 6737: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6738: 	}
1.594     albertel 6739: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6740: 
1.218     albertel 6741: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6742: 	my $filename;
                   6743: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6744: 	if ($symbparm) {
1.409     www      6745: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6746: 	} else {
1.620     albertel 6747: 	    $filename=$env{'request.filename'};
1.282     albertel 6748: 	}
                   6749: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6750: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6751: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6752: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6753: 
1.927     albertel 6754: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6755: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6756: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6757: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6758: 				     $env{'course.'.$courseid.'.domain'},
                   6759: 				     'course',
1.927     albertel 6760: 				     ([$courselevelm,'map'   ],
                   6761: 				      [$courselevel, 'course']));
                   6762: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6763: 	}
1.145     www      6764: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6765: 	unless ($space eq '0') {
1.336     albertel 6766: 	    my @parts=split(/_/,$space);
                   6767: 	    my $id=pop(@parts);
                   6768: 	    my $part=join('_',@parts);
                   6769: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6770: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6771: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6772: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6773: 	}
1.395     albertel 6774: 	if ($recurse) { return undef; }
                   6775: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6776: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6777: # ---------------------------------------------------- Any other user namespace
                   6778:     } elsif ($realm eq 'environment') {
                   6779: # ----------------------------------------------------------------- environment
1.620     albertel 6780: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6781: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6782: 	} else {
1.770     albertel 6783: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6784: 		return '';
                   6785: 	    }
1.219     albertel 6786: 	    my %returnhash=&userenvironment($udom,$uname,
                   6787: 					    $spacequalifierrest);
                   6788: 	    return $returnhash{$spacequalifierrest};
                   6789: 	}
1.28      www      6790:     } elsif ($realm eq 'system') {
1.48      www      6791: # ----------------------------------------------------------------- system.time
                   6792: 	if ($space eq 'time') {
                   6793: 	    return time;
                   6794:         }
1.696     albertel 6795:     } elsif ($realm eq 'server') {
                   6796: # ----------------------------------------------------------------- system.time
                   6797: 	if ($space eq 'name') {
                   6798: 	    return $ENV{'SERVER_NAME'};
                   6799:         }
1.28      www      6800:     }
1.48      www      6801:     return '';
1.61      www      6802: }
                   6803: 
1.927     albertel 6804: sub get_reply {
                   6805:     my ($reply_value) = @_;
1.940     raeburn  6806:     if (ref($reply_value) eq 'ARRAY') {
                   6807:         if (wantarray) {
                   6808: 	    return @$reply_value;
                   6809:         }
                   6810:         return $reply_value->[0];
                   6811:     } else {
                   6812:         return $reply_value;
1.927     albertel 6813:     }
                   6814: }
                   6815: 
1.691     raeburn  6816: sub check_group_parms {
                   6817:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6818:     my @groupitems = ();
                   6819:     my $resultitem;
1.927     albertel 6820:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6821:     foreach my $group (@{$groups}) {
                   6822:         foreach my $level (@levels) {
1.927     albertel 6823:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6824:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6825:         }
                   6826:     }
                   6827:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6828:                             $env{'course.'.$courseid.'.domain'},
                   6829:                                      'course',@groupitems);
                   6830:     return $coursereply;
                   6831: }
                   6832: 
                   6833: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6834:     my ($courseid,@groups) = @_;
                   6835:     @groups = sort(@groups);
1.691     raeburn  6836:     return @groups;
                   6837: }
                   6838: 
1.395     albertel 6839: sub packages_tab_default {
                   6840:     my ($uri,$varname)=@_;
                   6841:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6842: 
                   6843:     my (@extension,@specifics,$do_default);
                   6844:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6845: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6846: 	if ($pack_type eq 'default') {
                   6847: 	    $do_default=1;
                   6848: 	} elsif ($pack_type eq 'extension') {
                   6849: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6850: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6851: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6852: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6853: 	}
                   6854:     }
                   6855:     # first look for a package that matches the requested part id
                   6856:     foreach my $package (@specifics) {
                   6857: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6858: 	next if ($pack_part ne $part);
                   6859: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6860: 	    return $packagetab{"$pack_type&$name&default"};
                   6861: 	}
                   6862:     }
                   6863:     # look for any possible matching non extension_ package
                   6864:     foreach my $package (@specifics) {
                   6865: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6866: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6867: 	    return $packagetab{"$pack_type&$name&default"};
                   6868: 	}
1.585     albertel 6869: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6870: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6871: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6872: 	}
                   6873:     }
1.738     albertel 6874:     # look for any posible extension_ match
                   6875:     foreach my $package (@extension) {
                   6876: 	my ($package,$pack_type)=@{$package};
                   6877: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6878: 	    return $packagetab{"$pack_type&$name&default"};
                   6879: 	}
                   6880: 	if (defined($packagetab{$package."&$name&default"})) {
                   6881: 	    return $packagetab{$package."&$name&default"};
                   6882: 	}
                   6883:     }
                   6884:     # look for a global default setting
                   6885:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6886: 	return $packagetab{"default&$name&default"};
                   6887:     }
1.395     albertel 6888:     return undef;
                   6889: }
                   6890: 
1.334     albertel 6891: sub add_prefix_and_part {
                   6892:     my ($prefix,$part)=@_;
                   6893:     my $keyroot;
                   6894:     if (defined($prefix) && $prefix !~ /^__/) {
                   6895: 	# prefix that has a part already
                   6896: 	$keyroot=$prefix;
                   6897:     } elsif (defined($prefix)) {
                   6898: 	# prefix that is missing a part
                   6899: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6900:     } else {
                   6901: 	# no prefix at all
                   6902: 	if (defined($part)) { $keyroot='_'.$part; }
                   6903:     }
                   6904:     return $keyroot;
                   6905: }
                   6906: 
1.71      www      6907: # ---------------------------------------------------------------- Get metadata
                   6908: 
1.599     albertel 6909: my %metaentry;
1.71      www      6910: sub metadata {
1.176     www      6911:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6912:     $uri=&declutter($uri);
1.288     albertel 6913:     # if it is a non metadata possible uri return quickly
1.529     albertel 6914:     if (($uri eq '') || 
                   6915: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6916: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 6917:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   6918: 	return undef;
                   6919:     }
                   6920:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   6921: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 6922: 	return undef;
1.288     albertel 6923:     }
1.73      www      6924:     my $filename=$uri;
                   6925:     $uri=~s/\.meta$//;
1.172     www      6926: #
                   6927: # Is the metadata already cached?
1.177     www      6928: # Look at timestamp of caching
1.172     www      6929: # Everything is cached by the main uri, libraries are never directly cached
                   6930: #
1.428     albertel 6931:     if (!defined($liburi)) {
1.599     albertel 6932: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6933: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6934:     }
                   6935:     {
1.172     www      6936: #
                   6937: # Is this a recursive call for a library?
                   6938: #
1.599     albertel 6939: #	if (! exists($metacache{$uri})) {
                   6940: #	    $metacache{$uri}={};
                   6941: #	}
1.924     albertel 6942: 	my $cachetime = 60*60;
1.171     www      6943:         if ($liburi) {
                   6944: 	    $liburi=&declutter($liburi);
                   6945:             $filename=$liburi;
1.401     bowersj2 6946:         } else {
1.599     albertel 6947: 	    &devalidate_cache_new('meta',$uri);
                   6948: 	    undef(%metaentry);
1.401     bowersj2 6949: 	}
1.140     www      6950:         my %metathesekeys=();
1.73      www      6951:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6952: 	my $metastring;
1.924     albertel 6953: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 6954: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 6955: 	    $metastring = 
1.929     albertel 6956: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 6957: 					  ('grade_target' => 'meta'));
                   6958: 	    $cachetime = 1; # only want this cached in the child not long term
                   6959: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 6960: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6961: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6962: 	    $metastring=&getfile($file);
1.489     albertel 6963: 	}
1.208     albertel 6964:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6965:         my $token;
1.140     www      6966:         undef %metathesekeys;
1.71      www      6967:         while ($token=$parser->get_token) {
1.339     albertel 6968: 	    if ($token->[0] eq 'S') {
                   6969: 		if (defined($token->[2]->{'package'})) {
1.172     www      6970: #
                   6971: # This is a package - get package info
                   6972: #
1.339     albertel 6973: 		    my $package=$token->[2]->{'package'};
                   6974: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6975: 		    if (defined($token->[2]->{'id'})) { 
                   6976: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6977: 		    }
1.599     albertel 6978: 		    if ($metaentry{':packages'}) {
                   6979: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6980: 		    } else {
1.599     albertel 6981: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6982: 		    }
1.736     albertel 6983: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6984: 			my $part=$keyroot;
                   6985: 			$part=~s/^\_//;
1.736     albertel 6986: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6987: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6988: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6989: 			    # ignore package.tab specified default values
                   6990:                             # here &package_tab_default() will fetch those
                   6991: 			    if ($subp eq 'default') { next; }
1.736     albertel 6992: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6993: 			    my $unikey;
                   6994: 			    if ($pack =~ /_0$/) {
                   6995: 				$unikey='parameter_0_'.$name;
                   6996: 				$part=0;
                   6997: 			    } else {
                   6998: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6999: 			    }
1.339     albertel 7000: 			    if ($subp eq 'display') {
                   7001: 				$value.=' [Part: '.$part.']';
                   7002: 			    }
1.599     albertel 7003: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7004: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7005: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7006: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7007: 			    }
1.599     albertel 7008: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7009: 				$metaentry{':'.$unikey}=
                   7010: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7011: 			    }
1.339     albertel 7012: 			}
                   7013: 		    }
                   7014: 		} else {
1.172     www      7015: #
                   7016: # This is not a package - some other kind of start tag
1.339     albertel 7017: #
                   7018: 		    my $entry=$token->[1];
                   7019: 		    my $unikey;
                   7020: 		    if ($entry eq 'import') {
                   7021: 			$unikey='';
                   7022: 		    } else {
                   7023: 			$unikey=$entry;
                   7024: 		    }
                   7025: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7026: 
                   7027: 		    if (defined($token->[2]->{'id'})) { 
                   7028: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7029: 		    }
1.175     www      7030: 
1.339     albertel 7031: 		    if ($entry eq 'import') {
1.175     www      7032: #
                   7033: # Importing a library here
1.339     albertel 7034: #
                   7035: 			if ($depthcount<20) {
                   7036: 			    my $location=$parser->get_text('/import');
                   7037: 			    my $dir=$filename;
                   7038: 			    $dir=~s|[^/]*$||;
                   7039: 			    $location=&filelocation($dir,$location);
1.736     albertel 7040: 			    my $metadata = 
                   7041: 				&metadata($uri,'keys', $location,$unikey,
                   7042: 					  $depthcount+1);
                   7043: 			    foreach my $meta (split(',',$metadata)) {
                   7044: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7045: 				$metathesekeys{$meta}=1;
1.339     albertel 7046: 			    }
                   7047: 			}
                   7048: 		    } else { 
                   7049: 			
                   7050: 			if (defined($token->[2]->{'name'})) { 
                   7051: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7052: 			}
                   7053: 			$metathesekeys{$unikey}=1;
1.736     albertel 7054: 			foreach my $param (@{$token->[3]}) {
                   7055: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7056: 				$token->[2]->{$param};
1.339     albertel 7057: 			}
                   7058: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7059: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7060: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7061: 		 # only ws inside the tag, and not in default, so use default
                   7062: 		 # as value
1.599     albertel 7063: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7064: 			} elsif ( $internaltext =~ /\S/ ) {
                   7065: 		  # something interesting inside the tag
                   7066: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7067: 			} else {
1.908     albertel 7068: 		  # no interesting values, don't set a default
1.339     albertel 7069: 			}
1.172     www      7070: # end of not-a-package not-a-library import
1.339     albertel 7071: 		    }
1.172     www      7072: # end of not-a-package start tag
1.339     albertel 7073: 		}
1.172     www      7074: # the next is the end of "start tag"
1.339     albertel 7075: 	    }
                   7076: 	}
1.483     albertel 7077: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7078: 	$extension = lc($extension);
                   7079: 	if ($extension eq 'htm') { $extension='html'; }
                   7080: 
1.737     albertel 7081: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7082: 	    #no specific packages #how's our extension
                   7083: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7084: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7085: 					 \%metathesekeys);
                   7086: 	}
1.883     albertel 7087: 
                   7088: 	if (!exists($metaentry{':packages'})
                   7089: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7090: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7091: 		#no specific packages well let's get default then
                   7092: 		if ($key!~/^default&/) { next; }
1.488     albertel 7093: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7094: 					     \%metathesekeys);
                   7095: 	    }
                   7096: 	}
1.338     www      7097: # are there custom rights to evaluate
1.599     albertel 7098: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7099: 
1.338     www      7100:     #
                   7101:     # Importing a rights file here
1.339     albertel 7102:     #
                   7103: 	    unless ($depthcount) {
1.599     albertel 7104: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7105: 		my $dir=$filename;
                   7106: 		$dir=~s|[^/]*$||;
                   7107: 		$location=&filelocation($dir,$location);
1.736     albertel 7108: 		my $rights_metadata =
                   7109: 		    &metadata($uri,'keys',$location,'_rights',
                   7110: 			      $depthcount+1);
                   7111: 		foreach my $rights (split(',',$rights_metadata)) {
                   7112: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7113: 		    $metathesekeys{$rights}=1;
1.339     albertel 7114: 		}
                   7115: 	    }
                   7116: 	}
1.737     albertel 7117: 	# uniqifiy package listing
                   7118: 	my %seen;
                   7119: 	my @uniq_packages =
                   7120: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7121: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7122: 
                   7123: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7124: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7125: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7126: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7127: # this is the end of "was not already recently cached
1.71      www      7128:     }
1.599     albertel 7129:     return $metaentry{':'.$what};
1.261     albertel 7130: }
                   7131: 
1.488     albertel 7132: sub metadata_create_package_def {
1.483     albertel 7133:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7134:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7135:     if ($subp eq 'default') { next; }
                   7136:     
1.599     albertel 7137:     if (defined($metaentry{':packages'})) {
                   7138: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7139:     } else {
1.599     albertel 7140: 	$metaentry{':packages'}=$package;
1.483     albertel 7141:     }
                   7142:     my $value=$packagetab{$key};
                   7143:     my $unikey;
                   7144:     $unikey='parameter_0_'.$name;
1.599     albertel 7145:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7146:     $$metathesekeys{$unikey}=1;
1.599     albertel 7147:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7148: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7149:     }
1.599     albertel 7150:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7151: 	$metaentry{':'.$unikey}=
                   7152: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7153:     }
                   7154: }
                   7155: 
1.261     albertel 7156: sub metadata_generate_part0 {
                   7157:     my ($metadata,$metacache,$uri) = @_;
                   7158:     my %allnames;
1.737     albertel 7159:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7160: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7161: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7162: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7163: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7164: 	    $allnames{$name}=$part;
                   7165: 	  }
                   7166: 	}
                   7167:     }
                   7168:     foreach my $name (keys(%allnames)) {
                   7169:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7170:       my $key=":parameter_0_$name";
1.261     albertel 7171:       $$metacache{"$key.part"}='0';
                   7172:       $$metacache{"$key.name"}=$name;
1.428     albertel 7173:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7174: 					   $allnames{$name}.'_'.$name.
                   7175: 					   '.type'};
1.428     albertel 7176:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7177: 			     '.display'};
1.644     www      7178:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7179:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7180:       $$metacache{"$key.display"}=$olddis;
                   7181:     }
1.71      www      7182: }
                   7183: 
1.764     albertel 7184: # ------------------------------------------------------ Devalidate title cache
                   7185: 
                   7186: sub devalidate_title_cache {
                   7187:     my ($url)=@_;
                   7188:     if (!$env{'request.course.id'}) { return; }
                   7189:     my $symb=&symbread($url);
                   7190:     if (!$symb) { return; }
                   7191:     my $key=$env{'request.course.id'}."\0".$symb;
                   7192:     &devalidate_cache_new('title',$key);
                   7193: }
                   7194: 
1.301     www      7195: # ------------------------------------------------- Get the title of a resource
                   7196: 
                   7197: sub gettitle {
                   7198:     my $urlsymb=shift;
                   7199:     my $symb=&symbread($urlsymb);
1.534     albertel 7200:     if ($symb) {
1.620     albertel 7201: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7202: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7203: 	if (defined($cached)) { 
                   7204: 	    return $result;
                   7205: 	}
1.534     albertel 7206: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7207: 	my $title='';
1.907     albertel 7208: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7209: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7210: 	} else {
                   7211: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7212: 		    &GDBM_READER(),0640)) {
                   7213: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7214: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7215: 		untie(%bighash);
                   7216: 	    }
1.534     albertel 7217: 	}
                   7218: 	$title=~s/\&colon\;/\:/gs;
                   7219: 	if ($title) {
1.599     albertel 7220: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7221: 	}
                   7222: 	$urlsymb=$url;
                   7223:     }
                   7224:     my $title=&metadata($urlsymb,'title');
                   7225:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7226:     return $title;
1.301     www      7227: }
1.613     albertel 7228: 
1.614     albertel 7229: sub get_slot {
                   7230:     my ($which,$cnum,$cdom)=@_;
                   7231:     if (!$cnum || !$cdom) {
1.790     albertel 7232: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7233: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7234: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7235:     }
1.703     albertel 7236:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7237:     my %slotinfo;
                   7238:     if (exists($remembered{$key})) {
                   7239: 	$slotinfo{$which} = $remembered{$key};
                   7240:     } else {
                   7241: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7242: 	&Apache::lonhomework::showhash(%slotinfo);
                   7243: 	my ($tmp)=keys(%slotinfo);
                   7244: 	if ($tmp=~/^error:/) { return (); }
                   7245: 	$remembered{$key} = $slotinfo{$which};
                   7246:     }
1.616     albertel 7247:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7248: 	return %{$slotinfo{$which}};
                   7249:     }
                   7250:     return $slotinfo{$which};
1.614     albertel 7251: }
1.31      www      7252: # ------------------------------------------------- Update symbolic store links
                   7253: 
                   7254: sub symblist {
                   7255:     my ($mapname,%newhash)=@_;
1.438     www      7256:     $mapname=&deversion(&declutter($mapname));
1.31      www      7257:     my %hash;
1.620     albertel 7258:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7259:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7260:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7261: 	    foreach my $url (keys %newhash) {
                   7262: 		next if ($url eq 'last_known'
                   7263: 			 && $env{'form.no_update_last_known'});
                   7264: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7265: 						    $newhash{$url}->[1],
                   7266: 						    $newhash{$url}->[0]);
1.191     harris41 7267:             }
1.31      www      7268:             if (untie(%hash)) {
                   7269: 		return 'ok';
                   7270:             }
                   7271:         }
                   7272:     }
                   7273:     return 'error';
1.212     www      7274: }
                   7275: 
                   7276: # --------------------------------------------------------------- Verify a symb
                   7277: 
                   7278: sub symbverify {
1.510     www      7279:     my ($symb,$thisurl)=@_;
                   7280:     my $thisfn=$thisurl;
1.439     www      7281:     $thisfn=&declutter($thisfn);
1.215     www      7282: # direct jump to resource in page or to a sequence - will construct own symbs
                   7283:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7284: # check URL part
1.409     www      7285:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7286: 
1.431     www      7287:     unless ($url eq $thisfn) { return 0; }
1.213     www      7288: 
1.216     www      7289:     $symb=&symbclean($symb);
1.510     www      7290:     $thisurl=&deversion($thisurl);
1.439     www      7291:     $thisfn=&deversion($thisfn);
1.213     www      7292: 
                   7293:     my %bighash;
                   7294:     my $okay=0;
1.431     www      7295: 
1.620     albertel 7296:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7297:                             &GDBM_READER(),0640)) {
1.510     www      7298:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7299:         unless ($ids) { 
1.510     www      7300:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7301:         }
                   7302:         if ($ids) {
                   7303: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7304: 	    foreach my $id (split(/\,/,$ids)) {
                   7305: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7306:                if (
                   7307:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7308:    eq $symb) { 
1.620     albertel 7309: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7310: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7311: 		       $okay=1; 
                   7312: 		   }
                   7313: 	       }
1.216     www      7314: 	   }
                   7315:         }
1.213     www      7316: 	untie(%bighash);
                   7317:     }
                   7318:     return $okay;
1.31      www      7319: }
                   7320: 
1.210     www      7321: # --------------------------------------------------------------- Clean-up symb
                   7322: 
                   7323: sub symbclean {
                   7324:     my $symb=shift;
1.568     albertel 7325:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7326: # remove version from map
                   7327:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7328: 
1.210     www      7329: # remove version from URL
                   7330:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7331: 
1.507     www      7332: # remove wrapper
                   7333: 
1.510     www      7334:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7335:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7336:     return $symb;
1.409     www      7337: }
                   7338: 
                   7339: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7340: 
                   7341: sub encode_symb {
                   7342:     my ($map,$resid,$url)=@_;
                   7343:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7344: }
1.409     www      7345: 
                   7346: sub decode_symb {
1.568     albertel 7347:     my $symb=shift;
                   7348:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7349:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7350:     return (&fixversion($map),$resid,&fixversion($url));
                   7351: }
                   7352: 
                   7353: sub fixversion {
                   7354:     my $fn=shift;
1.609     banghart 7355:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7356:     my %bighash;
                   7357:     my $uri=&clutter($fn);
1.620     albertel 7358:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7359: # is this cached?
1.599     albertel 7360:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7361:     if (defined($cached)) { return $result; }
                   7362: # unfortunately not cached, or expired
1.620     albertel 7363:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7364: 	    &GDBM_READER(),0640)) {
                   7365:  	if ($bighash{'version_'.$uri}) {
                   7366:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7367:  	    unless (($version eq 'mostrecent') || 
                   7368: 		    ($version==&getversion($uri))) {
1.440     www      7369:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7370:  	    }
                   7371:  	}
                   7372:  	untie %bighash;
1.413     www      7373:     }
1.599     albertel 7374:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7375: }
                   7376: 
                   7377: sub deversion {
                   7378:     my $url=shift;
                   7379:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7380:     return $url;
1.210     www      7381: }
                   7382: 
1.31      www      7383: # ------------------------------------------------------ Return symb list entry
                   7384: 
                   7385: sub symbread {
1.249     www      7386:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7387:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7388:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7389: # no filename provided? try from environment
1.44      www      7390:     unless ($thisfn) {
1.620     albertel 7391:         if ($env{'request.symb'}) {
                   7392: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7393: 	}
1.620     albertel 7394: 	$thisfn=$env{'request.filename'};
1.44      www      7395:     }
1.569     albertel 7396:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7397: # is that filename actually a symb? Verify, clean, and return
                   7398:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7399: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7400: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7401: 	}
1.242     www      7402:     }
1.44      www      7403:     $thisfn=declutter($thisfn);
1.31      www      7404:     my %hash;
1.37      www      7405:     my %bighash;
                   7406:     my $syval='';
1.620     albertel 7407:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7408:         my $targetfn = $thisfn;
1.609     banghart 7409:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7410:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7411:         }
1.687     albertel 7412: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7413: 	    $targetfn=$1;
                   7414: 	}
1.620     albertel 7415:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7416:                       &GDBM_READER(),0640)) {
1.481     raeburn  7417: 	    $syval=$hash{$targetfn};
1.37      www      7418:             untie(%hash);
                   7419:         }
                   7420: # ---------------------------------------------------------- There was an entry
                   7421:         if ($syval) {
1.601     albertel 7422: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7423: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7424: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7425: 		    #return $env{$cache_str}='';
1.601     albertel 7426: 		#}    
                   7427: 		#$syval.=$1;
                   7428: 	    #}
1.37      www      7429:         } else {
                   7430: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7431:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7432:                             &GDBM_READER(),0640)) {
1.37      www      7433: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7434:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7435:               unless ($ids) { 
                   7436:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7437:               }
                   7438:               unless ($ids) {
                   7439: # alias?
                   7440: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7441:               }
1.37      www      7442:               if ($ids) {
                   7443: # ------------------------------------------------------------------- Has ID(s)
                   7444:                  my @possibilities=split(/\,/,$ids);
1.39      www      7445:                  if ($#possibilities==0) {
                   7446: # ----------------------------------------------- There is only one possibility
1.37      www      7447: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7448: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7449: 						    $resid,$thisfn);
1.249     www      7450:                  } elsif (!$donotrecurse) {
1.39      www      7451: # ------------------------------------------ There is more than one possibility
                   7452:                      my $realpossible=0;
1.800     albertel 7453:                      foreach my $id (@possibilities) {
                   7454: 			 my $file=$bighash{'src_'.$id};
1.39      www      7455:                          if (&allowed('bre',$file)) {
1.800     albertel 7456:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7457:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7458: 				$realpossible++;
1.626     albertel 7459:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7460: 						    $resid,$thisfn);
1.39      www      7461:                             }
                   7462: 			 }
1.191     harris41 7463:                      }
1.39      www      7464: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7465:                  } else {
                   7466:                      $syval='';
1.37      www      7467:                  }
                   7468: 	      }
                   7469:               untie(%bighash)
1.481     raeburn  7470:            }
1.31      www      7471:         }
1.62      www      7472:         if ($syval) {
1.620     albertel 7473: 	    return $env{$cache_str}=$syval;
1.62      www      7474:         }
1.31      www      7475:     }
1.44      www      7476:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7477:     return $env{$cache_str}='';
1.31      www      7478: }
                   7479: 
                   7480: # ---------------------------------------------------------- Return random seed
                   7481: 
1.32      www      7482: sub numval {
                   7483:     my $txt=shift;
                   7484:     $txt=~tr/A-J/0-9/;
                   7485:     $txt=~tr/a-j/0-9/;
                   7486:     $txt=~tr/K-T/0-9/;
                   7487:     $txt=~tr/k-t/0-9/;
                   7488:     $txt=~tr/U-Z/0-5/;
                   7489:     $txt=~tr/u-z/0-5/;
                   7490:     $txt=~s/\D//g;
1.564     albertel 7491:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7492:     return int($txt);
1.368     albertel 7493: }
                   7494: 
1.484     albertel 7495: sub numval2 {
                   7496:     my $txt=shift;
                   7497:     $txt=~tr/A-J/0-9/;
                   7498:     $txt=~tr/a-j/0-9/;
                   7499:     $txt=~tr/K-T/0-9/;
                   7500:     $txt=~tr/k-t/0-9/;
                   7501:     $txt=~tr/U-Z/0-5/;
                   7502:     $txt=~tr/u-z/0-5/;
                   7503:     $txt=~s/\D//g;
                   7504:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7505:     my $total;
                   7506:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7507:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7508:     return int($total);
                   7509: }
                   7510: 
1.575     albertel 7511: sub numval3 {
                   7512:     use integer;
                   7513:     my $txt=shift;
                   7514:     $txt=~tr/A-J/0-9/;
                   7515:     $txt=~tr/a-j/0-9/;
                   7516:     $txt=~tr/K-T/0-9/;
                   7517:     $txt=~tr/k-t/0-9/;
                   7518:     $txt=~tr/U-Z/0-5/;
                   7519:     $txt=~tr/u-z/0-5/;
                   7520:     $txt=~s/\D//g;
                   7521:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7522:     my $total;
                   7523:     foreach my $val (@txts) { $total+=$val; }
                   7524:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7525:     return $total;
                   7526: }
                   7527: 
1.675     albertel 7528: sub digest {
                   7529:     my ($data)=@_;
                   7530:     my $digest=&Digest::MD5::md5($data);
                   7531:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7532:     my ($e,$f);
                   7533:     {
                   7534:         use integer;
                   7535:         $e=($a+$b);
                   7536:         $f=($c+$d);
                   7537:         if ($_64bit) {
                   7538:             $e=(($e<<32)>>32);
                   7539:             $f=(($f<<32)>>32);
                   7540:         }
                   7541:     }
                   7542:     if (wantarray) {
                   7543: 	return ($e,$f);
                   7544:     } else {
                   7545: 	my $g;
                   7546: 	{
                   7547: 	    use integer;
                   7548: 	    $g=($e+$f);
                   7549: 	    if ($_64bit) {
                   7550: 		$g=(($g<<32)>>32);
                   7551: 	    }
                   7552: 	}
                   7553: 	return $g;
                   7554:     }
                   7555: }
                   7556: 
1.368     albertel 7557: sub latest_rnd_algorithm_id {
1.675     albertel 7558:     return '64bit5';
1.366     albertel 7559: }
1.32      www      7560: 
1.503     albertel 7561: sub get_rand_alg {
                   7562:     my ($courseid)=@_;
1.790     albertel 7563:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7564:     if ($courseid) {
1.620     albertel 7565: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7566:     }
                   7567:     return &latest_rnd_algorithm_id();
                   7568: }
                   7569: 
1.562     albertel 7570: sub validCODE {
                   7571:     my ($CODE)=@_;
                   7572:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7573:     return 0;
                   7574: }
                   7575: 
1.491     albertel 7576: sub getCODE {
1.620     albertel 7577:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7578:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7579: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7580: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7581: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7582:     }
                   7583:     return undef;
                   7584: }
                   7585: 
1.31      www      7586: sub rndseed {
1.155     albertel 7587:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7588:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7589:     if (!defined($symb)) {
1.366     albertel 7590: 	unless ($symb=$wsymb) { return time; }
                   7591:     }
                   7592:     if (!$courseid) { $courseid=$wcourseid; }
                   7593:     if (!$domain) { $domain=$wdomain; }
                   7594:     if (!$username) { $username=$wusername }
1.503     albertel 7595:     my $which=&get_rand_alg();
1.803     albertel 7596: 
1.491     albertel 7597:     if (defined(&getCODE())) {
1.675     albertel 7598: 	if ($which eq '64bit5') {
                   7599: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7600: 	} elsif ($which eq '64bit4') {
1.575     albertel 7601: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7602: 	} else {
                   7603: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7604: 	}
1.675     albertel 7605:     } elsif ($which eq '64bit5') {
                   7606: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7607:     } elsif ($which eq '64bit4') {
                   7608: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7609:     } elsif ($which eq '64bit3') {
                   7610: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7611:     } elsif ($which eq '64bit2') {
                   7612: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7613:     } elsif ($which eq '64bit') {
                   7614: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7615:     }
                   7616:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7617: }
                   7618: 
                   7619: sub rndseed_32bit {
                   7620:     my ($symb,$courseid,$domain,$username)=@_;
                   7621:     {
                   7622: 	use integer;
                   7623: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7624: 	my $symbseed=numval($symb) << 22;
                   7625: 	my $namechck=unpack("%32C*",$username) << 17;
                   7626: 	my $nameseed=numval($username) << 12;
                   7627: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7628: 	my $courseseed=unpack("%32C*",$courseid);
                   7629: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7630: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7631: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7632: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7633: 	return $num;
                   7634:     }
                   7635: }
                   7636: 
                   7637: sub rndseed_64bit {
                   7638:     my ($symb,$courseid,$domain,$username)=@_;
                   7639:     {
                   7640: 	use integer;
                   7641: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7642: 	my $symbseed=numval($symb) << 10;
                   7643: 	my $namechck=unpack("%32S*",$username);
                   7644: 	
                   7645: 	my $nameseed=numval($username) << 21;
                   7646: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7647: 	my $courseseed=unpack("%32S*",$courseid);
                   7648: 	
                   7649: 	my $num1=$symbchck+$symbseed+$namechck;
                   7650: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7651: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7652: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7653: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7654: 	return "$num1,$num2";
1.155     albertel 7655:     }
1.366     albertel 7656: }
                   7657: 
1.443     albertel 7658: sub rndseed_64bit2 {
                   7659:     my ($symb,$courseid,$domain,$username)=@_;
                   7660:     {
                   7661: 	use integer;
                   7662: 	# strings need to be an even # of cahracters long, it it is odd the
                   7663:         # last characters gets thrown away
                   7664: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7665: 	my $symbseed=numval($symb) << 10;
                   7666: 	my $namechck=unpack("%32S*",$username.' ');
                   7667: 	
                   7668: 	my $nameseed=numval($username) << 21;
1.501     albertel 7669: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7670: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7671: 	
                   7672: 	my $num1=$symbchck+$symbseed+$namechck;
                   7673: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7674: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7675: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7676: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7677: 	return "$num1,$num2";
                   7678:     }
                   7679: }
                   7680: 
                   7681: sub rndseed_64bit3 {
                   7682:     my ($symb,$courseid,$domain,$username)=@_;
                   7683:     {
                   7684: 	use integer;
                   7685: 	# strings need to be an even # of cahracters long, it it is odd the
                   7686:         # last characters gets thrown away
                   7687: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7688: 	my $symbseed=numval2($symb) << 10;
                   7689: 	my $namechck=unpack("%32S*",$username.' ');
                   7690: 	
                   7691: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7692: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7693: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7694: 	
                   7695: 	my $num1=$symbchck+$symbseed+$namechck;
                   7696: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7697: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7698: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7699: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7700: 	
1.503     albertel 7701: 	return "$num1:$num2";
1.443     albertel 7702:     }
                   7703: }
                   7704: 
1.575     albertel 7705: sub rndseed_64bit4 {
                   7706:     my ($symb,$courseid,$domain,$username)=@_;
                   7707:     {
                   7708: 	use integer;
                   7709: 	# strings need to be an even # of cahracters long, it it is odd the
                   7710:         # last characters gets thrown away
                   7711: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7712: 	my $symbseed=numval3($symb) << 10;
                   7713: 	my $namechck=unpack("%32S*",$username.' ');
                   7714: 	
                   7715: 	my $nameseed=numval3($username) << 21;
                   7716: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7717: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7718: 	
                   7719: 	my $num1=$symbchck+$symbseed+$namechck;
                   7720: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7721: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7722: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7723: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7724: 	
                   7725: 	return "$num1:$num2";
                   7726:     }
                   7727: }
                   7728: 
1.675     albertel 7729: sub rndseed_64bit5 {
                   7730:     my ($symb,$courseid,$domain,$username)=@_;
                   7731:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7732:     return "$num1:$num2";
                   7733: }
                   7734: 
1.366     albertel 7735: sub rndseed_CODE_64bit {
                   7736:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7737:     {
1.366     albertel 7738: 	use integer;
1.443     albertel 7739: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7740: 	my $symbseed=numval2($symb);
1.491     albertel 7741: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7742: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7743: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7744: 	my $num1=$symbseed+$CODEchck;
                   7745: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7746: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7747: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7748: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7749: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7750: 	return "$num1:$num2";
1.366     albertel 7751:     }
                   7752: }
                   7753: 
1.575     albertel 7754: sub rndseed_CODE_64bit4 {
                   7755:     my ($symb,$courseid,$domain,$username)=@_;
                   7756:     {
                   7757: 	use integer;
                   7758: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7759: 	my $symbseed=numval3($symb);
                   7760: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7761: 	my $CODEseed=numval3(&getCODE());
                   7762: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7763: 	my $num1=$symbseed+$CODEchck;
                   7764: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7765: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7766: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7767: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7768: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7769: 	return "$num1:$num2";
                   7770:     }
                   7771: }
                   7772: 
1.675     albertel 7773: sub rndseed_CODE_64bit5 {
                   7774:     my ($symb,$courseid,$domain,$username)=@_;
                   7775:     my $code = &getCODE();
                   7776:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7777:     return "$num1:$num2";
                   7778: }
                   7779: 
1.366     albertel 7780: sub setup_random_from_rndseed {
                   7781:     my ($rndseed)=@_;
1.503     albertel 7782:     if ($rndseed =~/([,:])/) {
                   7783: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7784: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7785:     } else {
                   7786: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7787:     }
1.36      albertel 7788: }
                   7789: 
1.474     albertel 7790: sub latest_receipt_algorithm_id {
1.835     albertel 7791:     return 'receipt3';
1.474     albertel 7792: }
                   7793: 
1.480     www      7794: sub recunique {
                   7795:     my $fucourseid=shift;
                   7796:     my $unique;
1.835     albertel 7797:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7798: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7799: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7800:     } else {
                   7801: 	$unique=$perlvar{'lonReceipt'};
                   7802:     }
                   7803:     return unpack("%32C*",$unique);
                   7804: }
                   7805: 
                   7806: sub recprefix {
                   7807:     my $fucourseid=shift;
                   7808:     my $prefix;
1.835     albertel 7809:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7810: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7811: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7812:     } else {
                   7813: 	$prefix=$perlvar{'lonHostID'};
                   7814:     }
                   7815:     return unpack("%32C*",$prefix);
                   7816: }
                   7817: 
1.76      www      7818: sub ireceipt {
1.474     albertel 7819:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7820: 
                   7821:     my $return =&recprefix($fucourseid).'-';
                   7822: 
                   7823:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7824: 	$env{'request.state'} eq 'construct') {
                   7825: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7826: 	return $return;
                   7827:     }
                   7828: 
1.76      www      7829:     my $cuname=unpack("%32C*",$funame);
                   7830:     my $cudom=unpack("%32C*",$fudom);
                   7831:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7832:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7833:     my $cunique=&recunique($fucourseid);
1.474     albertel 7834:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7835:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7836: 
1.790     albertel 7837: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7838: 			       
                   7839: 	$return.= ($cunique%$cuname+
                   7840: 		   $cunique%$cudom+
                   7841: 		   $cusymb%$cuname+
                   7842: 		   $cusymb%$cudom+
                   7843: 		   $cucourseid%$cuname+
                   7844: 		   $cucourseid%$cudom+
                   7845: 		   $cpart%$cuname+
                   7846: 		   $cpart%$cudom);
                   7847:     } else {
                   7848: 	$return.= ($cunique%$cuname+
                   7849: 		   $cunique%$cudom+
                   7850: 		   $cusymb%$cuname+
                   7851: 		   $cusymb%$cudom+
                   7852: 		   $cucourseid%$cuname+
                   7853: 		   $cucourseid%$cudom);
                   7854:     }
                   7855:     return $return;
1.76      www      7856: }
                   7857: 
                   7858: sub receipt {
1.474     albertel 7859:     my ($part)=@_;
1.790     albertel 7860:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7861:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7862: }
1.260     ng       7863: 
1.790     albertel 7864: sub whichuser {
                   7865:     my ($passedsymb)=@_;
                   7866:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7867:     if (defined($env{'form.grade_symb'})) {
                   7868: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7869: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7870: 	if (!$allowed &&
                   7871: 	    exists($env{'request.course.sec'}) &&
                   7872: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7873: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7874: 			      '/'.$env{'request.course.sec'});
                   7875: 	}
                   7876: 	if ($allowed) {
                   7877: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7878: 	    $courseid=$tmp_courseid;
                   7879: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7880: 	    ($name)=&get_env_multiple('form.grade_username');
                   7881: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7882: 	}
                   7883:     }
                   7884:     if (!$passedsymb) {
                   7885: 	$symb=&symbread();
                   7886:     } else {
                   7887: 	$symb=$passedsymb;
                   7888:     }
                   7889:     $courseid=$env{'request.course.id'};
                   7890:     $domain=$env{'user.domain'};
                   7891:     $name=$env{'user.name'};
                   7892:     if ($name eq 'public' && $domain eq 'public') {
                   7893: 	if (!defined($env{'form.username'})) {
                   7894: 	    $env{'form.username'}.=time.rand(10000000);
                   7895: 	}
                   7896: 	$name.=$env{'form.username'};
                   7897:     }
                   7898:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7899: 
                   7900: }
                   7901: 
1.36      albertel 7902: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7903: # returns either the contents of the file or 
                   7904: # -1 if the file doesn't exist
1.481     raeburn  7905: #
                   7906: # if the target is a file that was uploaded via DOCS, 
                   7907: # a check will be made to see if a current copy exists on the local server,
                   7908: # if it does this will be served, otherwise a copy will be retrieved from
                   7909: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7910: # the local server.   
1.472     albertel 7911: 
1.36      albertel 7912: sub getfile {
1.538     albertel 7913:     my ($file) = @_;
1.609     banghart 7914:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7915:     &repcopy($file);
                   7916:     return &readfile($file);
                   7917: }
                   7918: 
                   7919: sub repcopy_userfile {
                   7920:     my ($file)=@_;
1.609     banghart 7921:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7922:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7923:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7924: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7925:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7926:     if (-e "$file") {
1.828     www      7927: # we already have a local copy, check it out
1.538     albertel 7928: 	my @fileinfo = stat($file);
1.828     www      7929: 	my $rtncode;
                   7930: 	my $info;
1.538     albertel 7931: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7932: 	if ($lwpresp ne 'ok') {
1.828     www      7933: # there is no such file anymore, even though we had a local copy
1.482     albertel 7934: 	    if ($rtncode eq '404') {
1.538     albertel 7935: 		unlink($file);
1.482     albertel 7936: 	    }
                   7937: 	    return -1;
                   7938: 	}
                   7939: 	if ($info < $fileinfo[9]) {
1.828     www      7940: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7941: 	    return 'ok';
1.828     www      7942: 	} else {
                   7943: # the file is outdated, get rid of it
                   7944: 	    unlink($file);
1.482     albertel 7945: 	}
1.828     www      7946:     }
                   7947: # one way or the other, at this point, we don't have the file
                   7948: # construct the correct path for the file
                   7949:     my @parts = ($cdom,$cnum); 
                   7950:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7951: 	push @parts, split(/\//,$1);
                   7952:     }
                   7953:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7954:     foreach my $part (@parts) {
                   7955: 	$path .= '/'.$part;
                   7956: 	if (!-e $path) {
                   7957: 	    mkdir($path,0770);
1.482     albertel 7958: 	}
                   7959:     }
1.828     www      7960: # now the path exists for sure
                   7961: # get a user agent
                   7962:     my $ua=new LWP::UserAgent;
                   7963:     my $transferfile=$file.'.in.transfer';
                   7964: # FIXME: this should flock
                   7965:     if (-e $transferfile) { return 'ok'; }
                   7966:     my $request;
                   7967:     $uri=~s/^\///;
1.838     albertel 7968:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7969:     my $response=$ua->request($request,$transferfile);
                   7970: # did it work?
                   7971:     if ($response->is_error()) {
                   7972: 	unlink($transferfile);
                   7973: 	&logthis("Userfile repcopy failed for $uri");
                   7974: 	return -1;
                   7975:     }
                   7976: # worked, rename the transfer file
                   7977:     rename($transferfile,$file);
1.607     raeburn  7978:     return 'ok';
1.481     raeburn  7979: }
                   7980: 
1.517     albertel 7981: sub tokenwrapper {
                   7982:     my $uri=shift;
1.552     albertel 7983:     $uri=~s|^http\://([^/]+)||;
                   7984:     $uri=~s|^/||;
1.620     albertel 7985:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7986:     my $token=$1;
1.552     albertel 7987:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7988:     if ($udom && $uname && $file) {
                   7989: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7990:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7991:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7992:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7993:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7994:     } else {
                   7995:         return '/adm/notfound.html';
                   7996:     }
                   7997: }
                   7998: 
1.828     www      7999: # call with reqtype HEAD: get last modification time
                   8000: # call with reqtype GET: get the file contents
                   8001: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8002: #
1.481     raeburn  8003: sub getuploaded {
                   8004:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8005:     $uri=~s/^\///;
1.838     albertel 8006:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8007:     my $ua=new LWP::UserAgent;
                   8008:     my $request=new HTTP::Request($reqtype,$uri);
                   8009:     my $response=$ua->request($request);
                   8010:     $$rtncode = $response->code;
1.482     albertel 8011:     if (! $response->is_success()) {
                   8012: 	return 'failed';
                   8013:     }      
                   8014:     if ($reqtype eq 'HEAD') {
1.486     www      8015: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8016:     } elsif ($reqtype eq 'GET') {
                   8017: 	$$info = $response->content;
1.472     albertel 8018:     }
1.482     albertel 8019:     return 'ok';
1.36      albertel 8020: }
                   8021: 
1.481     raeburn  8022: sub readfile {
                   8023:     my $file = shift;
                   8024:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8025:     my $fh;
                   8026:     open($fh,"<$file");
                   8027:     my $a='';
1.800     albertel 8028:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8029:     return $a;
                   8030: }
                   8031: 
1.36      albertel 8032: sub filelocation {
1.590     banghart 8033:     my ($dir,$file) = @_;
                   8034:     my $location;
                   8035:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8036: 
                   8037:     if ($file =~ m-^/adm/-) {
                   8038: 	$file=~s-^/adm/wrapper/-/-;
                   8039: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8040:     }
1.882     albertel 8041: 
1.590     banghart 8042:     if ($file=~m:^/~:) { # is a contruction space reference
                   8043:         $location = $file;
                   8044:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8045:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8046: 	# is a correct contruction space reference
                   8047:         $location = $file;
1.609     banghart 8048:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8049:         my ($udom,$uname,$filename)=
1.811     albertel 8050:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8051:         my $home=&homeserver($uname,$udom);
                   8052:         my $is_me=0;
                   8053:         my @ids=&current_machine_ids();
                   8054:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8055:         if ($is_me) {
1.740     www      8056:   	    $location=&propath($udom,$uname).
1.590     banghart 8057:   	      '/userfiles/'.$filename;
                   8058:         } else {
                   8059:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8060:   	      $udom.'/'.$uname.'/'.$filename;
                   8061:         }
1.882     albertel 8062:     } elsif ($file =~ m-^/adm/-) {
                   8063: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8064:     } else {
                   8065:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8066:         $file=~s:^/res/:/:;
                   8067:         if ( !( $file =~ m:^/:) ) {
                   8068:             $location = $dir. '/'.$file;
                   8069:         } else {
                   8070:             $location = '/home/httpd/html/res'.$file;
                   8071:         }
1.59      albertel 8072:     }
1.590     banghart 8073:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8074:     while ($location=~m{/\.\./}) {
                   8075: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8076: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8077: 	} else {
                   8078: 	    $location=~ s{/\.\./}{/}g;
                   8079: 	}
                   8080:     } #remove dir/..
1.590     banghart 8081:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8082:     return $location;
1.46      www      8083: }
1.36      albertel 8084: 
1.46      www      8085: sub hreflocation {
                   8086:     my ($dir,$file)=@_;
1.460     albertel 8087:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8088: 	$file=filelocation($dir,$file);
1.700     albertel 8089:     } elsif ($file=~m-^/adm/-) {
                   8090: 	$file=~s-^/adm/wrapper/-/-;
                   8091: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8092:     }
                   8093:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8094: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8095:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8096: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8097:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8098: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8099: 	    -/uploaded/$1/$2/-x;
1.46      www      8100:     }
1.913     albertel 8101:     if ($file=~ m{^/userfiles/}) {
                   8102: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8103:     }
1.462     albertel 8104:     return $file;
1.465     albertel 8105: }
                   8106: 
                   8107: sub current_machine_domains {
1.853     albertel 8108:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8109: }
                   8110: 
                   8111: sub machine_domains {
                   8112:     my ($hostname) = @_;
1.465     albertel 8113:     my @domains;
1.838     albertel 8114:     my %hostname = &all_hostnames();
1.465     albertel 8115:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8116: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8117: 	if ($hostname eq $name) {
1.844     albertel 8118: 	    push(@domains,&host_domain($id));
1.465     albertel 8119: 	}
                   8120:     }
                   8121:     return @domains;
                   8122: }
                   8123: 
                   8124: sub current_machine_ids {
1.853     albertel 8125:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8126: }
                   8127: 
                   8128: sub machine_ids {
                   8129:     my ($hostname) = @_;
                   8130:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8131:     my @ids;
1.888     albertel 8132:     my %name_to_host = &all_names();
1.889     albertel 8133:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8134: 	return @{ $name_to_host{$hostname} };
                   8135:     }
                   8136:     return;
1.31      www      8137: }
                   8138: 
1.824     raeburn  8139: sub additional_machine_domains {
                   8140:     my @domains;
                   8141:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8142:     while( my $line = <$fh>) {
                   8143:         $line =~ s/\s//g;
                   8144:         push(@domains,$line);
                   8145:     }
                   8146:     return @domains;
                   8147: }
                   8148: 
                   8149: sub default_login_domain {
                   8150:     my $domain = $perlvar{'lonDefDomain'};
                   8151:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8152:     foreach my $posdom (&current_machine_domains(),
                   8153:                         &additional_machine_domains()) {
                   8154:         if (lc($posdom) eq lc($testdomain)) {
                   8155:             $domain=$posdom;
                   8156:             last;
                   8157:         }
                   8158:     }
                   8159:     return $domain;
                   8160: }
                   8161: 
1.31      www      8162: # ------------------------------------------------------------- Declutters URLs
                   8163: 
                   8164: sub declutter {
                   8165:     my $thisfn=shift;
1.569     albertel 8166:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8167:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8168:     $thisfn=~s/^\///;
1.697     albertel 8169:     $thisfn=~s|^adm/wrapper/||;
                   8170:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8171:     $thisfn=~s/^res\///;
1.235     www      8172:     $thisfn=~s/\?.+$//;
1.268     www      8173:     return $thisfn;
                   8174: }
                   8175: 
                   8176: # ------------------------------------------------------------- Clutter up URLs
                   8177: 
                   8178: sub clutter {
                   8179:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8180:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8181: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8182:        $thisfn='/res'.$thisfn; 
                   8183:     }
1.694     albertel 8184:     if ($thisfn !~m|/adm|) {
1.695     albertel 8185: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8186: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8187: 	} else {
                   8188: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8189: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8190: 	    if ($embstyle eq 'ssi'
                   8191: 		|| ($embstyle eq 'hdn')
                   8192: 		|| ($embstyle eq 'rat')
                   8193: 		|| ($embstyle eq 'prv')
                   8194: 		|| ($embstyle eq 'ign')) {
                   8195: 		#do nothing with these
                   8196: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8197: 		|| ($embstyle eq 'emb')
                   8198: 		|| ($embstyle eq 'wrp')) {
                   8199: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8200: 	    } elsif ($embstyle eq 'unk'
                   8201: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8202: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8203: 	    } else {
1.718     www      8204: #		&logthis("Got a blank emb style");
1.695     albertel 8205: 	    }
1.694     albertel 8206: 	}
                   8207:     }
1.31      www      8208:     return $thisfn;
1.12      www      8209: }
                   8210: 
1.787     albertel 8211: sub clutter_with_no_wrapper {
                   8212:     my $uri = &clutter(shift);
                   8213:     if ($uri =~ m-^/adm/-) {
                   8214: 	$uri =~ s-^/adm/wrapper/-/-;
                   8215: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8216:     }
                   8217:     return $uri;
                   8218: }
                   8219: 
1.557     albertel 8220: sub freeze_escape {
                   8221:     my ($value)=@_;
                   8222:     if (ref($value)) {
                   8223: 	$value=&nfreeze($value);
                   8224: 	return '__FROZEN__'.&escape($value);
                   8225:     }
                   8226:     return &escape($value);
                   8227: }
                   8228: 
1.11      www      8229: 
1.557     albertel 8230: sub thaw_unescape {
                   8231:     my ($value)=@_;
                   8232:     if ($value =~ /^__FROZEN__/) {
                   8233: 	substr($value,0,10,undef);
                   8234: 	$value=&unescape($value);
                   8235: 	return &thaw($value);
                   8236:     }
                   8237:     return &unescape($value);
                   8238: }
                   8239: 
1.436     albertel 8240: sub correct_line_ends {
                   8241:     my ($result)=@_;
                   8242:     $$result =~s/\r\n/\n/mg;
                   8243:     $$result =~s/\r/\n/mg;
1.415     albertel 8244: }
1.1       albertel 8245: # ================================================================ Main Program
                   8246: 
1.184     www      8247: sub goodbye {
1.204     albertel 8248:    &logthis("Starting Shut down");
1.443     albertel 8249: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8250:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8251: #converted
1.599     albertel 8252: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8253:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8254: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8255: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8256: #1.1 only
1.870     albertel 8257: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8258: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8259: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8260: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8261:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8262:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8263:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8264:    &flushcourselogs();
                   8265:    &logthis("Shutting down");
                   8266: }
                   8267: 
1.852     albertel 8268: sub get_dns {
1.869     albertel 8269:     my ($url,$func,$ignore_cache) = @_;
                   8270:     if (!$ignore_cache) {
                   8271: 	my ($content,$cached)=
                   8272: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8273: 	if ($cached) {
                   8274: 	    &$func($content);
                   8275: 	    return;
                   8276: 	}
                   8277:     }
                   8278: 
                   8279:     my %alldns;
1.852     albertel 8280:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8281:     foreach my $dns (<$config>) {
                   8282: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8283: 	$alldns{$1} = 1;
                   8284:     }
                   8285:     while (%alldns) {
                   8286: 	my ($dns) = keys(%alldns);
                   8287: 	delete($alldns{$dns});
1.852     albertel 8288: 	my $ua=new LWP::UserAgent;
                   8289: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8290: 	my $response=$ua->request($request);
                   8291: 	next if ($response->is_error());
                   8292: 	my @content = split("\n",$response->content);
1.869     albertel 8293: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8294: 	&$func(\@content);
1.869     albertel 8295: 	return;
1.852     albertel 8296:     }
                   8297:     close($config);
1.871     albertel 8298:     my $which = (split('/',$url))[3];
                   8299:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8300:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8301:     my @content = <$config>;
                   8302:     &$func(\@content);
                   8303:     return;
1.852     albertel 8304: }
1.327     albertel 8305: # ------------------------------------------------------------ Read domain file
                   8306: {
1.852     albertel 8307:     my $loaded;
1.846     albertel 8308:     my %domain;
                   8309: 
1.852     albertel 8310:     sub parse_domain_tab {
                   8311: 	my ($lines) = @_;
                   8312: 	foreach my $line (@$lines) {
                   8313: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8314: 
1.846     albertel 8315: 	    chomp($line);
1.852     albertel 8316: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8317: 	    my %this_domain;
                   8318: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8319: 			       'lang_def', 'city', 'longi', 'lati',
                   8320: 			       'primary') {
                   8321: 		$this_domain{$field} = shift(@elements);
                   8322: 	    }
                   8323: 	    $domain{$name} = \%this_domain;
1.852     albertel 8324: 	}
                   8325:     }
1.864     albertel 8326: 
                   8327:     sub reset_domain_info {
                   8328: 	undef($loaded);
                   8329: 	undef(%domain);
                   8330:     }
                   8331: 
1.852     albertel 8332:     sub load_domain_tab {
1.869     albertel 8333: 	my ($ignore_cache) = @_;
                   8334: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8335: 	my $fh;
                   8336: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8337: 	    my @lines = <$fh>;
                   8338: 	    &parse_domain_tab(\@lines);
1.448     albertel 8339: 	}
1.852     albertel 8340: 	close($fh);
                   8341: 	$loaded = 1;
1.327     albertel 8342:     }
1.846     albertel 8343: 
                   8344:     sub domain {
1.852     albertel 8345: 	&load_domain_tab() if (!$loaded);
                   8346: 
1.846     albertel 8347: 	my ($name,$what) = @_;
                   8348: 	return if ( !exists($domain{$name}) );
                   8349: 
                   8350: 	if (!$what) {
                   8351: 	    return $domain{$name}{'description'};
                   8352: 	}
                   8353: 	return $domain{$name}{$what};
                   8354:     }
1.327     albertel 8355: }
                   8356: 
                   8357: 
1.1       albertel 8358: # ------------------------------------------------------------- Read hosts file
                   8359: {
1.838     albertel 8360:     my %hostname;
1.844     albertel 8361:     my %hostdom;
1.845     albertel 8362:     my %libserv;
1.852     albertel 8363:     my $loaded;
1.888     albertel 8364:     my %name_to_host;
1.852     albertel 8365: 
                   8366:     sub parse_hosts_tab {
                   8367: 	my ($file) = @_;
                   8368: 	foreach my $configline (@$file) {
                   8369: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8370: 	    next if ($configline =~ /^\^/);
                   8371: 	    chomp($configline);
                   8372: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8373: 	    $name=~s/\s//g;
                   8374: 	    if ($id && $domain && $role && $name) {
                   8375: 		$hostname{$id}=$name;
1.888     albertel 8376: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8377: 		$hostdom{$id}=$domain;
                   8378: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8379: 	    }
                   8380: 	}
                   8381:     }
1.864     albertel 8382:     
                   8383:     sub reset_hosts_info {
1.897     albertel 8384: 	&purge_remembered();
1.864     albertel 8385: 	&reset_domain_info();
                   8386: 	&reset_hosts_ip_info();
1.892     albertel 8387: 	undef(%name_to_host);
1.864     albertel 8388: 	undef(%hostname);
                   8389: 	undef(%hostdom);
                   8390: 	undef(%libserv);
                   8391: 	undef($loaded);
                   8392:     }
1.1       albertel 8393: 
1.852     albertel 8394:     sub load_hosts_tab {
1.869     albertel 8395: 	my ($ignore_cache) = @_;
                   8396: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8397: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8398: 	my @config = <$config>;
                   8399: 	&parse_hosts_tab(\@config);
                   8400: 	close($config);
                   8401: 	$loaded=1;
1.1       albertel 8402:     }
1.852     albertel 8403: 
1.838     albertel 8404:     sub hostname {
1.852     albertel 8405: 	&load_hosts_tab() if (!$loaded);
                   8406: 
1.838     albertel 8407: 	my ($lonid) = @_;
                   8408: 	return $hostname{$lonid};
                   8409:     }
1.845     albertel 8410: 
1.838     albertel 8411:     sub all_hostnames {
1.852     albertel 8412: 	&load_hosts_tab() if (!$loaded);
                   8413: 
1.838     albertel 8414: 	return %hostname;
                   8415:     }
1.845     albertel 8416: 
1.888     albertel 8417:     sub all_names {
                   8418: 	&load_hosts_tab() if (!$loaded);
                   8419: 
                   8420: 	return %name_to_host;
                   8421:     }
                   8422: 
1.845     albertel 8423:     sub is_library {
1.852     albertel 8424: 	&load_hosts_tab() if (!$loaded);
                   8425: 
1.845     albertel 8426: 	return exists($libserv{$_[0]});
                   8427:     }
                   8428: 
                   8429:     sub all_library {
1.852     albertel 8430: 	&load_hosts_tab() if (!$loaded);
                   8431: 
1.845     albertel 8432: 	return %libserv;
                   8433:     }
                   8434: 
1.841     albertel 8435:     sub get_servers {
1.852     albertel 8436: 	&load_hosts_tab() if (!$loaded);
                   8437: 
1.841     albertel 8438: 	my ($domain,$type) = @_;
                   8439: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8440: 	                                          : %hostname;
                   8441: 	my %result;
1.842     albertel 8442: 	if (ref($domain) eq 'ARRAY') {
                   8443: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8444: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8445: 		    $result{$host} = $hostname;
                   8446: 		}
                   8447: 	    }
                   8448: 	} else {
                   8449: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8450: 		if ($hostdom{$host} eq $domain) {
                   8451: 		    $result{$host} = $hostname;
                   8452: 		}
1.841     albertel 8453: 	    }
                   8454: 	}
                   8455: 	return %result;
                   8456:     }
1.845     albertel 8457: 
1.844     albertel 8458:     sub host_domain {
1.852     albertel 8459: 	&load_hosts_tab() if (!$loaded);
                   8460: 
1.844     albertel 8461: 	my ($lonid) = @_;
                   8462: 	return $hostdom{$lonid};
                   8463:     }
                   8464: 
1.841     albertel 8465:     sub all_domains {
1.852     albertel 8466: 	&load_hosts_tab() if (!$loaded);
                   8467: 
1.841     albertel 8468: 	my %seen;
                   8469: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8470: 	return @uniq;
                   8471:     }
1.1       albertel 8472: }
                   8473: 
1.847     albertel 8474: { 
                   8475:     my %iphost;
1.856     albertel 8476:     my %name_to_ip;
                   8477:     my %lonid_to_ip;
1.869     albertel 8478: 
1.847     albertel 8479:     sub get_hosts_from_ip {
                   8480: 	my ($ip) = @_;
                   8481: 	my %iphosts = &get_iphost();
                   8482: 	if (ref($iphosts{$ip})) {
                   8483: 	    return @{$iphosts{$ip}};
                   8484: 	}
                   8485: 	return;
1.839     albertel 8486:     }
1.864     albertel 8487:     
                   8488:     sub reset_hosts_ip_info {
                   8489: 	undef(%iphost);
                   8490: 	undef(%name_to_ip);
                   8491: 	undef(%lonid_to_ip);
                   8492:     }
1.856     albertel 8493: 
                   8494:     sub get_host_ip {
                   8495: 	my ($lonid) = @_;
                   8496: 	if (exists($lonid_to_ip{$lonid})) {
                   8497: 	    return $lonid_to_ip{$lonid};
                   8498: 	}
                   8499: 	my $name=&hostname($lonid);
                   8500:    	my $ip = gethostbyname($name);
                   8501: 	return if (!$ip || length($ip) ne 4);
                   8502: 	$ip=inet_ntoa($ip);
                   8503: 	$name_to_ip{$name}   = $ip;
                   8504: 	$lonid_to_ip{$lonid} = $ip;
                   8505: 	return $ip;
                   8506:     }
1.847     albertel 8507:     
                   8508:     sub get_iphost {
1.869     albertel 8509: 	my ($ignore_cache) = @_;
1.894     albertel 8510: 
1.869     albertel 8511: 	if (!$ignore_cache) {
                   8512: 	    if (%iphost) {
                   8513: 		return %iphost;
                   8514: 	    }
                   8515: 	    my ($ip_info,$cached)=
                   8516: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8517: 	    if ($cached) {
                   8518: 		%iphost      = %{$ip_info->[0]};
                   8519: 		%name_to_ip  = %{$ip_info->[1]};
                   8520: 		%lonid_to_ip = %{$ip_info->[2]};
                   8521: 		return %iphost;
                   8522: 	    }
                   8523: 	}
1.894     albertel 8524: 
                   8525: 	# get yesterday's info for fallback
                   8526: 	my %old_name_to_ip;
                   8527: 	my ($ip_info,$cached)=
                   8528: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8529: 	if ($cached) {
                   8530: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8531: 	}
                   8532: 
1.888     albertel 8533: 	my %name_to_host = &all_names();
                   8534: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8535: 	    my $ip;
                   8536: 	    if (!exists($name_to_ip{$name})) {
                   8537: 		$ip = gethostbyname($name);
                   8538: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8539: 		    if (defined($old_name_to_ip{$name})) {
                   8540: 			$ip = $old_name_to_ip{$name};
                   8541: 			&logthis("Can't find $name defaulting to old $ip");
                   8542: 		    } else {
                   8543: 			&logthis("Name $name no IP found");
                   8544: 			next;
                   8545: 		    }
                   8546: 		} else {
                   8547: 		    $ip=inet_ntoa($ip);
1.847     albertel 8548: 		}
                   8549: 		$name_to_ip{$name} = $ip;
                   8550: 	    } else {
                   8551: 		$ip = $name_to_ip{$name};
1.653     albertel 8552: 	    }
1.888     albertel 8553: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8554: 		$lonid_to_ip{$id} = $ip;
                   8555: 	    }
                   8556: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8557: 	}
1.869     albertel 8558: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8559: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8560: 				      48*60*60);
1.869     albertel 8561: 
1.847     albertel 8562: 	return %iphost;
1.598     albertel 8563:     }
                   8564: }
                   8565: 
1.862     albertel 8566: BEGIN {
                   8567: 
                   8568: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8569:     unless ($readit) {
                   8570: {
                   8571:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8572:     %perlvar = (%perlvar,%{$configvars});
                   8573: }
                   8574: 
                   8575: 
1.1       albertel 8576: # ------------------------------------------------------ Read spare server file
                   8577: {
1.448     albertel 8578:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8579: 
                   8580:     while (my $configline=<$config>) {
                   8581:        chomp($configline);
1.284     matthew  8582:        if ($configline) {
1.784     albertel 8583: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8584: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8585: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8586:        }
                   8587:     }
1.448     albertel 8588:     close($config);
1.1       albertel 8589: }
1.11      www      8590: # ------------------------------------------------------------ Read permissions
                   8591: {
1.448     albertel 8592:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8593: 
                   8594:     while (my $configline=<$config>) {
1.448     albertel 8595: 	chomp($configline);
                   8596: 	if ($configline) {
                   8597: 	    my ($role,$perm)=split(/ /,$configline);
                   8598: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8599: 	}
1.11      www      8600:     }
1.448     albertel 8601:     close($config);
1.11      www      8602: }
                   8603: 
                   8604: # -------------------------------------------- Read plain texts for permissions
                   8605: {
1.448     albertel 8606:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8607: 
                   8608:     while (my $configline=<$config>) {
1.448     albertel 8609: 	chomp($configline);
                   8610: 	if ($configline) {
1.742     raeburn  8611: 	    my ($short,@plain)=split(/:/,$configline);
                   8612:             %{$prp{$short}} = ();
                   8613: 	    if (@plain > 0) {
                   8614:                 $prp{$short}{'std'} = $plain[0];
                   8615:                 for (my $i=1; $i<@plain; $i++) {
                   8616:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8617:                 }
                   8618:             }
1.448     albertel 8619: 	}
1.135     www      8620:     }
1.448     albertel 8621:     close($config);
1.135     www      8622: }
                   8623: 
                   8624: # ---------------------------------------------------------- Read package table
                   8625: {
1.448     albertel 8626:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8627: 
                   8628:     while (my $configline=<$config>) {
1.483     albertel 8629: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8630: 	chomp($configline);
                   8631: 	my ($short,$plain)=split(/:/,$configline);
                   8632: 	my ($pack,$name)=split(/\&/,$short);
                   8633: 	if ($plain ne '') {
                   8634: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8635: 	    $packagetab{$short}=$plain; 
                   8636: 	}
1.11      www      8637:     }
1.448     albertel 8638:     close($config);
1.329     matthew  8639: }
                   8640: 
                   8641: # ------------- set up temporary directory
                   8642: {
                   8643:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8644: 
1.11      www      8645: }
                   8646: 
1.794     albertel 8647: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8648: 				'compress_threshold'=> 20_000,
                   8649:  			        });
1.185     www      8650: 
1.281     www      8651: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8652: $dumpcount=0;
1.22      www      8653: 
1.163     harris41 8654: &logtouch();
1.672     albertel 8655: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8656: $readit=1;
1.564     albertel 8657:     {
                   8658: 	use integer;
                   8659: 	my $test=(2**32)+1;
1.568     albertel 8660: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8661: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8662:     }
1.195     www      8663: }
1.1       albertel 8664: }
1.179     www      8665: 
1.1       albertel 8666: 1;
1.191     harris41 8667: __END__
                   8668: 
1.243     albertel 8669: =pod
                   8670: 
1.191     harris41 8671: =head1 NAME
                   8672: 
1.243     albertel 8673: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8674: 
                   8675: =head1 SYNOPSIS
                   8676: 
1.243     albertel 8677: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8678: 
                   8679:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8680: 
1.243     albertel 8681: Common parameters:
                   8682: 
                   8683: =over 4
                   8684: 
                   8685: =item *
                   8686: 
                   8687: $uname : an internal username (if $cname expecting a course Id specifically)
                   8688: 
                   8689: =item *
                   8690: 
                   8691: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8692: 
                   8693: =item *
                   8694: 
                   8695: $symb : a resource instance identifier
                   8696: 
                   8697: =item *
                   8698: 
                   8699: $namespace : the name of a .db file that contains the data needed or
                   8700: being set.
                   8701: 
                   8702: =back
                   8703: 
1.394     bowersj2 8704: =head1 OVERVIEW
1.191     harris41 8705: 
1.394     bowersj2 8706: lonnet provides subroutines which interact with the
                   8707: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8708: about classes, users, and resources.
1.243     albertel 8709: 
                   8710: For many of these objects you can also use this to store data about
                   8711: them or modify them in various ways.
1.191     harris41 8712: 
1.394     bowersj2 8713: =head2 Symbs
1.191     harris41 8714: 
1.394     bowersj2 8715: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8716: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8717: map, the resource number of the resource in the map, and the URL of
                   8718: the resource itself. The latter is somewhat redundant, but might help
                   8719: if maps change.
                   8720: 
                   8721: An example is
                   8722: 
                   8723:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8724: 
                   8725: The respective map entry is
                   8726: 
                   8727:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8728:   title="Problem 2">
                   8729:  </resource>
                   8730: 
                   8731: Symbs are used by the random number generator, as well as to store and
                   8732: restore data specific to a certain instance of for example a problem.
                   8733: 
                   8734: =head2 Storing And Retrieving Data
                   8735: 
                   8736: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8737: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8738: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8739: is is the non-critical message twin of cstore. These functions are for
                   8740: handlers to store a perl hash to a user's permanent data space in an
                   8741: easy manner, and to retrieve it again on another call. It is expected
                   8742: that a handler would use this once at the beginning to retrieve data,
                   8743: and then again once at the end to send only the new data back.
                   8744: 
                   8745: The data is stored in the user's data directory on the user's
                   8746: homeserver under the ID of the course.
                   8747: 
                   8748: The hash that is returned by restore will have all of the previous
                   8749: value for all of the elements of the hash.
                   8750: 
                   8751: Example:
                   8752: 
                   8753:  #creating a hash
                   8754:  my %hash;
                   8755:  $hash{'foo'}='bar';
                   8756: 
                   8757:  #storing it
                   8758:  &Apache::lonnet::cstore(\%hash);
                   8759: 
                   8760:  #changing a value
                   8761:  $hash{'foo'}='notbar';
                   8762: 
                   8763:  #adding a new value
                   8764:  $hash{'bar'}='foo';
                   8765:  &Apache::lonnet::cstore(\%hash);
                   8766: 
                   8767:  #retrieving the hash
                   8768:  my %history=&Apache::lonnet::restore();
                   8769: 
                   8770:  #print the hash
                   8771:  foreach my $key (sort(keys(%history))) {
                   8772:    print("\%history{$key} = $history{$key}");
                   8773:  }
                   8774: 
                   8775: Will print out:
1.191     harris41 8776: 
1.394     bowersj2 8777:  %history{1:foo} = bar
                   8778:  %history{1:keys} = foo:timestamp
                   8779:  %history{1:timestamp} = 990455579
                   8780:  %history{2:bar} = foo
                   8781:  %history{2:foo} = notbar
                   8782:  %history{2:keys} = foo:bar:timestamp
                   8783:  %history{2:timestamp} = 990455580
                   8784:  %history{bar} = foo
                   8785:  %history{foo} = notbar
                   8786:  %history{timestamp} = 990455580
                   8787:  %history{version} = 2
                   8788: 
                   8789: Note that the special hash entries C<keys>, C<version> and
                   8790: C<timestamp> were added to the hash. C<version> will be equal to the
                   8791: total number of versions of the data that have been stored. The
                   8792: C<timestamp> attribute will be the UNIX time the hash was
                   8793: stored. C<keys> is available in every historical section to list which
                   8794: keys were added or changed at a specific historical revision of a
                   8795: hash.
                   8796: 
                   8797: B<Warning>: do not store the hash that restore returns directly. This
                   8798: will cause a mess since it will restore the historical keys as if the
                   8799: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8800: 
1.394     bowersj2 8801: Calling convention:
1.191     harris41 8802: 
1.394     bowersj2 8803:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8804:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8805: 
1.394     bowersj2 8806: For more detailed information, see lonnet specific documentation.
1.191     harris41 8807: 
1.394     bowersj2 8808: =head1 RETURN MESSAGES
1.191     harris41 8809: 
1.394     bowersj2 8810: =over 4
1.191     harris41 8811: 
1.394     bowersj2 8812: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8813: 
1.394     bowersj2 8814: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8815: when the connection is brought back up
1.191     harris41 8816: 
1.394     bowersj2 8817: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8818: for later delivery
1.191     harris41 8819: 
1.394     bowersj2 8820: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8821: 
1.394     bowersj2 8822: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8823: that was requested
1.191     harris41 8824: 
1.243     albertel 8825: =back
1.191     harris41 8826: 
1.243     albertel 8827: =head1 PUBLIC SUBROUTINES
1.191     harris41 8828: 
1.243     albertel 8829: =head2 Session Environment Functions
1.191     harris41 8830: 
1.243     albertel 8831: =over 4
1.191     harris41 8832: 
1.394     bowersj2 8833: =item * 
                   8834: X<appenv()>
                   8835: B<appenv(%hash)>: the value of %hash is written to
                   8836: the user envirnoment file, and will be restored for each access this
1.620     albertel 8837: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8838: process
1.191     harris41 8839: 
                   8840: =item *
1.394     bowersj2 8841: X<delenv()>
                   8842: B<delenv($regexp)>: removes all items from the session
                   8843: environment file that matches the regular expression in $regexp. The
1.620     albertel 8844: values are also delted from the current processes %env.
1.191     harris41 8845: 
1.795     albertel 8846: =item * get_env_multiple($name) 
                   8847: 
                   8848: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8849: values may be defined and end up as an array ref.
                   8850: 
                   8851: returns an array of values
                   8852: 
1.243     albertel 8853: =back
                   8854: 
                   8855: =head2 User Information
1.191     harris41 8856: 
1.243     albertel 8857: =over 4
1.191     harris41 8858: 
                   8859: =item *
1.394     bowersj2 8860: X<queryauthenticate()>
                   8861: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8862: authentication scheme
                   8863: 
                   8864: =item *
1.394     bowersj2 8865: X<authenticate()>
                   8866: B<authenticate($uname,$upass,$udom)>: try to
                   8867: authenticate user from domain's lib servers (first use the current
                   8868: one). C<$upass> should be the users password.
1.191     harris41 8869: 
                   8870: =item *
1.394     bowersj2 8871: X<homeserver()>
                   8872: B<homeserver($uname,$udom)>: find the server which has
                   8873: the user's directory and files (there must be only one), this caches
                   8874: the answer, and also caches if there is a borken connection.
1.191     harris41 8875: 
                   8876: =item *
1.394     bowersj2 8877: X<idget()>
                   8878: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8879: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8880: username, and only 1 username per ID in a specific domain) (returns
                   8881: hash: id=>name,id=>name)
1.191     harris41 8882: 
                   8883: =item *
1.394     bowersj2 8884: X<idrget()>
                   8885: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8886: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8887: 
                   8888: =item *
1.394     bowersj2 8889: X<idput()>
                   8890: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8891: 
                   8892: =item *
1.394     bowersj2 8893: X<rolesinit()>
                   8894: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8895: 
                   8896: =item *
1.551     albertel 8897: X<getsection()>
                   8898: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8899: course $cname, return section name/number or '' for "not in course"
                   8900: and '-1' for "no section"
                   8901: 
                   8902: =item *
1.394     bowersj2 8903: X<userenvironment()>
                   8904: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8905: passed in @what from the requested user's environment, returns a hash
                   8906: 
1.858     raeburn  8907: =item * 
                   8908: X<userlog_query()>
1.859     albertel 8909: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8910: activity.log file. %filters defines filters applied when parsing the
                   8911: log file. These can be start or end timestamps, or the type of action
                   8912: - log to look for Login or Logout events, check for Checkin or
                   8913: Checkout, role for role selection. The response is in the form
                   8914: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8915: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8916: 
1.243     albertel 8917: =back
                   8918: 
                   8919: =head2 User Roles
                   8920: 
                   8921: =over 4
                   8922: 
                   8923: =item *
                   8924: 
1.810     raeburn  8925: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8926:  F: full access
                   8927:  U,I,K: authentication modes (cxx only)
                   8928:  '': forbidden
                   8929:  1: user needs to choose course
                   8930:  2: browse allowed
1.766     albertel 8931:  A: passphrase authentication needed
1.243     albertel 8932: 
                   8933: =item *
                   8934: 
                   8935: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8936: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8937: and course level
                   8938: 
                   8939: =item *
                   8940: 
                   8941: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8942: explanation of a user role term
                   8943: 
1.832     raeburn  8944: =item *
                   8945: 
1.935     raeburn  8946: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  8947: All arguments are optional. Returns a hash of a roles, either for
                   8948: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8949: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  8950: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   8951: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   8952: For each key, value is set to colon-separated start and end times for
                   8953: the role.  If no username and domain are specified, will default to
1.934     raeburn  8954: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  8955: of role statuses (active, future or previous), roles 
                   8956: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8957: to restrict the list of roles reported. If no array ref is 
                   8958: provided for types, will default to return only active roles.
1.834     albertel 8959: 
1.243     albertel 8960: =back
                   8961: 
                   8962: =head2 User Modification
                   8963: 
                   8964: =over 4
                   8965: 
                   8966: =item *
                   8967: 
                   8968: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8969: user for the level given by URL.  Optional start and end dates (leave empty
                   8970: string or zero for "no date")
1.191     harris41 8971: 
                   8972: =item *
                   8973: 
1.243     albertel 8974: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8975: change a users, password, possible return values are: ok,
                   8976: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8977: refused
1.191     harris41 8978: 
                   8979: =item *
                   8980: 
1.243     albertel 8981: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8982: 
                   8983: =item *
                   8984: 
1.243     albertel 8985: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8986: modify user
1.191     harris41 8987: 
                   8988: =item *
                   8989: 
1.286     matthew  8990: modifystudent
                   8991: 
                   8992: modify a students enrollment and identification information.
                   8993: The course id is resolved based on the current users environment.  
                   8994: This means the envoking user must be a course coordinator or otherwise
                   8995: associated with a course.
                   8996: 
1.297     matthew  8997: This call is essentially a wrapper for lonnet::modifyuser and
                   8998: lonnet::modify_student_enrollment
1.286     matthew  8999: 
                   9000: Inputs: 
                   9001: 
                   9002: =over 4
                   9003: 
                   9004: =item B<$udom> Students loncapa domain
                   9005: 
                   9006: =item B<$uname> Students loncapa login name
                   9007: 
                   9008: =item B<$uid> Students id/student number
                   9009: 
                   9010: =item B<$umode> Students authentication mode
                   9011: 
                   9012: =item B<$upass> Students password
                   9013: 
                   9014: =item B<$first> Students first name
                   9015: 
                   9016: =item B<$middle> Students middle name
                   9017: 
                   9018: =item B<$last> Students last name
                   9019: 
                   9020: =item B<$gene> Students generation
                   9021: 
                   9022: =item B<$usec> Students section in course
                   9023: 
                   9024: =item B<$end> Unix time of the roles expiration
                   9025: 
                   9026: =item B<$start> Unix time of the roles start date
                   9027: 
                   9028: =item B<$forceid> If defined, allow $uid to be changed
                   9029: 
                   9030: =item B<$desiredhome> server to use as home server for student
                   9031: 
                   9032: =back
1.297     matthew  9033: 
                   9034: =item *
                   9035: 
                   9036: modify_student_enrollment
                   9037: 
                   9038: Change a students enrollment status in a class.  The environment variable
                   9039: 'role.request.course' must be defined for this function to proceed.
                   9040: 
                   9041: Inputs:
                   9042: 
                   9043: =over 4
                   9044: 
                   9045: =item $udom, students domain
                   9046: 
                   9047: =item $uname, students name
                   9048: 
                   9049: =item $uid, students user id
                   9050: 
                   9051: =item $first, students first name
                   9052: 
                   9053: =item $middle
                   9054: 
                   9055: =item $last
                   9056: 
                   9057: =item $gene
                   9058: 
                   9059: =item $usec
                   9060: 
                   9061: =item $end
                   9062: 
                   9063: =item $start
                   9064: 
                   9065: =back
                   9066: 
1.191     harris41 9067: 
                   9068: =item *
                   9069: 
1.243     albertel 9070: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9071: custom role; give a custom role to a user for the level given by URL.  Specify
                   9072: name and domain of role author, and role name
1.191     harris41 9073: 
                   9074: =item *
                   9075: 
1.243     albertel 9076: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9077: 
                   9078: =item *
                   9079: 
1.243     albertel 9080: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9081: 
                   9082: =back
                   9083: 
                   9084: =head2 Course Infomation
                   9085: 
                   9086: =over 4
1.191     harris41 9087: 
                   9088: =item *
                   9089: 
1.631     albertel 9090: coursedescription($courseid) : returns a hash of information about the
                   9091: specified course id, including all environment settings for the
                   9092: course, the description of the course will be in the hash under the
                   9093: key 'description'
1.191     harris41 9094: 
                   9095: =item *
                   9096: 
1.624     albertel 9097: resdata($name,$domain,$type,@which) : request for current parameter
                   9098: setting for a specific $type, where $type is either 'course' or 'user',
                   9099: @what should be a list of parameters to ask about. This routine caches
                   9100: answers for 5 minutes.
1.243     albertel 9101: 
1.877     foxr     9102: =item *
                   9103: 
                   9104: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9105: data base, returning a hash that is keyed by the resource name and has
                   9106: values that are the resource value.  I believe that the timestamps and
                   9107: versions are also returned.
                   9108: 
                   9109: 
1.243     albertel 9110: =back
                   9111: 
                   9112: =head2 Course Modification
                   9113: 
                   9114: =over 4
1.191     harris41 9115: 
                   9116: =item *
                   9117: 
1.243     albertel 9118: writecoursepref($courseid,%prefs) : write preferences (environment
                   9119: database) for a course
1.191     harris41 9120: 
                   9121: =item *
                   9122: 
1.243     albertel 9123: createcourse($udom,$description,$url) : make/modify course
                   9124: 
                   9125: =back
                   9126: 
                   9127: =head2 Resource Subroutines
                   9128: 
                   9129: =over 4
1.191     harris41 9130: 
                   9131: =item *
                   9132: 
1.243     albertel 9133: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9134: 
                   9135: =item *
                   9136: 
1.243     albertel 9137: repcopy($filename) : subscribes to the requested file, and attempts to
                   9138: replicate from the owning library server, Might return
1.607     raeburn  9139: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9140: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9141: resource. Expects the local filesystem pathname
                   9142: (/home/httpd/html/res/....)
                   9143: 
                   9144: =back
                   9145: 
                   9146: =head2 Resource Information
                   9147: 
                   9148: =over 4
1.191     harris41 9149: 
                   9150: =item *
                   9151: 
1.243     albertel 9152: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9153: a vairety of different possible values, $varname should be a request
                   9154: string, and the other parameters can be used to specify who and what
                   9155: one is asking about.
                   9156: 
                   9157: Possible values for $varname are environment.lastname (or other item
                   9158: from the envirnment hash), user.name (or someother aspect about the
                   9159: user), resource.0.maxtries (or some other part and parameter of a
                   9160: resource)
1.204     albertel 9161: 
                   9162: =item *
                   9163: 
1.243     albertel 9164: directcondval($number) : get current value of a condition; reads from a state
                   9165: string
1.204     albertel 9166: 
                   9167: =item *
                   9168: 
1.243     albertel 9169: condval($condidx) : value of condition index based on state
1.204     albertel 9170: 
                   9171: =item *
                   9172: 
1.243     albertel 9173: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9174: resource's metadata, $what should be either a specific key, or either
                   9175: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9176: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9177: 
                   9178: this function automatically caches all requests
1.191     harris41 9179: 
                   9180: =item *
                   9181: 
1.243     albertel 9182: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9183: network of library servers; returns file handle of where SQL and regex results
                   9184: will be stored for query
1.191     harris41 9185: 
                   9186: =item *
                   9187: 
1.243     albertel 9188: symbread($filename) : return symbolic list entry (filename argument optional);
                   9189: returns the data handle
1.191     harris41 9190: 
                   9191: =item *
                   9192: 
1.243     albertel 9193: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9194: a possible symb for the URL in $thisfn, and if is an encryypted
                   9195: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9196: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9197: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9198: 
1.191     harris41 9199: 
                   9200: =item *
                   9201: 
1.243     albertel 9202: symbclean($symb) : removes versions numbers from a symb, returns the
                   9203: cleaned symb
1.191     harris41 9204: 
                   9205: =item *
                   9206: 
1.243     albertel 9207: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9208: course map, user must be in a course for it to work.
1.191     harris41 9209: 
                   9210: =item *
                   9211: 
1.243     albertel 9212: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9213: 
                   9214: =item *
                   9215: 
1.243     albertel 9216: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9217: a random seed, all arguments are optional, if they aren't sent it uses the
                   9218: environment to derive them. Note: if symb isn't sent and it can't get one
                   9219: from &symbread it will use the current time as its return value
1.191     harris41 9220: 
                   9221: =item *
                   9222: 
1.243     albertel 9223: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9224: unfakeable, receipt
1.191     harris41 9225: 
                   9226: =item *
                   9227: 
1.620     albertel 9228: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9229: 
                   9230: =item *
                   9231: 
1.243     albertel 9232: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9233: 
                   9234: =item *
                   9235: 
1.243     albertel 9236: 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 9237: 
                   9238: =item *
                   9239: 
1.243     albertel 9240: 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 9241: 
                   9242: =item *
                   9243: 
1.243     albertel 9244: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9245: 
                   9246: =item *
                   9247: 
1.243     albertel 9248: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9249: forcing spreadsheet to reevaluate the resource scores next time.
                   9250: 
                   9251: =back
                   9252: 
                   9253: =head2 Storing/Retreiving Data
                   9254: 
                   9255: =over 4
1.191     harris41 9256: 
                   9257: =item *
                   9258: 
1.243     albertel 9259: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9260: for this url; hashref needs to be given and should be a \%hashname; the
                   9261: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9262: be derived from the env
1.191     harris41 9263: 
                   9264: =item *
                   9265: 
1.243     albertel 9266: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9267: uses critical subroutine
1.191     harris41 9268: 
                   9269: =item *
                   9270: 
1.243     albertel 9271: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9272: all args are optional
1.191     harris41 9273: 
                   9274: =item *
                   9275: 
1.717     albertel 9276: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9277: dumps the complete (or key matching regexp) namespace into a hash
                   9278: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9279: normally &store()ed into
                   9280: 
                   9281: $range should be either an integer '100' (give me the first 100
                   9282:                                            matching records)
                   9283:               or be  two integers sperated by a - with no spaces
                   9284:                  '30-50' (give me the 30th through the 50th matching
                   9285:                           records)
                   9286: 
                   9287: 
                   9288: =item *
                   9289: 
                   9290: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9291: replaces a &store() version of data with a replacement set of data
                   9292: for a particular resource in a namespace passed in the $storehash hash 
                   9293: reference
                   9294: 
                   9295: =item *
                   9296: 
1.243     albertel 9297: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9298: works very similar to store/cstore, but all data is stored in a
                   9299: temporary location and can be reset using tmpreset, $storehash should
                   9300: be a hash reference, returns nothing on success
1.191     harris41 9301: 
                   9302: =item *
                   9303: 
1.243     albertel 9304: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9305: similar to restore, but all data is stored in a temporary location and
                   9306: can be reset using tmpreset. Returns a hash of values on success,
                   9307: error string otherwise.
1.191     harris41 9308: 
                   9309: =item *
                   9310: 
1.243     albertel 9311: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9312: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9313: 
                   9314: =item *
                   9315: 
1.243     albertel 9316: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9317: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9318: 
                   9319: =item *
                   9320: 
1.243     albertel 9321: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9322: namesp ($udom and $uname are optional)
1.191     harris41 9323: 
                   9324: =item *
                   9325: 
1.702     albertel 9326: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9327: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9328: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9329: 
1.702     albertel 9330: $range should be either an integer '100' (give me the first 100
                   9331:                                            matching records)
                   9332:               or be  two integers sperated by a - with no spaces
                   9333:                  '30-50' (give me the 30th through the 50th matching
                   9334:                           records)
1.449     matthew  9335: =item *
                   9336: 
                   9337: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9338: $store can be a scalar, an array reference, or if the amount to be 
                   9339: incremented is > 1, a hash reference.
                   9340: 
                   9341: ($udom and $uname are optional)
1.191     harris41 9342: 
                   9343: =item *
                   9344: 
1.243     albertel 9345: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9346: ($udom and $uname are optional)
1.191     harris41 9347: 
                   9348: =item *
                   9349: 
1.243     albertel 9350: cput($namespace,$storehash,$udom,$uname) : critical put
                   9351: ($udom and $uname are optional)
1.191     harris41 9352: 
                   9353: =item *
                   9354: 
1.748     albertel 9355: newput($namespace,$storehash,$udom,$uname) :
                   9356: 
                   9357: Attempts to store the items in the $storehash, but only if they don't
                   9358: currently exist, if this succeeds you can be certain that you have 
                   9359: successfully created a new key value pair in the $namespace db.
                   9360: 
                   9361: 
                   9362: Args:
                   9363:  $namespace: name of database to store values to
                   9364:  $storehash: hashref to store to the db
                   9365:  $udom: (optional) domain of user containing the db
                   9366:  $uname: (optional) name of user caontaining the db
                   9367: 
                   9368: Returns:
                   9369:  'ok' -> succeeded in storing all keys of $storehash
                   9370:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9371:                         least <key> already existed in the db (other
                   9372:                         requested keys may also already exist)
                   9373:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9374:  'con_lost' -> unable to contact request server
                   9375:  'refused' -> action was not allowed by remote machine
                   9376: 
                   9377: 
                   9378: =item *
                   9379: 
1.243     albertel 9380: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9381: reference filled in from namesp (encrypts the return communication)
                   9382: ($udom and $uname are optional)
1.191     harris41 9383: 
                   9384: =item *
                   9385: 
1.243     albertel 9386: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9387: critical subroutine
                   9388: 
1.806     raeburn  9389: =item *
                   9390: 
1.860     raeburn  9391: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9392: array reference filled in from namespace found in domain level on either
                   9393: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9394: 
                   9395: =item *
                   9396: 
1.860     raeburn  9397: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9398: domain level either on specified domain server ($uhome) or primary domain 
                   9399: server ($udom and $uhome are optional)
1.806     raeburn  9400: 
1.943   ! raeburn  9401: =item * 
        !          9402: 
        !          9403: get_domain_defaults($target_domain) : returns hash with defaults for
        !          9404: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
        !          9405: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
        !          9406: or localauth), initial password or a kerberos realm, language (e.g., en-us).
        !          9407: Values are retrieved from cache (if current), or from domain's configuration.db
        !          9408: (if available), or lastly from values in lonTabs/dns_domain,tab, 
        !          9409: or lonTabs/domain.tab. 
        !          9410: 
        !          9411: %domdefaults = &get_auth_defaults($target_domain);
        !          9412: 
1.243     albertel 9413: =back
                   9414: 
                   9415: =head2 Network Status Functions
                   9416: 
                   9417: =over 4
1.191     harris41 9418: 
                   9419: =item *
                   9420: 
                   9421: dirlist($uri) : return directory list based on URI
                   9422: 
                   9423: =item *
                   9424: 
1.243     albertel 9425: spareserver() : find server with least workload from spare.tab
                   9426: 
                   9427: =back
                   9428: 
                   9429: =head2 Apache Request
                   9430: 
                   9431: =over 4
1.191     harris41 9432: 
                   9433: =item *
                   9434: 
1.243     albertel 9435: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9436: localhost, posts hash
                   9437: 
                   9438: =back
                   9439: 
                   9440: =head2 Data to String to Data
                   9441: 
                   9442: =over 4
1.191     harris41 9443: 
                   9444: =item *
                   9445: 
1.243     albertel 9446: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9447: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9448: 
                   9449: =item *
                   9450: 
1.243     albertel 9451: hashref2str($hashref) : convert a hashref into a string complete with
                   9452: escaping and '=' and '&' separators, supports elements that are
                   9453: arrayrefs and hashrefs
1.191     harris41 9454: 
                   9455: =item *
                   9456: 
1.243     albertel 9457: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9458: with escaping and '&' separators, supports elements that are arrayrefs
                   9459: and hashrefs
1.191     harris41 9460: 
                   9461: =item *
                   9462: 
1.243     albertel 9463: str2hash($string) : convert string to hash using unescaping and
                   9464: splitting on '=' and '&', supports elements that are arrayrefs and
                   9465: hashrefs
1.191     harris41 9466: 
                   9467: =item *
                   9468: 
1.243     albertel 9469: str2array($string) : convert string to hash using unescaping and
                   9470: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9471: 
                   9472: =back
                   9473: 
                   9474: =head2 Logging Routines
                   9475: 
                   9476: =over 4
                   9477: 
                   9478: These routines allow one to make log messages in the lonnet.log and
                   9479: lonnet.perm logfiles.
1.191     harris41 9480: 
                   9481: =item *
                   9482: 
1.243     albertel 9483: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9484: 
                   9485: =item *
                   9486: 
1.243     albertel 9487: logthis() : append message to the normal lonnet.log file, it gets
                   9488: preiodically rolled over and deleted.
1.191     harris41 9489: 
                   9490: =item *
                   9491: 
1.243     albertel 9492: logperm() : append a permanent message to lonnet.perm.log, this log
                   9493: file never gets deleted by any automated portion of the system, only
                   9494: messages of critical importance should go in here.
                   9495: 
                   9496: =back
                   9497: 
                   9498: =head2 General File Helper Routines
                   9499: 
                   9500: =over 4
1.191     harris41 9501: 
                   9502: =item *
                   9503: 
1.481     raeburn  9504: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9505: (a) files in /uploaded
                   9506:   (i) If a local copy of the file exists - 
                   9507:       compares modification date of local copy with last-modified date for 
                   9508:       definitive version stored on home server for course. If local copy is 
                   9509:       stale, requests a new version from the home server and stores it. 
                   9510:       If the original has been removed from the home server, then local copy 
                   9511:       is unlinked.
                   9512:   (ii) If local copy does not exist -
                   9513:       requests the file from the home server and stores it. 
                   9514:   
                   9515:   If $caller is 'uploadrep':  
                   9516:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9517:     for request for files originally uploaded via DOCS. 
                   9518:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9519:   
                   9520:   Otherwise:
                   9521:      This indicates a call from the content generation phase of the request.
                   9522:      -  returns the entire contents of the file or -1.
                   9523:      
                   9524: (b) files in /res
                   9525:    - returns the entire contents of a file or -1; 
                   9526:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9527: 
1.712     albertel 9528: 
                   9529: =item *
                   9530: 
                   9531: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9532:                   reference
                   9533: 
                   9534: returns either a stat() list of data about the file or an empty list
                   9535: if the file doesn't exist or couldn't find out about it (connection
                   9536: problems or user unknown)
                   9537: 
1.191     harris41 9538: =item *
                   9539: 
1.243     albertel 9540: filelocation($dir,$file) : returns file system location of a file
                   9541: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9542: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9543: and a file of ../bob will become /a/bob)
1.191     harris41 9544: 
                   9545: =item *
                   9546: 
                   9547: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9548: filelocation except for hrefs
                   9549: 
                   9550: =item *
                   9551: 
                   9552: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9553: 
1.243     albertel 9554: =back
                   9555: 
1.608     albertel 9556: =head2 Usererfile file routines (/uploaded*)
                   9557: 
                   9558: =over 4
                   9559: 
                   9560: =item *
                   9561: 
                   9562: userfileupload(): main rotine for putting a file in a user or course's
                   9563:                   filespace, arguments are,
                   9564: 
1.620     albertel 9565:  formname - required - this is the name of the element in $env where the
1.608     albertel 9566:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9567:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9568:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9569:  coursedoc - if true, store the file in the course of the active role
                   9570:              of the current user
                   9571:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9572:          if undefined, it will be placed in "unknown"
                   9573: 
                   9574:  (This routine calls clean_filename() to remove any dangerous
                   9575:  characters from the filename, and then calls finuserfileupload() to
                   9576:  complete the transaction)
                   9577: 
                   9578:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9579:  and /adm/notfound.html if unsuccessful
                   9580: 
                   9581: =item *
                   9582: 
                   9583: clean_filename(): routine for cleaing a filename up for storage in
                   9584:                  userfile space, argument is:
                   9585: 
                   9586:  filename - proposed filename
                   9587: 
                   9588: returns: the new clean filename
                   9589: 
                   9590: =item *
                   9591: 
                   9592: finishuserfileupload(): routine that creaes and sends the file to
                   9593: userspace, probably shouldn't be called directly
                   9594: 
                   9595:   docuname: username or courseid of destination for the file
                   9596:   docudom: domain of user/course of destination for the file
                   9597:   formname: same as for userfileupload()
                   9598:   fname: filename (inculding subdirectories) for the file
                   9599: 
                   9600:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9601:  and /adm/notfound.html if unsuccessful
                   9602: 
                   9603: =item *
                   9604: 
                   9605: renameuserfile(): renames an existing userfile to a new name
                   9606: 
                   9607:   Args:
                   9608:    docuname: username or courseid of destination for the file
                   9609:    docudom: domain of user/course of destination for the file
                   9610:    old: current file name (including any subdirs under userfiles)
                   9611:    new: desired file name (including any subdirs under userfiles)
                   9612: 
                   9613: =item *
                   9614: 
                   9615: mkdiruserfile(): creates a directory is a userfiles dir
                   9616: 
                   9617:   Args:
                   9618:    docuname: username or courseid of destination for the file
                   9619:    docudom: domain of user/course of destination for the file
                   9620:    dir: dir to create (including any subdirs under userfiles)
                   9621: 
                   9622: =item *
                   9623: 
                   9624: removeuserfile(): removes a file that exists in userfiles
                   9625: 
                   9626:   Args:
                   9627:    docuname: username or courseid of destination for the file
                   9628:    docudom: domain of user/course of destination for the file
                   9629:    fname: filname to delete (including any subdirs under userfiles)
                   9630: 
                   9631: =item *
                   9632: 
                   9633: removeuploadedurl(): convience function for removeuserfile()
                   9634: 
                   9635:   Args:
                   9636:    url:  a full /uploaded/... url to delete
                   9637: 
1.747     albertel 9638: =item * 
                   9639: 
                   9640: get_portfile_permissions():
                   9641:   Args:
                   9642:     domain: domain of user or course contain the portfolio files
                   9643:     user: name of user or num of course contain the portfolio files
                   9644:   Returns:
                   9645:     hashref of a dump of the proper file_permissions.db
                   9646:    
                   9647: 
                   9648: =item * 
                   9649: 
                   9650: get_access_controls():
                   9651: 
                   9652: Args:
                   9653:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9654:   group: (optional) the group you want the files associated with
                   9655:   file: (optional) the file you want access info on
                   9656: 
                   9657: Returns:
1.749     raeburn  9658:     a hash (keys are file names) of hashes containing
                   9659:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9660:         values are XML containing access control settings (see below) 
1.747     albertel 9661: 
                   9662: Internal notes:
                   9663: 
1.749     raeburn  9664:  access controls are stored in file_permissions.db as key=value pairs.
                   9665:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9666:         where scope -> public,guest,course,group,domains or users.
                   9667:               end -> UNIX time for end of access (0 -> no end date)
                   9668:               start -> UNIX time for start of access
                   9669: 
                   9670:     value -> XML description of access control
                   9671:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9672:             <start></start>
                   9673:             <end></end>
                   9674: 
                   9675:             <password></password>  for scope type = guest
                   9676: 
                   9677:             <domain></domain>     for scope type = course or group
                   9678:             <number></number>
                   9679:             <roles id="">
                   9680:              <role></role>
                   9681:              <access></access>
                   9682:              <section></section>
                   9683:              <group></group>
                   9684:             </roles>
                   9685: 
                   9686:             <dom></dom>         for scope type = domains
                   9687: 
                   9688:             <users>             for scope type = users
                   9689:              <user>
                   9690:               <uname></uname>
                   9691:               <udom></udom>
                   9692:              </user>
                   9693:             </users>
                   9694:            </scope> 
                   9695:               
                   9696:  Access data is also aggregated for each file in an additional key=value pair:
                   9697:  key -> path to file/file_name\0accesscontrol 
                   9698:  value -> reference to hash
                   9699:           hash contains key = value pairs
                   9700:           where key = uniqueID:scope_end_start
                   9701:                 value = UNIX time record was last updated
                   9702: 
                   9703:           Used to improve speed of look-ups of access controls for each file.  
                   9704:  
                   9705:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9706: 
                   9707: modify_access_controls():
                   9708: 
                   9709: Modifies access controls for a portfolio file
                   9710: Args
                   9711: 1. file name
                   9712: 2. reference to hash of required changes,
                   9713: 3. domain
                   9714: 4. username
                   9715:   where domain,username are the domain of the portfolio owner 
                   9716:   (either a user or a course) 
                   9717: 
                   9718: Returns:
                   9719: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9720: 2. result of deletions ('ok' or 'error', with error message).
                   9721: 3. reference to hash of any new or updated access controls.
                   9722: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9723:    key = integer (inbound ID)
                   9724:    value = uniqueID  
1.747     albertel 9725: 
1.608     albertel 9726: =back
                   9727: 
1.243     albertel 9728: =head2 HTTP Helper Routines
                   9729: 
                   9730: =over 4
                   9731: 
1.191     harris41 9732: =item *
                   9733: 
                   9734: escape() : unpack non-word characters into CGI-compatible hex codes
                   9735: 
                   9736: =item *
                   9737: 
                   9738: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9739: 
1.243     albertel 9740: =back
                   9741: 
                   9742: =head1 PRIVATE SUBROUTINES
                   9743: 
                   9744: =head2 Underlying communication routines (Shouldn't call)
                   9745: 
                   9746: =over 4
                   9747: 
                   9748: =item *
                   9749: 
                   9750: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9751: 
                   9752: =item *
                   9753: 
                   9754: reply() : uses subreply to send a message to remote machine, logs all failures
                   9755: 
                   9756: =item *
                   9757: 
                   9758: critical() : passes a critical message to another server; if cannot
                   9759: get through then place message in connection buffer directory and
                   9760: returns con_delayed, if incapable of saving message, returns
                   9761: con_failed
                   9762: 
                   9763: =item *
                   9764: 
                   9765: reconlonc() : tries to reconnect lonc client processes.
                   9766: 
                   9767: =back
                   9768: 
                   9769: =head2 Resource Access Logging
                   9770: 
                   9771: =over 4
                   9772: 
                   9773: =item *
                   9774: 
                   9775: flushcourselogs() : flush (save) buffer logs and access logs
                   9776: 
                   9777: =item *
                   9778: 
                   9779: courselog($what) : save message for course in hash
                   9780: 
                   9781: =item *
                   9782: 
                   9783: courseacclog($what) : save message for course using &courselog().  Perform
                   9784: special processing for specific resource types (problems, exams, quizzes, etc).
                   9785: 
1.191     harris41 9786: =item *
                   9787: 
                   9788: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9789: as a PerlChildExitHandler
1.243     albertel 9790: 
                   9791: =back
                   9792: 
                   9793: =head2 Other
                   9794: 
                   9795: =over 4
                   9796: 
                   9797: =item *
                   9798: 
                   9799: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9800: 
                   9801: =back
                   9802: 
                   9803: =cut
1.877     foxr     9804: 

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