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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.947   ! raeburn     4: # $Id: lonnet.pm,v 1.946 2008/03/09 16:57:26 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.891     albertel  217:     my ($lonid) = @_;
                    218:     my $hostname = &hostname($lonid);
                    219:     if ($lonid) {
                    220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    221: 	if ($hostname && -e $peerfile) {
                    222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    224: 					     Type    => SOCK_STREAM,
                    225: 					     Timeout => 10);
                    226: 	    if ($client) {
                    227: 		print $client ("reset_retries\n");
                    228: 		my $answer=<$client>;
                    229: 		#reset just this one.
                    230: 	    }
                    231: 	}
                    232: 	return;
                    233:     }
                    234: 
1.836     www       235:     &logthis("Trying to reconnect lonc");
1.1       albertel  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  237:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  238: 	my $loncpid=<$fh>;
                    239:         chomp($loncpid);
                    240:         if (kill 0 => $loncpid) {
                    241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    242:             kill USR1 => $loncpid;
                    243:             sleep 1;
1.836     www       244:          } else {
1.12      www       245: 	    &logthis(
1.672     albertel  246:                "<font color=\"blue\">WARNING:".
1.12      www       247:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  248:         }
                    249:     } else {
1.836     www       250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  251:     }
                    252: }
                    253: 
                    254: # ------------------------------------------------------ Critical communication
1.12      www       255: 
1.1       albertel  256: sub critical {
                    257:     my ($cmd,$server)=@_;
1.838     albertel  258:     unless (&hostname($server)) {
1.672     albertel  259:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       260:                " Critical message to unknown server ($server)</font>");
                    261:         return 'no_such_host';
                    262:     }
1.1       albertel  263:     my $answer=reply($cmd,$server);
                    264:     if ($answer eq 'con_lost') {
                    265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  266: 	my $answer=reply($cmd,$server);
1.1       albertel  267:         if ($answer eq 'con_lost') {
                    268:             my $now=time;
                    269:             my $middlename=$cmd;
1.5       www       270:             $middlename=substr($middlename,0,16);
1.1       albertel  271:             $middlename=~s/\W//g;
                    272:             my $dfilename=
1.305     www       273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    274:             $dumpcount++;
1.1       albertel  275:             {
1.448     albertel  276: 		my $dfh;
                    277: 		if (open($dfh,">$dfilename")) {
                    278: 		    print $dfh "$cmd\n"; 
                    279: 		    close($dfh);
                    280: 		}
1.1       albertel  281:             }
                    282:             sleep 2;
                    283:             my $wcmd='';
                    284:             {
1.448     albertel  285: 		my $dfh;
                    286: 		if (open($dfh,"<$dfilename")) {
                    287: 		    $wcmd=<$dfh>; 
                    288: 		    close($dfh);
                    289: 		}
1.1       albertel  290:             }
                    291:             chomp($wcmd);
1.7       www       292:             if ($wcmd eq $cmd) {
1.672     albertel  293: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       294:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  295:                 &logperm("D:$server:$cmd");
                    296: 	        return 'con_delayed';
                    297:             } else {
1.672     albertel  298:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       299:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  300:                 &logperm("F:$server:$cmd");
                    301:                 return 'con_failed';
                    302:             }
                    303:         }
                    304:     }
                    305:     return $answer;
1.405     albertel  306: }
                    307: 
1.755     albertel  308: # ------------------------------------------- check if return value is an error
                    309: 
                    310: sub error {
                    311:     my ($result) = @_;
1.756     albertel  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  313: 	if ($2 == 2) { return undef; }
                    314: 	return $1;
                    315:     }
                    316:     return undef;
                    317: }
                    318: 
1.783     albertel  319: sub convert_and_load_session_env {
                    320:     my ($lonidsdir,$handle)=@_;
                    321:     my @profile;
                    322:     {
1.917     albertel  323: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    324: 	if (!$opened) {
1.915     albertel  325: 	    return 0;
                    326: 	}
1.783     albertel  327: 	flock($idf,LOCK_SH);
                    328: 	@profile=<$idf>;
                    329: 	close($idf);
                    330:     }
                    331:     my %temp_env;
                    332:     foreach my $line (@profile) {
1.786     albertel  333: 	if ($line !~ m/=/) {
                    334: 	    return 0;
                    335: 	}
1.783     albertel  336: 	chomp($line);
                    337: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    338: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    339:     }
                    340:     unlink("$lonidsdir/$handle.id");
                    341:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    342: 	    0640)) {
                    343: 	%disk_env = %temp_env;
                    344: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    345: 	untie(%disk_env);
                    346:     }
1.786     albertel  347:     return 1;
1.783     albertel  348: }
                    349: 
1.374     www       350: # ------------------------------------------- Transfer profile into environment
1.780     albertel  351: my $env_loaded;
                    352: sub transfer_profile_to_env {
1.788     albertel  353:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    354:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       355: 
1.720     albertel  356:     if (!defined($lonidsdir)) {
                    357: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    358:     }
                    359:     if (!defined($handle)) {
                    360:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    361:     }
                    362: 
1.786     albertel  363:     my $convert;
                    364:     {
1.917     albertel  365:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    366: 	if (!$opened) {
1.915     albertel  367: 	    return;
                    368: 	}
1.786     albertel  369: 	flock($idf,LOCK_SH);
                    370: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    371: 		&GDBM_READER(),0640)) {
                    372: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    373: 	    untie(%disk_env);
                    374: 	} else {
                    375: 	    $convert = 1;
                    376: 	}
                    377:     }
                    378:     if ($convert) {
                    379: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    380: 	    &logthis("Failed to load session, or convert session.");
                    381: 	}
1.374     www       382:     }
1.783     albertel  383: 
1.786     albertel  384:     my %remove;
1.783     albertel  385:     while ( my $envname = each(%env) ) {
1.433     matthew   386:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    387:             if ($time < time-300) {
1.783     albertel  388:                 $remove{$key}++;
1.433     matthew   389:             }
                    390:         }
                    391:     }
1.783     albertel  392: 
1.619     albertel  393:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  394:     $env_loaded=1;
1.783     albertel  395:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   396:         &delenv($expired_key);
1.374     www       397:     }
1.1       albertel  398: }
                    399: 
1.916     albertel  400: # ---------------------------------------------------- Check for valid session 
                    401: sub check_for_valid_session {
                    402:     my ($r) = @_;
                    403:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    404:     my $lonid=$cookies{'lonID'};
                    405:     return undef if (!$lonid);
                    406: 
                    407:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    408:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    409:     return undef if (!-e "$lonidsdir/$handle.id");
                    410: 
1.917     albertel  411:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    412:     return undef if (!$opened);
1.916     albertel  413: 
                    414:     flock($idf,LOCK_SH);
                    415:     my %disk_env;
                    416:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    417: 	    &GDBM_READER(),0640)) {
                    418: 	return undef;	
                    419:     }
                    420: 
                    421:     if (!defined($disk_env{'user.name'})
                    422: 	|| !defined($disk_env{'user.domain'})) {
                    423: 	return undef;
                    424:     }
                    425:     return $handle;
                    426: }
                    427: 
1.830     albertel  428: sub timed_flock {
                    429:     my ($file,$lock_type) = @_;
                    430:     my $failed=0;
                    431:     eval {
                    432: 	local $SIG{__DIE__}='DEFAULT';
                    433: 	local $SIG{ALRM}=sub {
                    434: 	    $failed=1;
                    435: 	    die("failed lock");
                    436: 	};
                    437: 	alarm(13);
                    438: 	flock($file,$lock_type);
                    439: 	alarm(0);
                    440:     };
                    441:     if ($failed) {
                    442: 	return undef;
                    443:     } else {
                    444: 	return 1;
                    445:     }
                    446: }
                    447: 
1.5       www       448: # ---------------------------------------------------------- Append Environment
                    449: 
                    450: sub appenv {
1.6       www       451:     my %newenv=@_;
1.692     albertel  452:     foreach my $key (keys(%newenv)) {
                    453: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  454:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  455:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       456:                 .'</font>');
1.692     albertel  457: 	    delete($newenv{$key});
1.35      www       458:         } else {
1.692     albertel  459:             $env{$key}=$newenv{$key};
1.35      www       460:         }
1.191     harris41  461:     }
1.917     albertel  462:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    463:     if ($opened
1.915     albertel  464: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  465: 	&&
                    466: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    467: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  468: 	while (my ($key,$value) = each(%newenv)) {
                    469: 	    $disk_env{$key} = $value;
1.448     albertel  470: 	}
1.783     albertel  471: 	untie(%disk_env);
1.56      www       472:     }
                    473:     return 'ok';
                    474: }
                    475: # ----------------------------------------------------- Delete from Environment
                    476: 
                    477: sub delenv {
                    478:     my $delthis=shift;
                    479:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  480:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       481:                 "Attempt to delete from environment ".$delthis);
                    482:         return 'error';
                    483:     }
1.917     albertel  484:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    485:     if ($opened
1.915     albertel  486: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  487: 	&&
                    488: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    489: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  490: 	foreach my $key (keys(%disk_env)) {
                    491: 	    if ($key=~/^$delthis/) { 
1.915     albertel  492: 		delete($env{$key});
                    493: 		delete($disk_env{$key});
                    494: 	    }
1.448     albertel  495: 	}
1.783     albertel  496: 	untie(%disk_env);
1.5       www       497:     }
                    498:     return 'ok';
1.369     albertel  499: }
                    500: 
1.790     albertel  501: sub get_env_multiple {
                    502:     my ($name) = @_;
                    503:     my @values;
                    504:     if (defined($env{$name})) {
                    505:         # exists is it an array
                    506:         if (ref($env{$name})) {
                    507:             @values=@{ $env{$name} };
                    508:         } else {
                    509:             $values[0]=$env{$name};
                    510:         }
                    511:     }
                    512:     return(@values);
                    513: }
                    514: 
1.369     albertel  515: # ------------------------------------------ Find out current server userload
                    516: 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.945     raeburn  1067:                 } elsif ($item eq 'selfcreate') {
                   1068:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  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.
1.944     foxr     1695: # Returns:
                   1696: #   Scalar context: The content of the reply.
                   1697: #   Array context:  2 element list of the content and the full response variable.
1.942     foxr     1698: #     
                   1699: # Returns:
                   1700: #    The content of the response.
1.15      www      1701: sub ssi {
                   1702: 
1.944     foxr     1703:     my ($fn,%form)=@_;
                   1704:     my $count = scalar(@_);
                   1705:     
1.15      www      1706: 
                   1707:     my $ua=new LWP::UserAgent;
1.23      www      1708:     
                   1709:     my $request;
1.711     albertel 1710: 
                   1711:     $form{'no_update_last_known'}=1;
1.895     albertel 1712:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1713:     if (%form) {
1.782     albertel 1714:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1715:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1716:     } else {
1.782     albertel 1717:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1718:     }
                   1719: 
1.15      www      1720:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1721:     my $response=$ua->request($request);
1.944     foxr     1722:     my $status = $response->code;
1.15      www      1723: 
1.944     foxr     1724:     if (wantarray) {
                   1725: 	return ($response->content, $response);
                   1726:     } else {
                   1727: 	return $response->content;
1.942     foxr     1728:     }
1.324     www      1729: }
                   1730: 
                   1731: sub externalssi {
                   1732:     my ($url)=@_;
                   1733:     my $ua=new LWP::UserAgent;
                   1734:     my $request=new HTTP::Request('GET',$url);
                   1735:     my $response=$ua->request($request);
1.15      www      1736:     return $response->content;
                   1737: }
1.254     www      1738: 
1.492     albertel 1739: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1740: 
                   1741: sub allowuploaded {
                   1742:     my ($srcurl,$url)=@_;
                   1743:     $url=&clutter(&declutter($url));
                   1744:     my $dir=$url;
                   1745:     $dir=~s/\/[^\/]+$//;
                   1746:     my %httpref=();
                   1747:     my $httpurl=&hreflocation('',$url);
                   1748:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1749:     &Apache::lonnet::appenv(%httpref);
1.254     www      1750: }
1.477     raeburn  1751: 
1.478     albertel 1752: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1753: # input: action, courseID, current domain, intended
1.637     raeburn  1754: #        path to file, source of file, instruction to parse file for objects,
                   1755: #        ref to hash for embedded objects,
                   1756: #        ref to hash for codebase of java objects.
                   1757: #
1.485     raeburn  1758: # output: url to file (if action was uploaddoc), 
                   1759: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1760: #
1.478     albertel 1761: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1762: # course.
1.477     raeburn  1763: #
1.478     albertel 1764: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1765: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1766: #          course's home server.
1.477     raeburn  1767: #
1.478     albertel 1768: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1769: #          be copied from $source (current location) to 
                   1770: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1771: #         and will then be copied to
                   1772: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1773: #         course's home server.
1.485     raeburn  1774: #
1.481     raeburn  1775: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1776: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1777: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1778: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1779: #         in course's home server.
1.637     raeburn  1780: #
1.477     raeburn  1781: 
                   1782: sub process_coursefile {
1.638     albertel 1783:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1784:     my $fetchresult;
1.638     albertel 1785:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1786:     if ($action eq 'propagate') {
1.638     albertel 1787:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1788: 			     $home);
1.481     raeburn  1789:     } else {
1.477     raeburn  1790:         my $fpath = '';
                   1791:         my $fname = $file;
1.478     albertel 1792:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1793:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1794:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1795:         if ($action eq 'copy') {
                   1796:             if ($source eq '') {
                   1797:                 $fetchresult = 'no source file';
                   1798:                 return $fetchresult;
                   1799:             } else {
                   1800:                 my $destination = $filepath.'/'.$fname;
                   1801:                 rename($source,$destination);
                   1802:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1803:                                  $home);
1.481     raeburn  1804:             }
                   1805:         } elsif ($action eq 'uploaddoc') {
                   1806:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1807:             print $fh $env{'form.'.$source};
1.481     raeburn  1808:             close($fh);
1.637     raeburn  1809:             if ($parser eq 'parse') {
                   1810:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1811:                 unless ($parse_result eq 'ok') {
                   1812:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1813:                 }
                   1814:             }
1.477     raeburn  1815:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1816:                                  $home);
1.481     raeburn  1817:             if ($fetchresult eq 'ok') {
                   1818:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1819:             } else {
                   1820:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1821:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1822:                 return '/adm/notfound.html';
                   1823:             }
1.477     raeburn  1824:         }
                   1825:     }
1.485     raeburn  1826:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1827:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1828:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1829:     }
                   1830:     return $fetchresult;
                   1831: }
                   1832: 
1.637     raeburn  1833: sub build_filepath {
                   1834:     my ($fpath) = @_;
                   1835:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1836:     unless ($fpath eq '') {
                   1837:         my @parts=split('/',$fpath);
                   1838:         foreach my $part (@parts) {
                   1839:             $filepath.= '/'.$part;
                   1840:             if ((-e $filepath)!=1) {
                   1841:                 mkdir($filepath,0777);
                   1842:             }
                   1843:         }
                   1844:     }
                   1845:     return $filepath;
                   1846: }
                   1847: 
                   1848: sub store_edited_file {
1.638     albertel 1849:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1850:     my $file = $primary_url;
                   1851:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1852:     my $fpath = '';
                   1853:     my $fname = $file;
                   1854:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1855:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1856:     my $filepath = &build_filepath($fpath);
                   1857:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1858:     print $fh $content;
                   1859:     close($fh);
1.638     albertel 1860:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1861:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1862: 			  $home);
1.637     raeburn  1863:     if ($$fetchresult eq 'ok') {
                   1864:         return '/uploaded/'.$fpath.'/'.$fname;
                   1865:     } else {
1.638     albertel 1866:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1867: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1868:         return '/adm/notfound.html';
                   1869:     }
                   1870: }
                   1871: 
1.531     albertel 1872: sub clean_filename {
1.831     albertel 1873:     my ($fname,$args)=@_;
1.315     www      1874: # Replace Windows backslashes by forward slashes
1.257     www      1875:     $fname=~s/\\/\//g;
1.831     albertel 1876:     if (!$args->{'keep_path'}) {
                   1877:         # Get rid of everything but the actual filename
                   1878: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1879:     }
1.315     www      1880: # Replace spaces by underscores
                   1881:     $fname=~s/\s+/\_/g;
                   1882: # Replace all other weird characters by nothing
1.831     albertel 1883:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1884: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1885: # numbers
                   1886:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1887:     return $fname;
                   1888: }
                   1889: 
1.608     albertel 1890: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1891: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1892: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1893: #        $coursedoc - if true up to the current course
                   1894: #                     if false
                   1895: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1896: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1897: #        $allfiles - reference to hash for embedded objects
                   1898: #        $codebase - reference to hash for codebase of java objects
                   1899: #        $desuname - username for permanent storage of uploaded file
                   1900: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1901: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1902: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1903: # 
1.686     albertel 1904: # output: url of file in userspace, or error: <message> 
                   1905: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1906: 
                   1907: 
1.531     albertel 1908: sub userfileupload {
1.860     raeburn  1909:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1910:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1911:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1912:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1913:     $fname=&clean_filename($fname);
1.315     www      1914: # See if there is anything left
1.257     www      1915:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1916:     chop($env{'form.'.$formname});
1.523     raeburn  1917:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1918:         my $now = time;
                   1919:         my $filepath = 'tmp/helprequests/'.$now;
                   1920:         my @parts=split(/\//,$filepath);
                   1921:         my $fullpath = $perlvar{'lonDaemons'};
                   1922:         for (my $i=0;$i<@parts;$i++) {
                   1923:             $fullpath .= '/'.$parts[$i];
                   1924:             if ((-e $fullpath)!=1) {
                   1925:                 mkdir($fullpath,0777);
                   1926:             }
                   1927:         }
                   1928:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1929:         print $fh $env{'form.'.$formname};
1.523     raeburn  1930:         close($fh);
1.741     raeburn  1931:         return $fullpath.'/'.$fname;
                   1932:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1933:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1934:                        '_'.$env{'user.domain'}.'/pending';
                   1935:         my @parts=split(/\//,$filepath);
                   1936:         my $fullpath = $perlvar{'lonDaemons'};
                   1937:         for (my $i=0;$i<@parts;$i++) {
                   1938:             $fullpath .= '/'.$parts[$i];
                   1939:             if ((-e $fullpath)!=1) {
                   1940:                 mkdir($fullpath,0777);
                   1941:             }
                   1942:         }
                   1943:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1944:         print $fh $env{'form.'.$formname};
                   1945:         close($fh);
                   1946:         return $fullpath.'/'.$fname;
1.523     raeburn  1947:     }
1.719     banghart 1948:     
1.258     www      1949: # Create the directory if not present
1.493     albertel 1950:     $fname="$subdir/$fname";
1.259     www      1951:     if ($coursedoc) {
1.638     albertel 1952: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1953: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1954:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1955:             return &finishuserfileupload($docuname,$docudom,
                   1956: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1957: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1958:         } else {
1.620     albertel 1959:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1960:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1961: 				       $fname,$formname,$parser,
                   1962: 				       $allfiles,$codebase);
1.481     raeburn  1963:         }
1.719     banghart 1964:     } elsif (defined($destuname)) {
                   1965:         my $docuname=$destuname;
                   1966:         my $docudom=$destudom;
1.860     raeburn  1967: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1968: 				     $parser,$allfiles,$codebase,
                   1969:                                      $thumbwidth,$thumbheight);
1.719     banghart 1970:         
1.259     www      1971:     } else {
1.638     albertel 1972:         my $docuname=$env{'user.name'};
                   1973:         my $docudom=$env{'user.domain'};
1.714     raeburn  1974:         if (exists($env{'form.group'})) {
                   1975:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1976:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1977:         }
1.860     raeburn  1978: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1979: 				     $parser,$allfiles,$codebase,
                   1980:                                      $thumbwidth,$thumbheight);
1.259     www      1981:     }
1.271     www      1982: }
                   1983: 
                   1984: sub finishuserfileupload {
1.860     raeburn  1985:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1986:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1987:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1988:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1989:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1990:     $file=$fname;
                   1991:     if ($fname=~m|/|) {
                   1992:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1993: 	$path.=$fnamepath.'/';
                   1994:     }
1.259     www      1995:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1996:     my $count;
                   1997:     for ($count=4;$count<=$#parts;$count++) {
                   1998:         $filepath.="/$parts[$count]";
                   1999:         if ((-e $filepath)!=1) {
                   2000: 	    mkdir($filepath,0777);
                   2001:         }
                   2002:     }
                   2003: # Save the file
                   2004:     {
1.701     albertel 2005: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2006: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2007: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2008: 	    return '/adm/notfound.html';
                   2009: 	}
                   2010: 	if (!print FH ($env{'form.'.$formname})) {
                   2011: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2012: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2013: 	    return '/adm/notfound.html';
                   2014: 	}
1.570     albertel 2015: 	close(FH);
1.258     www      2016:     }
1.637     raeburn  2017:     if ($parser eq 'parse') {
1.638     albertel 2018:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2019: 						   $codebase);
1.637     raeburn  2020:         unless ($parse_result eq 'ok') {
1.638     albertel 2021:             &logthis('Failed to parse '.$filepath.$file.
                   2022: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2023:         }
                   2024:     }
1.860     raeburn  2025:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2026:         my $input = $filepath.'/'.$file;
                   2027:         my $output = $filepath.'/'.'tn-'.$file;
                   2028:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2029:         system("convert -sample $thumbsize $input $output");
                   2030:         if (-e $filepath.'/'.'tn-'.$file) {
                   2031:             $fetchthumb  = 1; 
                   2032:         }
                   2033:     }
1.858     raeburn  2034:  
1.259     www      2035: # Notify homeserver to grep it
                   2036: #
1.638     albertel 2037:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2038:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2039:     if ($fetchresult eq 'ok') {
1.860     raeburn  2040:         if ($fetchthumb) {
                   2041:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2042:             if ($thumbresult ne 'ok') {
                   2043:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2044:                          $docuhome.': '.$thumbresult);
                   2045:             }
                   2046:         }
1.259     www      2047: #
1.258     www      2048: # Return the URL to it
1.494     albertel 2049:         return '/uploaded/'.$path.$file;
1.263     www      2050:     } else {
1.494     albertel 2051:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2052: 		 ': '.$fetchresult);
1.263     www      2053:         return '/adm/notfound.html';
1.858     raeburn  2054:     }
1.493     albertel 2055: }
                   2056: 
1.637     raeburn  2057: sub extract_embedded_items {
1.648     raeburn  2058:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2059:     my @state = ();
                   2060:     my %javafiles = (
                   2061:                       codebase => '',
                   2062:                       code => '',
                   2063:                       archive => ''
                   2064:                     );
                   2065:     my %mediafiles = (
                   2066:                       src => '',
                   2067:                       movie => '',
                   2068:                      );
1.648     raeburn  2069:     my $p;
                   2070:     if ($content) {
                   2071:         $p = HTML::LCParser->new($content);
                   2072:     } else {
                   2073:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2074:     }
1.641     albertel 2075:     while (my $t=$p->get_token()) {
1.640     albertel 2076: 	if ($t->[0] eq 'S') {
                   2077: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2078: 	    push(@state, $tagname);
1.648     raeburn  2079:             if (lc($tagname) eq 'allow') {
                   2080:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2081:             }
1.640     albertel 2082: 	    if (lc($tagname) eq 'img') {
                   2083: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2084: 	    }
1.886     albertel 2085: 	    if (lc($tagname) eq 'a') {
                   2086: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2087: 	    }
1.645     raeburn  2088:             if (lc($tagname) eq 'script') {
                   2089:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2090:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2091:                 } else {
                   2092:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2093:                 }
                   2094:             }
                   2095:             if (lc($tagname) eq 'link') {
                   2096:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2097:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2098:                 }
                   2099:             }
1.640     albertel 2100: 	    if (lc($tagname) eq 'object' ||
                   2101: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2102: 		foreach my $item (keys(%javafiles)) {
                   2103: 		    $javafiles{$item} = '';
                   2104: 		}
                   2105: 	    }
                   2106: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2107: 		my $name = lc($attr->{'name'});
                   2108: 		foreach my $item (keys(%javafiles)) {
                   2109: 		    if ($name eq $item) {
                   2110: 			$javafiles{$item} = $attr->{'value'};
                   2111: 			last;
                   2112: 		    }
                   2113: 		}
                   2114: 		foreach my $item (keys(%mediafiles)) {
                   2115: 		    if ($name eq $item) {
                   2116: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2117: 			last;
                   2118: 		    }
                   2119: 		}
                   2120: 	    }
                   2121: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2122: 		foreach my $item (keys(%javafiles)) {
                   2123: 		    if ($attr->{$item}) {
                   2124: 			$javafiles{$item} = $attr->{$item};
                   2125: 			last;
                   2126: 		    }
                   2127: 		}
                   2128: 		foreach my $item (keys(%mediafiles)) {
                   2129: 		    if ($attr->{$item}) {
                   2130: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2131: 			last;
                   2132: 		    }
                   2133: 		}
                   2134: 	    }
                   2135: 	} elsif ($t->[0] eq 'E') {
                   2136: 	    my ($tagname) = ($t->[1]);
                   2137: 	    if ($javafiles{'codebase'} ne '') {
                   2138: 		$javafiles{'codebase'} .= '/';
                   2139: 	    }  
                   2140: 	    if (lc($tagname) eq 'applet' ||
                   2141: 		lc($tagname) eq 'object' ||
                   2142: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2143: 		) {
                   2144: 		foreach my $item (keys(%javafiles)) {
                   2145: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2146: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2147: 			&add_filetype($allfiles,$file,$item);
                   2148: 		    }
                   2149: 		}
                   2150: 	    } 
                   2151: 	    pop @state;
                   2152: 	}
                   2153:     }
1.637     raeburn  2154:     return 'ok';
                   2155: }
                   2156: 
1.639     albertel 2157: sub add_filetype {
                   2158:     my ($allfiles,$file,$type)=@_;
                   2159:     if (exists($allfiles->{$file})) {
                   2160: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2161: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2162: 	}
                   2163:     } else {
                   2164: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2165:     }
                   2166: }
                   2167: 
1.493     albertel 2168: sub removeuploadedurl {
                   2169:     my ($url)=@_;
                   2170:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2171:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2172: }
                   2173: 
                   2174: sub removeuserfile {
                   2175:     my ($docuname,$docudom,$fname)=@_;
                   2176:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2177:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2178:     if ($result eq 'ok') {
                   2179:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2180:             my $metafile = $fname.'.meta';
                   2181:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2182: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2183:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2184:             my $sqlresult = 
1.823     albertel 2185:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2186:                                         'portfolio_metadata',$group,
                   2187:                                         'delete');
1.798     raeburn  2188:         }
                   2189:     }
                   2190:     return $result;
1.257     www      2191: }
1.15      www      2192: 
1.530     albertel 2193: sub mkdiruserfile {
                   2194:     my ($docuname,$docudom,$dir)=@_;
                   2195:     my $home=&homeserver($docuname,$docudom);
                   2196:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2197: }
                   2198: 
1.531     albertel 2199: sub renameuserfile {
                   2200:     my ($docuname,$docudom,$old,$new)=@_;
                   2201:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2202:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2203:                         &escape("$old").':'.&escape("$new"),$home);
                   2204:     if ($result eq 'ok') {
                   2205:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2206:             my $oldmeta = $old.'.meta';
                   2207:             my $newmeta = $new.'.meta';
                   2208:             my $metaresult = 
                   2209:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2210: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2211:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2212:             my $sqlresult = 
1.823     albertel 2213:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2214:                                         'portfolio_metadata',$group,
                   2215:                                         'delete');
1.798     raeburn  2216:         }
                   2217:     }
                   2218:     return $result;
1.531     albertel 2219: }
                   2220: 
1.14      www      2221: # ------------------------------------------------------------------------- Log
                   2222: 
                   2223: sub log {
                   2224:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2225:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2226: }
                   2227: 
                   2228: # ------------------------------------------------------------------ Course Log
1.352     www      2229: #
                   2230: # This routine flushes several buffers of non-mission-critical nature
                   2231: #
1.157     www      2232: 
                   2233: sub flushcourselogs {
1.352     www      2234:     &logthis('Flushing log buffers');
                   2235: #
                   2236: # course logs
                   2237: # This is a log of all transactions in a course, which can be used
                   2238: # for data mining purposes
                   2239: #
                   2240: # It also collects the courseid database, which lists last transaction
                   2241: # times and course titles for all courseids
                   2242: #
                   2243:     my %courseidbuffer=();
1.921     raeburn  2244:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2245:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2246: 		          &escape($courselogs{$crsid}),
                   2247: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2248: 	    delete $courselogs{$crsid};
                   2249:         } else {
                   2250:             &logthis('Failed to flush log buffer for '.$crsid);
                   2251:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2252:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2253:                         " exceeded maximum size, deleting.</font>");
                   2254:                delete $courselogs{$crsid};
                   2255:             }
1.352     www      2256:         }
1.920     raeburn  2257:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2258:             'description' => $coursedescrbuf{$crsid},
                   2259:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2260:             'type'        => $coursetypebuf{$crsid},
                   2261:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2262:         };
1.191     harris41 2263:     }
1.352     www      2264: #
                   2265: # Write course id database (reverse lookup) to homeserver of courses 
                   2266: # Is used in pickcourse
                   2267: #
1.840     albertel 2268:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2269:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2270:                                     $courseidbuffer{$crs_home},
                   2271:                                     $crs_home,'timeonly');
1.352     www      2272:     }
                   2273: #
                   2274: # File accesses
                   2275: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2276: #
1.449     matthew  2277:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2278:         if ($entry =~ /___count$/) {
                   2279:             my ($dom,$name);
1.807     albertel 2280:             ($dom,$name,undef)=
1.811     albertel 2281: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2282:             if (! defined($dom) || $dom eq '' || 
                   2283:                 ! defined($name) || $name eq '') {
1.620     albertel 2284:                 my $cid = $env{'request.course.id'};
                   2285:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2286:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2287:             }
1.450     matthew  2288:             my $value = $accesshash{$entry};
                   2289:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2290:             my %temphash=($url => $value);
1.449     matthew  2291:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2292:             if ($result eq 'ok') {
                   2293:                 delete $accesshash{$entry};
                   2294:             } elsif ($result eq 'unknown_cmd') {
                   2295:                 # Target server has old code running on it.
1.450     matthew  2296:                 my %temphash=($entry => $value);
1.449     matthew  2297:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2298:                     delete $accesshash{$entry};
                   2299:                 }
                   2300:             }
                   2301:         } else {
1.811     albertel 2302:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2303:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2304:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2305:                 delete $accesshash{$entry};
                   2306:             }
1.185     www      2307:         }
1.191     harris41 2308:     }
1.352     www      2309: #
                   2310: # Roles
                   2311: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2312: #
1.800     albertel 2313:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2314:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2315: 	    split(/\:/,$entry);
                   2316:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2317:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2318:                 $rudom,$runame) eq 'ok') {
                   2319: 	    delete $userrolehash{$entry};
                   2320:         }
                   2321:     }
1.662     raeburn  2322: #
                   2323: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2324: #
                   2325:     my %domrolebuffer = ();
                   2326:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2327:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2328:         if ($domrolebuffer{$rudom}) {
                   2329:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2330:                       '='.&escape($domainrolehash{$entry});
                   2331:         } else {
                   2332:             $domrolebuffer{$rudom}.=&escape($entry).
                   2333:                       '='.&escape($domainrolehash{$entry});
                   2334:         }
                   2335:         delete $domainrolehash{$entry};
                   2336:     }
                   2337:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2338: 	my %servers = &get_servers($dom,'library');
                   2339: 	foreach my $tryserver (keys(%servers)) {
                   2340: 	    unless (&reply('domroleput:'.$dom.':'.
                   2341: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2342: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2343: 	    }
1.662     raeburn  2344:         }
                   2345:     }
1.186     www      2346:     $dumpcount++;
1.157     www      2347: }
                   2348: 
                   2349: sub courselog {
                   2350:     my $what=shift;
1.158     www      2351:     $what=time.':'.$what;
1.620     albertel 2352:     unless ($env{'request.course.id'}) { return ''; }
                   2353:     $coursedombuf{$env{'request.course.id'}}=
                   2354:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2355:     $coursenumbuf{$env{'request.course.id'}}=
                   2356:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2357:     $coursehombuf{$env{'request.course.id'}}=
                   2358:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2359:     $coursedescrbuf{$env{'request.course.id'}}=
                   2360:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2361:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2362:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2363:     $courseownerbuf{$env{'request.course.id'}}=
                   2364:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2365:     $coursetypebuf{$env{'request.course.id'}}=
                   2366:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2367:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2368: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2369:     } else {
1.620     albertel 2370: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2371:     }
1.620     albertel 2372:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2373: 	&flushcourselogs();
                   2374:     }
1.158     www      2375: }
                   2376: 
                   2377: sub courseacclog {
                   2378:     my $fnsymb=shift;
1.620     albertel 2379:     unless ($env{'request.course.id'}) { return ''; }
                   2380:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2381:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2382:         $what.=':POST';
1.583     matthew  2383:         # FIXME: Probably ought to escape things....
1.800     albertel 2384: 	foreach my $key (keys(%env)) {
                   2385:             if ($key=~/^form\.(.*)/) {
                   2386: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2387:             }
1.191     harris41 2388:         }
1.583     matthew  2389:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2390:         # FIXME: We should not be depending on a form parameter that someone
                   2391:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2392:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2393:             $what.= ':POST';
                   2394:             # FIXME: Probably ought to escape things....
                   2395:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2396:                                  'crsdiscuss') {
1.620     albertel 2397:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2398:             }
                   2399:         }
1.158     www      2400:     }
                   2401:     &courselog($what);
1.149     www      2402: }
                   2403: 
1.185     www      2404: sub countacc {
                   2405:     my $url=&declutter(shift);
1.458     matthew  2406:     return if (! defined($url) || $url eq '');
1.620     albertel 2407:     unless ($env{'request.course.id'}) { return ''; }
                   2408:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2409:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2410:     $accesshash{$key}++;
1.185     www      2411: }
1.349     www      2412: 
1.361     www      2413: sub linklog {
                   2414:     my ($from,$to)=@_;
                   2415:     $from=&declutter($from);
                   2416:     $to=&declutter($to);
                   2417:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2418:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2419: }
                   2420:   
1.349     www      2421: sub userrolelog {
                   2422:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2423:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2424:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2425:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2426:         ($trole=~/^ta/)) {
1.350     www      2427:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2428:        $userrolehash
                   2429:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2430:                     =$tend.':'.$tstart;
1.662     raeburn  2431:     }
1.898     albertel 2432:     if (($env{'request.role'} =~ /dc\./) &&
                   2433: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2434: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2435: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2436:        $userrolehash
                   2437:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2438:                     =$tend.':'.$tstart;
                   2439:     }
1.662     raeburn  2440:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2441:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2442:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2443:         ($trole=~/^sc/)) {
                   2444:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2445:        $domainrolehash
                   2446:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2447:                     = $tend.':'.$tstart;
                   2448:     }
1.351     www      2449: }
                   2450: 
                   2451: sub get_course_adv_roles {
                   2452:     my $cid=shift;
1.620     albertel 2453:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2454:     my %coursehash=&coursedescription($cid);
1.470     www      2455:     my %nothide=();
1.800     albertel 2456:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2457:         if ($user !~ /:/) {
                   2458: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2459:         } else {
                   2460:             $nothide{$user}=1;
                   2461:         }
1.470     www      2462:     }
1.351     www      2463:     my %returnhash=();
                   2464:     my %dumphash=
                   2465:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2466:     my $now=time;
1.800     albertel 2467:     foreach my $entry (keys %dumphash) {
                   2468: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2469:         if (($tstart) && ($tstart<0)) { next; }
                   2470:         if (($tend) && ($tend<$now)) { next; }
                   2471:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2472:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2473: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2474: 	if ((&privileged($username,$domain)) && 
                   2475: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2476: 	if ($role eq 'cr') { next; }
1.351     www      2477:         my $key=&plaintext($role);
                   2478:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2479:         if ($returnhash{$key}) {
                   2480: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2481:         } else {
                   2482:             $returnhash{$key}=$username.':'.$domain;
                   2483:         }
1.400     www      2484:      }
                   2485:     return %returnhash;
                   2486: }
                   2487: 
                   2488: sub get_my_roles {
1.937     raeburn  2489:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2490:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2491:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2492:     my (%dumphash,%nothide);
1.858     raeburn  2493:     if ($context eq 'userroles') { 
                   2494:         %dumphash = &dump('roles',$udom,$uname);
                   2495:     } else {
                   2496:         %dumphash=
1.400     www      2497:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2498:         if ($hidepriv) {
                   2499:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2500:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2501:                 if ($user !~ /:/) {
                   2502:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2503:                 } else {
                   2504:                     $nothide{$user} = 1;
                   2505:                 }
                   2506:             }
                   2507:         }
1.858     raeburn  2508:     }
1.400     www      2509:     my %returnhash=();
                   2510:     my $now=time;
1.800     albertel 2511:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2512:         my ($role,$tend,$tstart);
                   2513:         if ($context eq 'userroles') {
                   2514: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2515:         } else {
                   2516:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2517:         }
1.400     www      2518:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2519:         my $status = 'active';
1.939     raeburn  2520:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2521:             $status = 'previous';
                   2522:         } 
                   2523:         if (($tstart) && ($now<$tstart)) {
                   2524:             $status = 'future';
                   2525:         }
                   2526:         if (ref($types) eq 'ARRAY') {
                   2527:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2528:                 next;
                   2529:             } 
                   2530:         } else {
                   2531:             if ($status ne 'active') {
                   2532:                 next;
                   2533:             }
                   2534:         }
1.867     raeburn  2535:         my ($rolecode,$username,$domain,$section,$area);
                   2536:         if ($context eq 'userroles') {
                   2537:             ($area,$rolecode) = split(/_/,$entry);
                   2538:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2539:         } else {
                   2540:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2541:         }
1.832     raeburn  2542:         if (ref($roledoms) eq 'ARRAY') {
                   2543:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2544:                 next;
                   2545:             }
                   2546:         }
                   2547:         if (ref($roles) eq 'ARRAY') {
                   2548:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2549:                 if ($role =~ /^cr\//) {
                   2550:                     if (!grep(/^cr$/,@{$roles})) {
                   2551:                         next;
                   2552:                     }
                   2553:                 } else {
                   2554:                     next;
                   2555:                 }
1.832     raeburn  2556:             }
1.867     raeburn  2557:         }
1.937     raeburn  2558:         if ($hidepriv) {
                   2559:             if ((&privileged($username,$domain)) &&
                   2560:                 (!$nothide{$username.':'.$domain})) { 
                   2561:                 next;
                   2562:             }
                   2563:         }
1.933     raeburn  2564:         if ($withsec) {
                   2565:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2566:                 $tstart.':'.$tend;
                   2567:         } else {
                   2568:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2569:         }
1.832     raeburn  2570:     }
1.373     www      2571:     return %returnhash;
1.399     www      2572: }
                   2573: 
                   2574: # ----------------------------------------------------- Frontpage Announcements
                   2575: #
                   2576: #
                   2577: 
                   2578: sub postannounce {
                   2579:     my ($server,$text)=@_;
1.844     albertel 2580:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2581:     unless ($text=~/\w/) { $text=''; }
                   2582:     return &reply('setannounce:'.&escape($text),$server);
                   2583: }
                   2584: 
                   2585: sub getannounce {
1.448     albertel 2586: 
                   2587:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2588: 	my $announcement='';
1.800     albertel 2589: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2590: 	close($fh);
1.399     www      2591: 	if ($announcement=~/\w/) { 
                   2592: 	    return 
                   2593:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2594:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2595: 	} else {
                   2596: 	    return '';
                   2597: 	}
                   2598:     } else {
                   2599: 	return '';
                   2600:     }
1.351     www      2601: }
1.353     www      2602: 
                   2603: # ---------------------------------------------------------- Course ID routines
                   2604: # Deal with domain's nohist_courseid.db files
                   2605: #
                   2606: 
                   2607: sub courseidput {
1.921     raeburn  2608:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2609:     my $outcome;
                   2610:     if ($caller eq 'timeonly') {
                   2611:         my $cids = '';
                   2612:         foreach my $item (keys(%$storehash)) {
                   2613:             $cids.=&escape($item).'&';
                   2614:         }
                   2615:         $cids=~s/\&$//;
                   2616:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2617:                           $coursehome);       
                   2618:     } else {
                   2619:         my $items = '';
                   2620:         foreach my $item (keys(%$storehash)) {
                   2621:             $items.= &escape($item).'='.
                   2622:                      &freeze_escape($$storehash{$item}).'&';
                   2623:         }
                   2624:         $items=~s/\&$//;
                   2625:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2626:                           $coursehome);
1.918     raeburn  2627:     }
                   2628:     if ($outcome eq 'unknown_cmd') {
                   2629:         my $what;
                   2630:         foreach my $cid (keys(%$storehash)) {
                   2631:             $what .= &escape($cid).'=';
1.921     raeburn  2632:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2633:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2634:             }
                   2635:             $what =~ s/\:$/&/;
                   2636:         }
                   2637:         $what =~ s/\&$//;  
                   2638:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2639:     } else {
                   2640:         return $outcome;
                   2641:     }
1.353     www      2642: }
                   2643: 
                   2644: sub courseiddump {
1.921     raeburn  2645:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947   ! raeburn  2646:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
        !          2647:         $selfenrollonly)=@_;
1.918     raeburn  2648:     my $as_hash = 1;
                   2649:     my %returnhash;
                   2650:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2651:     my %libserv = &all_library();
                   2652:     foreach my $tryserver (keys(%libserv)) {
                   2653:         if ( (  $hostidflag == 1 
                   2654: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2655: 	     || (!defined($hostidflag)) ) {
                   2656: 
1.918     raeburn  2657: 	    if (($domfilter eq '') ||
                   2658: 		(&host_domain($tryserver) eq $domfilter)) {
                   2659:                 my $rep = 
                   2660:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2661:                          $sincefilter.':'.&escape($descfilter).':'.
                   2662:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2663:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947   ! raeburn  2664:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
        !          2665:                          &escape($selfenrollonly),$tryserver);
1.918     raeburn  2666:                 my @pairs=split(/\&/,$rep);
                   2667:                 foreach my $item (@pairs) {
                   2668:                     my ($key,$value)=split(/\=/,$item,2);
                   2669:                     $key = &unescape($key);
                   2670:                     next if ($key =~ /^error: 2 /);
                   2671:                     my $result = &thaw_unescape($value);
                   2672:                     if (ref($result) eq 'HASH') {
                   2673:                         $returnhash{$key}=$result;
                   2674:                     } else {
1.921     raeburn  2675:                         my @responses = split(/:/,$value);
                   2676:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2677:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2678:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2679:                         }
                   2680:                     } 
1.353     www      2681:                 }
                   2682:             }
                   2683:         }
                   2684:     }
                   2685:     return %returnhash;
                   2686: }
                   2687: 
1.658     raeburn  2688: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2689: 
                   2690: sub dcmailput {
1.685     raeburn  2691:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2692:     my $status = &Apache::lonnet::critical(
1.740     www      2693:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2694:        &escape($message),$server);
1.662     raeburn  2695:     return $status;
                   2696: }
                   2697: 
1.658     raeburn  2698: sub dcmaildump {
                   2699:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2700:     my %returnhash=();
1.846     albertel 2701: 
                   2702:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2703:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2704:                                                          &escape($enddate).':';
                   2705: 	my @esc_senders=map { &escape($_)} @$senders;
                   2706: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2707: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2708:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2709:             if (($key) && ($value)) {
                   2710:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2711:             }
                   2712:         }
                   2713:     }
                   2714:     return %returnhash;
                   2715: }
1.662     raeburn  2716: # ---------------------------------------------------------- Domain roles
                   2717: 
                   2718: sub get_domain_roles {
                   2719:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2720:     if (undef($startdate) || $startdate eq '') {
                   2721:         $startdate = '.';
                   2722:     }
                   2723:     if (undef($enddate) || $enddate eq '') {
                   2724:         $enddate = '.';
                   2725:     }
1.922     raeburn  2726:     my $rolelist;
                   2727:     if (ref($roles) eq 'ARRAY') {
                   2728:         $rolelist = join(':',@{$roles});
                   2729:     }
1.662     raeburn  2730:     my %personnel = ();
1.841     albertel 2731: 
                   2732:     my %servers = &get_servers($dom,'library');
                   2733:     foreach my $tryserver (keys(%servers)) {
                   2734: 	%{$personnel{$tryserver}}=();
                   2735: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2736: 					    &escape($startdate).':'.
                   2737: 					    &escape($enddate).':'.
                   2738: 					    &escape($rolelist), $tryserver))) {
                   2739: 	    my ($key,$value) = split(/\=/,$line,2);
                   2740: 	    if (($key) && ($value)) {
                   2741: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2742: 	    }
                   2743: 	}
1.662     raeburn  2744:     }
                   2745:     return %personnel;
                   2746: }
1.658     raeburn  2747: 
1.149     www      2748: # ----------------------------------------------------------- Check out an item
                   2749: 
1.504     albertel 2750: sub get_first_access {
                   2751:     my ($type,$argsymb)=@_;
1.790     albertel 2752:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2753:     if ($argsymb) { $symb=$argsymb; }
                   2754:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2755:     if ($type eq 'course') {
                   2756: 	$res='course';
                   2757:     } elsif ($type eq 'map') {
1.588     albertel 2758: 	$res=&symbread($map);
                   2759:     } else {
                   2760: 	$res=$symb;
                   2761:     }
                   2762:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2763:     return $times{"$courseid\0$res"};
1.504     albertel 2764: }
                   2765: 
                   2766: sub set_first_access {
                   2767:     my ($type)=@_;
1.790     albertel 2768:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2769:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2770:     if ($type eq 'course') {
                   2771: 	$res='course';
                   2772:     } elsif ($type eq 'map') {
1.588     albertel 2773: 	$res=&symbread($map);
                   2774:     } else {
                   2775: 	$res=$symb;
                   2776:     }
                   2777:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2778:     if (!$firstaccess) {
1.588     albertel 2779: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2780:     }
                   2781:     return 'already_set';
1.504     albertel 2782: }
                   2783: 
1.149     www      2784: sub checkout {
                   2785:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2786:     my $now=time;
                   2787:     my $lonhost=$perlvar{'lonHostID'};
                   2788:     my $infostr=&escape(
1.234     www      2789:                  'CHECKOUTTOKEN&'.
1.149     www      2790:                  $tuname.'&'.
                   2791:                  $tudom.'&'.
                   2792:                  $tcrsid.'&'.
                   2793:                  $symb.'&'.
                   2794: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2795:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2796:     if ($token=~/^error\:/) { 
1.672     albertel 2797:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2798:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2799:                  "</font>");
                   2800:         return ''; 
                   2801:     }
                   2802: 
1.149     www      2803:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2804:     $token=~tr/a-z/A-Z/;
                   2805: 
1.153     www      2806:     my %infohash=('resource.0.outtoken' => $token,
                   2807:                   'resource.0.checkouttime' => $now,
                   2808:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2809: 
                   2810:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2811:        return '';
1.151     www      2812:     } else {
1.672     albertel 2813:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2814:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2815:                  "</font>");
1.149     www      2816:     }    
                   2817: 
                   2818:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2819:                          &escape('Checkout '.$infostr.' - '.
                   2820:                                                  $token)) ne 'ok') {
                   2821: 	return '';
1.151     www      2822:     } else {
1.672     albertel 2823:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2824:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2825:                  "</font>");
1.149     www      2826:     }
1.151     www      2827:     return $token;
1.149     www      2828: }
                   2829: 
                   2830: # ------------------------------------------------------------ Check in an item
                   2831: 
                   2832: sub checkin {
                   2833:     my $token=shift;
1.150     www      2834:     my $now=time;
                   2835:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2836:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2837:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2838:     $dtoken=~s/\W/\_/g;
1.234     www      2839:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2840:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2841: 
1.154     www      2842:     unless (($tuname) && ($tudom)) {
                   2843:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2844:         return '';
                   2845:     }
                   2846:     
                   2847:     unless (&allowed('mgr',$tcrsid)) {
                   2848:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2849:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2850:         return '';
                   2851:     }
                   2852: 
1.153     www      2853:     my %infohash=('resource.0.intoken' => $token,
                   2854:                   'resource.0.checkintime' => $now,
                   2855:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2856: 
                   2857:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2858:        return '';
                   2859:     }    
                   2860: 
                   2861:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2862:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2863: 	return '';
                   2864:     }
                   2865: 
                   2866:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2867: }
                   2868: 
                   2869: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2870: 
                   2871: sub expirespread {
                   2872:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2873:     my $cid=$env{'request.course.id'}; 
1.110     www      2874:     if ($cid) {
                   2875:        my $now=time;
                   2876:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2877:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2878:                             $env{'course.'.$cid.'.num'}.
1.110     www      2879: 	        	    ':nohist_expirationdates:'.
                   2880:                             &escape($key).'='.$now,
1.620     albertel 2881:                             $env{'course.'.$cid.'.home'})
1.110     www      2882:     }
                   2883:     return 'ok';
1.14      www      2884: }
                   2885: 
1.109     www      2886: # ----------------------------------------------------- Devalidate Spreadsheets
                   2887: 
                   2888: sub devalidate {
1.325     www      2889:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2890:     my $cid=$env{'request.course.id'}; 
1.109     www      2891:     if ($cid) {
1.391     matthew  2892:         # delete the stored spreadsheets for
                   2893:         # - the student level sheet of this user in course's homespace
                   2894:         # - the assessment level sheet for this resource 
                   2895:         #   for this user in user's homespace
1.553     albertel 2896: 	# - current conditional state info
1.325     www      2897: 	my $key=$uname.':'.$udom.':';
1.109     www      2898:         my $status=
1.299     matthew  2899: 	    &del('nohist_calculatedsheets',
1.391     matthew  2900: 		 [$key.'studentcalc:'],
1.620     albertel 2901: 		 $env{'course.'.$cid.'.domain'},
                   2902: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2903: 		.' '.
                   2904: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2905: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2906:         unless ($status eq 'ok ok') {
                   2907:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2908:                     $uname.' at '.$udom.' for '.
1.109     www      2909: 		    $symb.': '.$status);
1.133     albertel 2910:         }
1.553     albertel 2911: 	&delenv('user.state.'.$cid);
1.109     www      2912:     }
                   2913: }
                   2914: 
1.265     albertel 2915: sub get_scalar {
                   2916:     my ($string,$end) = @_;
                   2917:     my $value;
                   2918:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2919: 	$value = $1;
                   2920:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2921: 	$value = $1;
                   2922:     }
                   2923:     return &unescape($value);
                   2924: }
                   2925: 
                   2926: sub array2str {
                   2927:   my (@array) = @_;
                   2928:   my $result=&arrayref2str(\@array);
                   2929:   $result=~s/^__ARRAY_REF__//;
                   2930:   $result=~s/__END_ARRAY_REF__$//;
                   2931:   return $result;
                   2932: }
                   2933: 
1.204     albertel 2934: sub arrayref2str {
                   2935:   my ($arrayref) = @_;
1.265     albertel 2936:   my $result='__ARRAY_REF__';
1.204     albertel 2937:   foreach my $elem (@$arrayref) {
1.265     albertel 2938:     if(ref($elem) eq 'ARRAY') {
                   2939:       $result.=&arrayref2str($elem).'&';
                   2940:     } elsif(ref($elem) eq 'HASH') {
                   2941:       $result.=&hashref2str($elem).'&';
                   2942:     } elsif(ref($elem)) {
                   2943:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2944:     } else {
                   2945:       $result.=&escape($elem).'&';
                   2946:     }
                   2947:   }
                   2948:   $result=~s/\&$//;
1.265     albertel 2949:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2950:   return $result;
                   2951: }
                   2952: 
1.168     albertel 2953: sub hash2str {
1.204     albertel 2954:   my (%hash) = @_;
                   2955:   my $result=&hashref2str(\%hash);
1.265     albertel 2956:   $result=~s/^__HASH_REF__//;
                   2957:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2958:   return $result;
                   2959: }
                   2960: 
                   2961: sub hashref2str {
                   2962:   my ($hashref)=@_;
1.265     albertel 2963:   my $result='__HASH_REF__';
1.800     albertel 2964:   foreach my $key (sort(keys(%$hashref))) {
                   2965:     if (ref($key) eq 'ARRAY') {
                   2966:       $result.=&arrayref2str($key).'=';
                   2967:     } elsif (ref($key) eq 'HASH') {
                   2968:       $result.=&hashref2str($key).'=';
                   2969:     } elsif (ref($key)) {
1.265     albertel 2970:       $result.='=';
1.800     albertel 2971:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2972:     } else {
1.800     albertel 2973: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2974:     }
                   2975: 
1.800     albertel 2976:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2977:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2978:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2979:       $result.=&hashref2str($hashref->{$key}).'&';
                   2980:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2981:        $result.='&';
1.800     albertel 2982:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2983:     } else {
1.800     albertel 2984:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2985:     }
                   2986:   }
1.168     albertel 2987:   $result=~s/\&$//;
1.265     albertel 2988:   $result .= '__END_HASH_REF__';
1.168     albertel 2989:   return $result;
                   2990: }
                   2991: 
                   2992: sub str2hash {
1.265     albertel 2993:     my ($string)=@_;
                   2994:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2995:     return %$hash;
                   2996: }
                   2997: 
                   2998: sub str2hashref {
1.168     albertel 2999:   my ($string) = @_;
1.265     albertel 3000: 
                   3001:   my %hash;
                   3002: 
                   3003:   if($string !~ /^__HASH_REF__/) {
                   3004:       if (! ($string eq '' || !defined($string))) {
                   3005: 	  $hash{'error'}='Not hash reference';
                   3006:       }
                   3007:       return (\%hash, $string);
                   3008:   }
                   3009: 
                   3010:   $string =~ s/^__HASH_REF__//;
                   3011: 
                   3012:   while($string !~ /^__END_HASH_REF__/) {
                   3013:       #key
                   3014:       my $key='';
                   3015:       if($string =~ /^__HASH_REF__/) {
                   3016:           ($key, $string)=&str2hashref($string);
                   3017:           if(defined($key->{'error'})) {
                   3018:               $hash{'error'}='Bad data';
                   3019:               return (\%hash, $string);
                   3020:           }
                   3021:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3022:           ($key, $string)=&str2arrayref($string);
                   3023:           if($key->[0] eq 'Array reference error') {
                   3024:               $hash{'error'}='Bad data';
                   3025:               return (\%hash, $string);
                   3026:           }
                   3027:       } else {
                   3028:           $string =~ s/^(.*?)=//;
1.267     albertel 3029: 	  $key=&unescape($1);
1.265     albertel 3030:       }
                   3031:       $string =~ s/^=//;
                   3032: 
                   3033:       #value
                   3034:       my $value='';
                   3035:       if($string =~ /^__HASH_REF__/) {
                   3036:           ($value, $string)=&str2hashref($string);
                   3037:           if(defined($value->{'error'})) {
                   3038:               $hash{'error'}='Bad data';
                   3039:               return (\%hash, $string);
                   3040:           }
                   3041:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3042:           ($value, $string)=&str2arrayref($string);
                   3043:           if($value->[0] eq 'Array reference error') {
                   3044:               $hash{'error'}='Bad data';
                   3045:               return (\%hash, $string);
                   3046:           }
                   3047:       } else {
                   3048: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3049:       }
                   3050:       $string =~ s/^&//;
                   3051: 
                   3052:       $hash{$key}=$value;
1.204     albertel 3053:   }
1.265     albertel 3054: 
                   3055:   $string =~ s/^__END_HASH_REF__//;
                   3056: 
                   3057:   return (\%hash, $string);
1.204     albertel 3058: }
                   3059: 
                   3060: sub str2array {
1.265     albertel 3061:     my ($string)=@_;
                   3062:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3063:     return @$array;
                   3064: }
                   3065: 
                   3066: sub str2arrayref {
1.204     albertel 3067:   my ($string) = @_;
1.265     albertel 3068:   my @array;
                   3069: 
                   3070:   if($string !~ /^__ARRAY_REF__/) {
                   3071:       if (! ($string eq '' || !defined($string))) {
                   3072: 	  $array[0]='Array reference error';
                   3073:       }
                   3074:       return (\@array, $string);
                   3075:   }
                   3076: 
                   3077:   $string =~ s/^__ARRAY_REF__//;
                   3078: 
                   3079:   while($string !~ /^__END_ARRAY_REF__/) {
                   3080:       my $value='';
                   3081:       if($string =~ /^__HASH_REF__/) {
                   3082:           ($value, $string)=&str2hashref($string);
                   3083:           if(defined($value->{'error'})) {
                   3084:               $array[0] ='Array reference error';
                   3085:               return (\@array, $string);
                   3086:           }
                   3087:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3088:           ($value, $string)=&str2arrayref($string);
                   3089:           if($value->[0] eq 'Array reference error') {
                   3090:               $array[0] ='Array reference error';
                   3091:               return (\@array, $string);
                   3092:           }
                   3093:       } else {
                   3094: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3095:       }
                   3096:       $string =~ s/^&//;
                   3097: 
                   3098:       push(@array, $value);
1.191     harris41 3099:   }
1.265     albertel 3100: 
                   3101:   $string =~ s/^__END_ARRAY_REF__//;
                   3102: 
                   3103:   return (\@array, $string);
1.168     albertel 3104: }
                   3105: 
1.167     albertel 3106: # -------------------------------------------------------------------Temp Store
                   3107: 
1.168     albertel 3108: sub tmpreset {
                   3109:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3110:   if (!$symb) {
                   3111:     $symb=&symbread();
1.620     albertel 3112:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3113:   }
                   3114:   $symb=escape($symb);
                   3115: 
1.620     albertel 3116:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3117:   $namespace=~s/\//\_/g;
                   3118:   $namespace=~s/\W//g;
                   3119: 
1.620     albertel 3120:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3121:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3122:   if ($domain eq 'public' && $stuname eq 'public') {
                   3123:       $stuname=$ENV{'REMOTE_ADDR'};
                   3124:   }
1.168     albertel 3125:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3126:   my %hash;
                   3127:   if (tie(%hash,'GDBM_File',
                   3128: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3129: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3130:     foreach my $key (keys %hash) {
1.180     albertel 3131:       if ($key=~ /:$symb/) {
1.168     albertel 3132: 	delete($hash{$key});
                   3133:       }
                   3134:     }
                   3135:   }
                   3136: }
                   3137: 
1.167     albertel 3138: sub tmpstore {
1.168     albertel 3139:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3140: 
                   3141:   if (!$symb) {
                   3142:     $symb=&symbread();
1.620     albertel 3143:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3144:   }
                   3145:   $symb=escape($symb);
                   3146: 
                   3147:   if (!$namespace) {
                   3148:     # I don't think we would ever want to store this for a course.
                   3149:     # it seems this will only be used if we don't have a course.
1.620     albertel 3150:     #$namespace=$env{'request.course.id'};
1.168     albertel 3151:     #if (!$namespace) {
1.620     albertel 3152:       $namespace=$env{'request.state'};
1.168     albertel 3153:     #}
                   3154:   }
                   3155:   $namespace=~s/\//\_/g;
                   3156:   $namespace=~s/\W//g;
1.620     albertel 3157:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3158:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3159:   if ($domain eq 'public' && $stuname eq 'public') {
                   3160:       $stuname=$ENV{'REMOTE_ADDR'};
                   3161:   }
1.168     albertel 3162:   my $now=time;
                   3163:   my %hash;
                   3164:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3165:   if (tie(%hash,'GDBM_File',
                   3166: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3167: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3168:     $hash{"version:$symb"}++;
                   3169:     my $version=$hash{"version:$symb"};
                   3170:     my $allkeys=''; 
                   3171:     foreach my $key (keys(%$storehash)) {
                   3172:       $allkeys.=$key.':';
1.591     albertel 3173:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3174:     }
                   3175:     $hash{"$version:$symb:timestamp"}=$now;
                   3176:     $allkeys.='timestamp';
                   3177:     $hash{"$version:keys:$symb"}=$allkeys;
                   3178:     if (untie(%hash)) {
                   3179:       return 'ok';
                   3180:     } else {
                   3181:       return "error:$!";
                   3182:     }
                   3183:   } else {
                   3184:     return "error:$!";
                   3185:   }
                   3186: }
1.167     albertel 3187: 
1.168     albertel 3188: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3189: 
1.168     albertel 3190: sub tmprestore {
                   3191:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3192: 
1.168     albertel 3193:   if (!$symb) {
                   3194:     $symb=&symbread();
1.620     albertel 3195:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3196:   }
                   3197:   $symb=escape($symb);
                   3198: 
1.620     albertel 3199:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3200: 
1.620     albertel 3201:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3202:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3203:   if ($domain eq 'public' && $stuname eq 'public') {
                   3204:       $stuname=$ENV{'REMOTE_ADDR'};
                   3205:   }
1.168     albertel 3206:   my %returnhash;
                   3207:   $namespace=~s/\//\_/g;
                   3208:   $namespace=~s/\W//g;
                   3209:   my %hash;
                   3210:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3211:   if (tie(%hash,'GDBM_File',
                   3212: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3213: 	  &GDBM_READER(),0640)) {
1.168     albertel 3214:     my $version=$hash{"version:$symb"};
                   3215:     $returnhash{'version'}=$version;
                   3216:     my $scope;
                   3217:     for ($scope=1;$scope<=$version;$scope++) {
                   3218:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3219:       my @keys=split(/:/,$vkeys);
                   3220:       my $key;
                   3221:       $returnhash{"$scope:keys"}=$vkeys;
                   3222:       foreach $key (@keys) {
1.591     albertel 3223: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3224: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3225:       }
                   3226:     }
1.168     albertel 3227:     if (!(untie(%hash))) {
                   3228:       return "error:$!";
                   3229:     }
                   3230:   } else {
                   3231:     return "error:$!";
                   3232:   }
                   3233:   return %returnhash;
1.167     albertel 3234: }
                   3235: 
1.9       www      3236: # ----------------------------------------------------------------------- Store
                   3237: 
                   3238: sub store {
1.124     www      3239:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3240:     my $home='';
                   3241: 
1.168     albertel 3242:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3243: 
1.213     www      3244:     $symb=&symbclean($symb);
1.122     albertel 3245:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3246: 
1.620     albertel 3247:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3248:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3249: 
                   3250:     &devalidate($symb,$stuname,$domain);
1.109     www      3251: 
                   3252:     $symb=escape($symb);
1.187     www      3253:     if (!$namespace) { 
1.620     albertel 3254:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3255:           return ''; 
                   3256:        } 
                   3257:     }
1.620     albertel 3258:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3259: 
                   3260:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3261:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3262: 
1.12      www      3263:     my $namevalue='';
1.800     albertel 3264:     foreach my $key (keys(%$storehash)) {
                   3265:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3266:     }
1.12      www      3267:     $namevalue=~s/\&$//;
1.187     www      3268:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3269:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3270: }
                   3271: 
1.47      www      3272: # -------------------------------------------------------------- Critical Store
                   3273: 
                   3274: sub cstore {
1.124     www      3275:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3276:     my $home='';
                   3277: 
1.168     albertel 3278:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3279: 
1.213     www      3280:     $symb=&symbclean($symb);
1.122     albertel 3281:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3282: 
1.620     albertel 3283:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3284:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3285: 
                   3286:     &devalidate($symb,$stuname,$domain);
1.109     www      3287: 
                   3288:     $symb=escape($symb);
1.187     www      3289:     if (!$namespace) { 
1.620     albertel 3290:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3291:           return ''; 
                   3292:        } 
                   3293:     }
1.620     albertel 3294:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3295: 
                   3296:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3297:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3298: 
1.47      www      3299:     my $namevalue='';
1.800     albertel 3300:     foreach my $key (keys(%$storehash)) {
                   3301:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3302:     }
1.47      www      3303:     $namevalue=~s/\&$//;
1.187     www      3304:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3305:     return critical
                   3306:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3307: }
                   3308: 
1.9       www      3309: # --------------------------------------------------------------------- Restore
                   3310: 
                   3311: sub restore {
1.124     www      3312:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3313:     my $home='';
                   3314: 
1.168     albertel 3315:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3316: 
1.122     albertel 3317:     if (!$symb) {
                   3318:       unless ($symb=escape(&symbread())) { return ''; }
                   3319:     } else {
1.213     www      3320:       $symb=&escape(&symbclean($symb));
1.122     albertel 3321:     }
1.188     www      3322:     if (!$namespace) { 
1.620     albertel 3323:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3324:           return ''; 
                   3325:        } 
                   3326:     }
1.620     albertel 3327:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3328:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3329:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3330:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3331: 
1.12      www      3332:     my %returnhash=();
1.800     albertel 3333:     foreach my $line (split(/\&/,$answer)) {
                   3334: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3335:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3336:     }
1.75      www      3337:     my $version;
                   3338:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3339:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3340:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3341:        }
1.75      www      3342:     }
1.13      www      3343:     return %returnhash;
1.34      www      3344: }
                   3345: 
                   3346: # ---------------------------------------------------------- Course Description
                   3347: 
                   3348: sub coursedescription {
1.731     albertel 3349:     my ($courseid,$args)=@_;
1.34      www      3350:     $courseid=~s/^\///;
1.49      www      3351:     $courseid=~s/\_/\//g;
1.34      www      3352:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3353:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3354:     my $normalid=$cdomain.'_'.$cnum;
                   3355:     # need to always cache even if we get errors otherwise we keep 
                   3356:     # trying and trying and trying to get the course description.
                   3357:     my %envhash=();
                   3358:     my %returnhash=();
1.731     albertel 3359:     
                   3360:     my $expiretime=600;
                   3361:     if ($env{'request.course.id'} eq $normalid) {
                   3362: 	$expiretime=120;
                   3363:     }
                   3364: 
                   3365:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3366:     if (!$args->{'freshen_cache'}
                   3367: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3368: 	foreach my $key (keys(%env)) {
                   3369: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3370: 	    my ($setting) = $1;
                   3371: 	    $returnhash{$setting} = $env{$key};
                   3372: 	}
                   3373: 	return %returnhash;
                   3374:     }
                   3375: 
                   3376:     # get the data agin
                   3377:     if (!$args->{'one_time'}) {
                   3378: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3379:     }
1.811     albertel 3380: 
1.34      www      3381:     if ($chome ne 'no_host') {
1.302     albertel 3382:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3383:        if (!exists($returnhash{'con_lost'})) {
                   3384:            $returnhash{'home'}= $chome;
                   3385: 	   $returnhash{'domain'} = $cdomain;
                   3386: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3387:            if (!defined($returnhash{'type'})) {
                   3388:                $returnhash{'type'} = 'Course';
                   3389:            }
1.130     albertel 3390:            while (my ($name,$value) = each %returnhash) {
1.53      www      3391:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3392:            }
1.270     www      3393:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3394:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3395: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3396:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3397:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3398:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3399:        }
                   3400:     }
1.731     albertel 3401:     if (!$args->{'one_time'}) {
                   3402: 	&appenv(%envhash);
                   3403:     }
1.302     albertel 3404:     return %returnhash;
1.461     www      3405: }
                   3406: 
                   3407: # -------------------------------------------------See if a user is privileged
                   3408: 
                   3409: sub privileged {
                   3410:     my ($username,$domain)=@_;
                   3411:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3412: 			&homeserver($username,$domain));
                   3413:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3414:     my $now=time;
                   3415:     if ($rolesdump ne '') {
1.800     albertel 3416:         foreach my $entry (split(/&/,$rolesdump)) {
                   3417: 	    if ($entry!~/^rolesdef_/) {
                   3418: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3419: 		$area=~s/\_\w\w$//;
                   3420: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3421: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3422: 		    my $active=1;
                   3423: 		    if ($tend) {
                   3424: 			if ($tend<$now) { $active=0; }
                   3425: 		    }
                   3426: 		    if ($tstart) {
                   3427: 			if ($tstart>$now) { $active=0; }
                   3428: 		    }
                   3429: 		    if ($active) { return 1; }
                   3430: 		}
                   3431: 	    }
                   3432: 	}
                   3433:     }
                   3434:     return 0;
1.9       www      3435: }
1.1       albertel 3436: 
1.103     harris41 3437: # -------------------------------------------------------- Get user privileges
1.11      www      3438: 
                   3439: sub rolesinit {
                   3440:     my ($domain,$username,$authhost)=@_;
                   3441:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3442:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3443:     my %allroles=();
1.678     raeburn  3444:     my %allgroups=();   
1.11      www      3445:     my $now=time;
1.743     albertel 3446:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3447:     my $group_privs;
1.11      www      3448: 
                   3449:     if ($rolesdump ne '') {
1.800     albertel 3450:         foreach my $entry (split(/&/,$rolesdump)) {
                   3451: 	  if ($entry!~/^rolesdef_/) {
                   3452:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3453: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3454:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3455: 	    if ($role=~/^cr/) { 
1.807     albertel 3456: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3457: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3458: 		    ($tend,$tstart)=split('_',$trest);
                   3459: 		} else {
                   3460: 		    $trole=$role;
                   3461: 		}
1.678     raeburn  3462:             } elsif ($role =~ m|^gr/|) {
                   3463:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3464:                 ($trole,$group_privs) = split(/\//,$trole);
                   3465:                 $group_privs = &unescape($group_privs);
1.587     albertel 3466: 	    } else {
                   3467: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3468: 	    }
1.743     albertel 3469: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3470: 					 $username);
                   3471: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3472:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3473:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3474:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3475: 		my $spec=$trole.'.'.$area;
                   3476: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3477: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3478:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3479:                 } elsif ($trole eq 'gr') {
                   3480:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3481: 		} else {
1.567     raeburn  3482:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3483: 		}
1.12      www      3484:             }
1.662     raeburn  3485:           }
1.191     harris41 3486:         }
1.743     albertel 3487:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3488:         $userroles{'user.adv'}    = $adv;
                   3489: 	$userroles{'user.author'} = $author;
1.620     albertel 3490:         $env{'user.adv'}=$adv;
1.11      www      3491:     }
1.743     albertel 3492:     return \%userroles;  
1.11      www      3493: }
                   3494: 
1.567     raeburn  3495: sub set_arearole {
                   3496:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3497: # log the associated role with the area
                   3498:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3499:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3500: }
                   3501: 
                   3502: sub custom_roleprivs {
                   3503:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3504:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3505:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3506:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3507:         my ($rdummy,$roledef)=
                   3508:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3509:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3510:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3511:             if (defined($syspriv)) {
                   3512:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3513:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3514:             }
                   3515:             if ($tdomain ne '') {
                   3516:                 if (defined($dompriv)) {
                   3517:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3518:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3519:                 }
                   3520:                 if (($trest ne '') && (defined($coursepriv))) {
                   3521:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3522:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3523:                 }
                   3524:             }
                   3525:         }
                   3526:     }
                   3527: }
                   3528: 
1.678     raeburn  3529: sub group_roleprivs {
                   3530:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3531:     my $access = 1;
                   3532:     my $now = time;
                   3533:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3534:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3535:     if ($access) {
1.811     albertel 3536:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3537:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3538:     }
                   3539: }
1.567     raeburn  3540: 
                   3541: sub standard_roleprivs {
                   3542:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3543:     if (defined($pr{$trole.':s'})) {
                   3544:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3545:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3546:     }
                   3547:     if ($tdomain ne '') {
                   3548:         if (defined($pr{$trole.':d'})) {
                   3549:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3550:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3551:         }
                   3552:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3553:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3554:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3555:         }
                   3556:     }
                   3557: }
                   3558: 
                   3559: sub set_userprivs {
1.678     raeburn  3560:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3561:     my $author=0;
                   3562:     my $adv=0;
1.678     raeburn  3563:     my %grouproles = ();
                   3564:     if (keys(%{$allgroups}) > 0) {
                   3565:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3566:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3567:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3568:                 $trole = $1;
                   3569:                 $area = $2;
1.681     raeburn  3570:                 $sec = $3;
                   3571:                 $extendedarea = $area.$sec;
                   3572:                 if (exists($$allgroups{$area})) {
                   3573:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3574:                         my $spec = $trole.'.'.$extendedarea;
                   3575:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3576:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3577:                     }
                   3578:                 }
                   3579:             }
                   3580:         }
                   3581:     }
1.800     albertel 3582:     foreach my $group (keys(%grouproles)) {
                   3583:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3584:     }
1.800     albertel 3585:     foreach my $role (keys(%{$allroles})) {
                   3586:         my %thesepriv;
1.941     raeburn  3587:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3588:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3589:             if ($item ne '') {
                   3590:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3591:                 if ($restrictions eq '') {
                   3592:                     $thesepriv{$privilege}='F';
                   3593:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3594:                     $thesepriv{$privilege}.=$restrictions;
                   3595:                 }
                   3596:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3597:             }
                   3598:         }
                   3599:         my $thesestr='';
1.800     albertel 3600:         foreach my $priv (keys(%thesepriv)) {
                   3601: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3602: 	}
                   3603:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3604:     }
                   3605:     return ($author,$adv);
                   3606: }
                   3607: 
1.12      www      3608: # --------------------------------------------------------------- get interface
                   3609: 
                   3610: sub get {
1.131     albertel 3611:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3612:    my $items='';
1.800     albertel 3613:    foreach my $item (@$storearr) {
                   3614:        $items.=&escape($item).'&';
1.191     harris41 3615:    }
1.12      www      3616:    $items=~s/\&$//;
1.620     albertel 3617:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3618:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3619:    my $uhome=&homeserver($uname,$udomain);
                   3620: 
1.133     albertel 3621:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3622:    my @pairs=split(/\&/,$rep);
1.273     albertel 3623:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3624:      return @pairs;
                   3625:    }
1.15      www      3626:    my %returnhash=();
1.42      www      3627:    my $i=0;
1.800     albertel 3628:    foreach my $item (@$storearr) {
                   3629:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3630:       $i++;
1.191     harris41 3631:    }
1.15      www      3632:    return %returnhash;
1.27      www      3633: }
                   3634: 
                   3635: # --------------------------------------------------------------- del interface
                   3636: 
                   3637: sub del {
1.133     albertel 3638:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3639:    my $items='';
1.800     albertel 3640:    foreach my $item (@$storearr) {
                   3641:        $items.=&escape($item).'&';
1.191     harris41 3642:    }
1.27      www      3643:    $items=~s/\&$//;
1.620     albertel 3644:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3645:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3646:    my $uhome=&homeserver($uname,$udomain);
                   3647: 
                   3648:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3649: }
                   3650: 
                   3651: # -------------------------------------------------------------- dump interface
                   3652: 
                   3653: sub dump {
1.755     albertel 3654:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3655:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3656:     if (!$uname) { $uname=$env{'user.name'}; }
                   3657:     my $uhome=&homeserver($uname,$udomain);
                   3658:     if ($regexp) {
                   3659: 	$regexp=&escape($regexp);
                   3660:     } else {
                   3661: 	$regexp='.';
                   3662:     }
                   3663:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3664:     my @pairs=split(/\&/,$rep);
                   3665:     my %returnhash=();
                   3666:     foreach my $item (@pairs) {
                   3667: 	my ($key,$value)=split(/=/,$item,2);
                   3668: 	$key = &unescape($key);
                   3669: 	next if ($key =~ /^error: 2 /);
                   3670: 	$returnhash{$key}=&thaw_unescape($value);
                   3671:     }
                   3672:     return %returnhash;
1.407     www      3673: }
                   3674: 
1.717     albertel 3675: # --------------------------------------------------------- dumpstore interface
                   3676: 
                   3677: sub dumpstore {
                   3678:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3679:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3680:    if (!$uname) { $uname=$env{'user.name'}; }
                   3681:    my $uhome=&homeserver($uname,$udomain);
                   3682:    if ($regexp) {
                   3683:        $regexp=&escape($regexp);
                   3684:    } else {
                   3685:        $regexp='.';
                   3686:    }
                   3687:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3688:    my @pairs=split(/\&/,$rep);
                   3689:    my %returnhash=();
                   3690:    foreach my $item (@pairs) {
                   3691:        my ($key,$value)=split(/=/,$item,2);
                   3692:        next if ($key =~ /^error: 2 /);
                   3693:        $returnhash{$key}=&thaw_unescape($value);
                   3694:    }
                   3695:    return %returnhash;
1.717     albertel 3696: }
                   3697: 
1.407     www      3698: # -------------------------------------------------------------- keys interface
                   3699: 
                   3700: sub getkeys {
                   3701:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3702:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3703:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3704:    my $uhome=&homeserver($uname,$udomain);
                   3705:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3706:    my @keyarray=();
1.800     albertel 3707:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3708:       next if ($key =~ /^error: 2 /);
1.800     albertel 3709:       push(@keyarray,&unescape($key));
1.407     www      3710:    }
                   3711:    return @keyarray;
1.318     matthew  3712: }
                   3713: 
1.319     matthew  3714: # --------------------------------------------------------------- currentdump
                   3715: sub currentdump {
1.328     matthew  3716:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3717:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3718:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3719:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3720:    my $uhome = &homeserver($sname,$sdom);
                   3721:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3722:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3723:    #
1.318     matthew  3724:    my %returnhash=();
1.319     matthew  3725:    #
                   3726:    if ($rep eq "unknown_cmd") { 
                   3727:        # an old lond will not know currentdump
                   3728:        # Do a dump and make it look like a currentdump
1.822     albertel 3729:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3730:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3731:        my %hash = @tmp;
                   3732:        @tmp=();
1.424     matthew  3733:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3734:    } else {
                   3735:        my @pairs=split(/\&/,$rep);
1.800     albertel 3736:        foreach my $pair (@pairs) {
                   3737:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3738:            my ($symb,$param) = split(/:/,$key);
                   3739:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3740:                                                         &thaw_unescape($value);
1.319     matthew  3741:        }
1.191     harris41 3742:    }
1.12      www      3743:    return %returnhash;
1.424     matthew  3744: }
                   3745: 
                   3746: sub convert_dump_to_currentdump{
                   3747:     my %hash = %{shift()};
                   3748:     my %returnhash;
                   3749:     # Code ripped from lond, essentially.  The only difference
                   3750:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3751:     # we might run in to problems with parameter names =~ /^v\./
                   3752:     while (my ($key,$value) = each(%hash)) {
                   3753:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3754: 	$symb  = &unescape($symb);
                   3755: 	$param = &unescape($param);
1.424     matthew  3756:         next if ($v eq 'version' || $symb eq 'keys');
                   3757:         next if (exists($returnhash{$symb}) &&
                   3758:                  exists($returnhash{$symb}->{$param}) &&
                   3759:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3760:         $returnhash{$symb}->{$param}=$value;
                   3761:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3762:     }
                   3763:     #
                   3764:     # Remove all of the keys in the hashes which keep track of
                   3765:     # the version of the parameter.
                   3766:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3767:         # use a foreach because we are going to delete from the hash.
                   3768:         foreach my $key (keys(%$param_hash)) {
                   3769:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3770:         }
                   3771:     }
                   3772:     return \%returnhash;
1.12      www      3773: }
                   3774: 
1.627     albertel 3775: # ------------------------------------------------------ critical inc interface
                   3776: 
                   3777: sub cinc {
                   3778:     return &inc(@_,'critical');
                   3779: }
                   3780: 
1.449     matthew  3781: # --------------------------------------------------------------- inc interface
                   3782: 
                   3783: sub inc {
1.627     albertel 3784:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3785:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3786:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3787:     my $uhome=&homeserver($uname,$udomain);
                   3788:     my $items='';
                   3789:     if (! ref($store)) {
                   3790:         # got a single value, so use that instead
                   3791:         $items = &escape($store).'=&';
                   3792:     } elsif (ref($store) eq 'SCALAR') {
                   3793:         $items = &escape($$store).'=&';        
                   3794:     } elsif (ref($store) eq 'ARRAY') {
                   3795:         $items = join('=&',map {&escape($_);} @{$store});
                   3796:     } elsif (ref($store) eq 'HASH') {
                   3797:         while (my($key,$value) = each(%{$store})) {
                   3798:             $items.= &escape($key).'='.&escape($value).'&';
                   3799:         }
                   3800:     }
                   3801:     $items=~s/\&$//;
1.627     albertel 3802:     if ($critical) {
                   3803: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3804:     } else {
                   3805: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3806:     }
1.449     matthew  3807: }
                   3808: 
1.12      www      3809: # --------------------------------------------------------------- put interface
                   3810: 
                   3811: sub put {
1.134     albertel 3812:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3813:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3814:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3815:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3816:    my $items='';
1.800     albertel 3817:    foreach my $item (keys(%$storehash)) {
                   3818:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3819:    }
1.12      www      3820:    $items=~s/\&$//;
1.134     albertel 3821:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3822: }
                   3823: 
1.631     albertel 3824: # ------------------------------------------------------------ newput interface
                   3825: 
                   3826: sub newput {
                   3827:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3828:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3829:    if (!$uname) { $uname=$env{'user.name'}; }
                   3830:    my $uhome=&homeserver($uname,$udomain);
                   3831:    my $items='';
                   3832:    foreach my $key (keys(%$storehash)) {
                   3833:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3834:    }
                   3835:    $items=~s/\&$//;
                   3836:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3837: }
                   3838: 
                   3839: # ---------------------------------------------------------  putstore interface
                   3840: 
1.524     raeburn  3841: sub putstore {
1.715     albertel 3842:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3843:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3844:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3845:    my $uhome=&homeserver($uname,$udomain);
                   3846:    my $items='';
1.715     albertel 3847:    foreach my $key (keys(%$storehash)) {
                   3848:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3849:    }
1.715     albertel 3850:    $items=~s/\&$//;
1.716     albertel 3851:    my $esc_symb=&escape($symb);
                   3852:    my $esc_v=&escape($version);
1.715     albertel 3853:    my $reply =
1.716     albertel 3854:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3855: 	      $uhome);
                   3856:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3857:        # gfall back to way things use to be done
1.715     albertel 3858:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3859: 			    $uname);
1.524     raeburn  3860:    }
1.715     albertel 3861:    return $reply;
                   3862: }
                   3863: 
                   3864: sub old_putstore {
1.716     albertel 3865:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3866:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3867:     if (!$uname) { $uname=$env{'user.name'}; }
                   3868:     my $uhome=&homeserver($uname,$udomain);
                   3869:     my %newstorehash;
1.800     albertel 3870:     foreach my $item (keys(%$storehash)) {
                   3871: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3872: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3873:     }
                   3874:     my $items='';
                   3875:     my %allitems = ();
1.800     albertel 3876:     foreach my $item (keys(%newstorehash)) {
                   3877: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3878: 	    my $key = $1.':keys:'.$2;
                   3879: 	    $allitems{$key} .= $3.':';
                   3880: 	}
1.800     albertel 3881: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3882:     }
1.800     albertel 3883:     foreach my $item (keys(%allitems)) {
                   3884: 	$allitems{$item} =~ s/\:$//;
                   3885: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3886:     }
                   3887:     $items=~s/\&$//;
                   3888:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3889: }
                   3890: 
1.47      www      3891: # ------------------------------------------------------ critical put interface
                   3892: 
                   3893: sub cput {
1.134     albertel 3894:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3895:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3896:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3897:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3898:    my $items='';
1.800     albertel 3899:    foreach my $item (keys(%$storehash)) {
                   3900:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3901:    }
1.47      www      3902:    $items=~s/\&$//;
1.134     albertel 3903:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3904: }
                   3905: 
                   3906: # -------------------------------------------------------------- eget interface
                   3907: 
                   3908: sub eget {
1.133     albertel 3909:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3910:    my $items='';
1.800     albertel 3911:    foreach my $item (@$storearr) {
                   3912:        $items.=&escape($item).'&';
1.191     harris41 3913:    }
1.12      www      3914:    $items=~s/\&$//;
1.620     albertel 3915:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3916:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3917:    my $uhome=&homeserver($uname,$udomain);
                   3918:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3919:    my @pairs=split(/\&/,$rep);
                   3920:    my %returnhash=();
1.42      www      3921:    my $i=0;
1.800     albertel 3922:    foreach my $item (@$storearr) {
                   3923:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3924:       $i++;
1.191     harris41 3925:    }
1.12      www      3926:    return %returnhash;
                   3927: }
                   3928: 
1.667     albertel 3929: # ------------------------------------------------------------ tmpput interface
                   3930: sub tmpput {
1.802     raeburn  3931:     my ($storehash,$server,$context)=@_;
1.667     albertel 3932:     my $items='';
1.800     albertel 3933:     foreach my $item (keys(%$storehash)) {
                   3934: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3935:     }
                   3936:     $items=~s/\&$//;
1.802     raeburn  3937:     if (defined($context)) {
                   3938:         $items .= ':'.&escape($context);
                   3939:     }
1.667     albertel 3940:     return &reply("tmpput:$items",$server);
                   3941: }
                   3942: 
                   3943: # ------------------------------------------------------------ tmpget interface
                   3944: sub tmpget {
1.688     albertel 3945:     my ($token,$server)=@_;
                   3946:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3947:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3948:     my %returnhash;
                   3949:     foreach my $item (split(/\&/,$rep)) {
                   3950: 	my ($key,$value)=split(/=/,$item);
                   3951: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3952:     }
                   3953:     return %returnhash;
                   3954: }
                   3955: 
1.688     albertel 3956: # ------------------------------------------------------------ tmpget interface
                   3957: sub tmpdel {
                   3958:     my ($token,$server)=@_;
                   3959:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3960:     return &reply("tmpdel:$token",$server);
                   3961: }
                   3962: 
1.765     albertel 3963: # -------------------------------------------------- portfolio access checking
                   3964: 
                   3965: sub portfolio_access {
1.766     albertel 3966:     my ($requrl) = @_;
1.765     albertel 3967:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3968:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3969:     if ($result) {
                   3970:         my %setters;
                   3971:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3972:             my ($startblock,$endblock) =
                   3973:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3974:             if ($startblock && $endblock) {
                   3975:                 return 'B';
                   3976:             }
                   3977:         } else {
                   3978:             my ($startblock,$endblock) =
                   3979:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3980:             if ($startblock && $endblock) {
                   3981:                 return 'B';
                   3982:             }
                   3983:         }
                   3984:     }
1.765     albertel 3985:     if ($result eq 'ok') {
1.766     albertel 3986:        return 'F';
1.765     albertel 3987:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3988:        return 'A';
1.765     albertel 3989:     }
1.766     albertel 3990:     return '';
1.765     albertel 3991: }
                   3992: 
                   3993: sub get_portfolio_access {
1.767     albertel 3994:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3995: 
                   3996:     if (!ref($access_hash)) {
                   3997: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3998: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3999: 						   $file_name);
                   4000: 	$access_hash = $access_controls{$file_name};
                   4001:     }
                   4002: 
1.765     albertel 4003:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4004:     my $now = time;
                   4005:     if (ref($access_hash) eq 'HASH') {
                   4006:         foreach my $key (keys(%{$access_hash})) {
                   4007:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4008:             if ($start > $now) {
                   4009:                 next;
                   4010:             }
                   4011:             if ($end && $end<$now) {
                   4012:                 next;
                   4013:             }
                   4014:             if ($scope eq 'public') {
                   4015:                 $public = $key;
                   4016:                 last;
                   4017:             } elsif ($scope eq 'guest') {
                   4018:                 $guest = $key;
                   4019:             } elsif ($scope eq 'domains') {
                   4020:                 push(@domains,$key);
                   4021:             } elsif ($scope eq 'users') {
                   4022:                 push(@users,$key);
                   4023:             } elsif ($scope eq 'course') {
                   4024:                 push(@courses,$key);
                   4025:             } elsif ($scope eq 'group') {
                   4026:                 push(@groups,$key);
                   4027:             }
                   4028:         }
                   4029:         if ($public) {
                   4030:             return 'ok';
                   4031:         }
                   4032:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4033:             if ($guest) {
                   4034:                 return $guest;
                   4035:             }
                   4036:         } else {
                   4037:             if (@domains > 0) {
                   4038:                 foreach my $domkey (@domains) {
                   4039:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4040:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4041:                             return 'ok';
                   4042:                         }
                   4043:                     }
                   4044:                 }
                   4045:             }
                   4046:             if (@users > 0) {
                   4047:                 foreach my $userkey (@users) {
1.865     raeburn  4048:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4049:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4050:                             if (ref($item) eq 'HASH') {
                   4051:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4052:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4053:                                     return 'ok';
                   4054:                                 }
                   4055:                             }
                   4056:                         }
                   4057:                     } 
1.765     albertel 4058:                 }
                   4059:             }
                   4060:             my %roleshash;
                   4061:             my @courses_and_groups = @courses;
                   4062:             push(@courses_and_groups,@groups); 
                   4063:             if (@courses_and_groups > 0) {
                   4064:                 my (%allgroups,%allroles); 
                   4065:                 my ($start,$end,$role,$sec,$group);
                   4066:                 foreach my $envkey (%env) {
1.811     albertel 4067:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4068:                         my $cid = $2.'_'.$3; 
                   4069:                         if ($1 eq 'gr') {
                   4070:                             $group = $4;
                   4071:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4072:                         } else {
                   4073:                             if ($4 eq '') {
                   4074:                                 $sec = 'none';
                   4075:                             } else {
                   4076:                                 $sec = $4;
                   4077:                             }
                   4078:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4079:                         }
1.811     albertel 4080:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4081:                         my $cid = $2.'_'.$3;
                   4082:                         if ($4 eq '') {
                   4083:                             $sec = 'none';
                   4084:                         } else {
                   4085:                             $sec = $4;
                   4086:                         }
                   4087:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4088:                     }
                   4089:                 }
                   4090:                 if (keys(%allroles) == 0) {
                   4091:                     return;
                   4092:                 }
                   4093:                 foreach my $key (@courses_and_groups) {
                   4094:                     my %content = %{$$access_hash{$key}};
                   4095:                     my $cnum = $content{'number'};
                   4096:                     my $cdom = $content{'domain'};
                   4097:                     my $cid = $cdom.'_'.$cnum;
                   4098:                     if (!exists($allroles{$cid})) {
                   4099:                         next;
                   4100:                     }    
                   4101:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4102:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4103:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4104:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4105:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4106:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4107:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4108:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4109:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4110:                                         if (grep/^all$/,@sections) {
                   4111:                                             return 'ok';
                   4112:                                         } else {
                   4113:                                             if (grep/^$sec$/,@sections) {
                   4114:                                                 return 'ok';
                   4115:                                             }
                   4116:                                         }
                   4117:                                     }
                   4118:                                 }
                   4119:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4120:                                     if (grep/^none$/,@groups) {
                   4121:                                         return 'ok';
                   4122:                                     }
                   4123:                                 } else {
                   4124:                                     if (grep/^all$/,@groups) {
                   4125:                                         return 'ok';
                   4126:                                     } 
                   4127:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4128:                                         if (grep/^$group$/,@groups) {
                   4129:                                             return 'ok';
                   4130:                                         }
                   4131:                                     }
                   4132:                                 } 
                   4133:                             }
                   4134:                         }
                   4135:                     }
                   4136:                 }
                   4137:             }
                   4138:             if ($guest) {
                   4139:                 return $guest;
                   4140:             }
                   4141:         }
                   4142:     }
                   4143:     return;
                   4144: }
                   4145: 
                   4146: sub course_group_datechecker {
                   4147:     my ($dates,$now,$status) = @_;
                   4148:     my ($start,$end) = split(/\./,$dates);
                   4149:     if (!$start && !$end) {
                   4150:         return 'ok';
                   4151:     }
                   4152:     if (grep/^active$/,@{$status}) {
                   4153:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4154:             return 'ok';
                   4155:         }
                   4156:     }
                   4157:     if (grep/^previous$/,@{$status}) {
                   4158:         if ($end > $now ) {
                   4159:             return 'ok';
                   4160:         }
                   4161:     }
                   4162:     if (grep/^future$/,@{$status}) {
                   4163:         if ($start > $now) {
                   4164:             return 'ok';
                   4165:         }
                   4166:     }
                   4167:     return; 
                   4168: }
                   4169: 
                   4170: sub parse_portfolio_url {
                   4171:     my ($url) = @_;
                   4172: 
                   4173:     my ($type,$udom,$unum,$group,$file_name);
                   4174:     
1.823     albertel 4175:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4176: 	$type = 1;
                   4177:         $udom = $1;
                   4178:         $unum = $2;
                   4179:         $file_name = $3;
1.823     albertel 4180:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4181: 	$type = 2;
                   4182:         $udom = $1;
                   4183:         $unum = $2;
                   4184:         $group = $3;
                   4185:         $file_name = $3.'/'.$4;
                   4186:     }
                   4187:     if (wantarray) {
                   4188: 	return ($type,$udom,$unum,$file_name,$group);
                   4189:     }
                   4190:     return $type;
                   4191: }
                   4192: 
                   4193: sub is_portfolio_url {
                   4194:     my ($url) = @_;
                   4195:     return scalar(&parse_portfolio_url($url));
                   4196: }
                   4197: 
1.798     raeburn  4198: sub is_portfolio_file {
                   4199:     my ($file) = @_;
1.820     raeburn  4200:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4201:         return 1;
                   4202:     }
                   4203:     return;
                   4204: }
                   4205: 
                   4206: 
1.341     www      4207: # ---------------------------------------------- Custom access rule evaluation
                   4208: 
                   4209: sub customaccess {
                   4210:     my ($priv,$uri)=@_;
1.807     albertel 4211:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4212:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4213:     $udom = &LONCAPA::clean_domain($udom);
                   4214:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4215:     my $access=0;
1.800     albertel 4216:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4217: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4218: 	if ($type eq 'user') {
                   4219: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4220: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4221: 		if ($tdom) {
                   4222: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4223: 		}
1.896     albertel 4224: 		if ($tuname) {
                   4225: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4226: 		}
                   4227: 		$access=($effect eq 'allow');
                   4228: 		last;
                   4229: 	    }
                   4230: 	} else {
                   4231: 	    if ($role) {
                   4232: 		if ($role ne $urole) { next; }
                   4233: 	    }
                   4234: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4235: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4236: 		if ($tdom) {
                   4237: 		    if ($tdom ne $udom) { next; }
                   4238: 		}
                   4239: 		if ($tcrs) {
                   4240: 		    if ($tcrs ne $ucrs) { next; }
                   4241: 		}
                   4242: 		if ($tsec) {
                   4243: 		    if ($tsec ne $usec) { next; }
                   4244: 		}
                   4245: 		$access=($effect eq 'allow');
                   4246: 		last;
                   4247: 	    }
                   4248: 	    if ($realm eq '' && $role eq '') {
                   4249: 		$access=($effect eq 'allow');
                   4250: 	    }
1.402     bowersj2 4251: 	}
1.341     www      4252:     }
                   4253:     return $access;
                   4254: }
                   4255: 
1.103     harris41 4256: # ------------------------------------------------- Check for a user privilege
1.12      www      4257: 
                   4258: sub allowed {
1.810     raeburn  4259:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4260:     my $ver_orguri=$uri;
1.439     www      4261:     $uri=&deversion($uri);
1.152     www      4262:     my $orguri=$uri;
1.52      www      4263:     $uri=&declutter($uri);
1.809     raeburn  4264: 
1.810     raeburn  4265:     if ($priv eq 'evb') {
                   4266: # Evade communication block restrictions for specified role in a course
                   4267:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4268:             return $1;
                   4269:         } else {
                   4270:             return;
                   4271:         }
                   4272:     }
                   4273: 
1.620     albertel 4274:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4275: # Free bre access to adm and meta resources
1.775     albertel 4276:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4277: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4278: 	&& ($priv eq 'bre')) {
1.14      www      4279: 	return 'F';
1.159     www      4280:     }
                   4281: 
1.545     banghart 4282: # Free bre access to user's own portfolio contents
1.714     raeburn  4283:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4284:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4285: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4286:         my %setters;
                   4287:         my ($startblock,$endblock) = 
                   4288:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4289:         if ($startblock && $endblock) {
                   4290:             return 'B';
                   4291:         } else {
                   4292:             return 'F';
                   4293:         }
1.545     banghart 4294:     }
                   4295: 
1.762     raeburn  4296: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4297:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4298:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4299:         if (exists($env{'request.course.id'})) {
                   4300:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4301:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4302:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4303:                 my $courseprivid=$env{'request.course.id'};
                   4304:                 $courseprivid=~s/\_/\//;
                   4305:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4306:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4307:                     return $1; 
1.762     raeburn  4308:                 } else {
                   4309:                     if ($env{'request.course.sec'}) {
                   4310:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4311:                     }
                   4312:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4313:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4314:                         return $2;
                   4315:                     }
1.714     raeburn  4316:                 }
                   4317:             }
                   4318:         }
                   4319:     }
                   4320: 
1.159     www      4321: # Free bre to public access
                   4322: 
                   4323:     if ($priv eq 'bre') {
1.238     www      4324:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4325: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4326:            return 'F'; 
                   4327:         }
1.238     www      4328:         if ($copyright eq 'priv') {
                   4329:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4330: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4331: 		return '';
                   4332:             }
                   4333:         }
                   4334:         if ($copyright eq 'domain') {
                   4335:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4336: 	    unless (($env{'user.domain'} eq $1) ||
                   4337:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4338: 		return '';
                   4339:             }
1.262     matthew  4340:         }
1.620     albertel 4341:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4342:             # Library role, so allow browsing of resources in this domain.
                   4343:             return 'F';
1.238     www      4344:         }
1.341     www      4345:         if ($copyright eq 'custom') {
                   4346: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4347:         }
1.14      www      4348:     }
1.264     matthew  4349:     # Domain coordinator is trying to create a course
1.620     albertel 4350:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4351:         # uri is the requested domain in this case.
                   4352:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4353:         # a role of dc for the domain in question.
1.620     albertel 4354:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4355:     }
1.29      www      4356: 
1.52      www      4357:     my $thisallowed='';
                   4358:     my $statecond=0;
                   4359:     my $courseprivid='';
                   4360: 
                   4361: # Course
                   4362: 
1.620     albertel 4363:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4364:        $thisallowed.=$1;
                   4365:     }
1.29      www      4366: 
1.52      www      4367: # Domain
                   4368: 
1.620     albertel 4369:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4370:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4371:        $thisallowed.=$1;
                   4372:     }
1.52      www      4373: 
                   4374: # Course: uri itself is a course
1.66      www      4375:     my $courseuri=$uri;
                   4376:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4377:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4378: 
1.620     albertel 4379:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4380:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4381:        $thisallowed.=$1;
                   4382:     }
1.29      www      4383: 
1.665     albertel 4384: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4385: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4386:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4387: 	$thisallowed='';
1.671     raeburn  4388:         my ($match)=&is_on_map($uri);
                   4389:         if ($match) {
                   4390:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4391:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4392:                 $thisallowed.=$1;
                   4393:             }
                   4394:         } else {
1.705     albertel 4395:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4396:             if ($refuri) {
                   4397:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4398:                     $thisallowed='F';
1.671     raeburn  4399:                 } else {
                   4400:                     $refuri=&declutter($refuri);
                   4401:                     my ($match) = &is_on_map($refuri);
                   4402:                     if ($match) {
                   4403:                         $thisallowed='F';
                   4404:                     }
1.669     raeburn  4405:                 }
1.671     raeburn  4406:             }
                   4407:         }
1.314     www      4408:     }
1.492     albertel 4409: 
1.766     albertel 4410:     if ($priv eq 'bre'
                   4411: 	&& $thisallowed ne 'F' 
                   4412: 	&& $thisallowed ne '2'
                   4413: 	&& &is_portfolio_url($uri)) {
                   4414: 	$thisallowed = &portfolio_access($uri);
                   4415:     }
                   4416:     
1.52      www      4417: # Full access at system, domain or course-wide level? Exit.
1.29      www      4418: 
                   4419:     if ($thisallowed=~/F/) {
                   4420: 	return 'F';
                   4421:     }
                   4422: 
1.52      www      4423: # If this is generating or modifying users, exit with special codes
1.29      www      4424: 
1.643     www      4425:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4426: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4427: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4428: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4429: 	    unless ($auname) { return $thisallowed; }
                   4430: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4431: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4432: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4433: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4434: 	}
1.52      www      4435: 	return $thisallowed;
                   4436:     }
                   4437: #
1.103     harris41 4438: # Gathered so far: system, domain and course wide privileges
1.52      www      4439: #
                   4440: # Course: See if uri or referer is an individual resource that is part of 
                   4441: # the course
                   4442: 
1.620     albertel 4443:     if ($env{'request.course.id'}) {
1.232     www      4444: 
1.620     albertel 4445:        $courseprivid=$env{'request.course.id'};
                   4446:        if ($env{'request.course.sec'}) {
                   4447:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4448:        }
                   4449:        $courseprivid=~s/\_/\//;
                   4450:        my $checkreferer=1;
1.232     www      4451:        my ($match,$cond)=&is_on_map($uri);
                   4452:        if ($match) {
                   4453:            $statecond=$cond;
1.620     albertel 4454:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4455:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4456:                $thisallowed.=$1;
                   4457:                $checkreferer=0;
                   4458:            }
1.29      www      4459:        }
1.83      www      4460:        
1.148     www      4461:        if ($checkreferer) {
1.620     albertel 4462: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4463:             unless ($refuri) {
1.800     albertel 4464:                 foreach my $key (keys(%env)) {
                   4465: 		    if ($key=~/^httpref\..*\*/) {
                   4466: 			my $pattern=$key;
1.156     www      4467:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4468:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4469:                         $pattern=~s/\//\\\//g;
1.152     www      4470:                         if ($orguri=~/$pattern/) {
1.800     albertel 4471: 			    $refuri=$env{$key};
1.148     www      4472:                         }
                   4473:                     }
1.191     harris41 4474:                 }
1.148     www      4475:             }
1.232     www      4476: 
1.148     www      4477:          if ($refuri) { 
1.152     www      4478: 	  $refuri=&declutter($refuri);
1.232     www      4479:           my ($match,$cond)=&is_on_map($refuri);
                   4480:             if ($match) {
                   4481:               my $refstatecond=$cond;
1.620     albertel 4482:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4483:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4484:                   $thisallowed.=$1;
1.53      www      4485:                   $uri=$refuri;
                   4486:                   $statecond=$refstatecond;
1.52      www      4487:               }
                   4488:           }
1.148     www      4489:         }
1.29      www      4490:        }
1.52      www      4491:    }
1.29      www      4492: 
1.52      www      4493: #
1.103     harris41 4494: # Gathered now: all privileges that could apply, and condition number
1.52      www      4495: # 
                   4496: #
                   4497: # Full or no access?
                   4498: #
1.29      www      4499: 
1.52      www      4500:     if ($thisallowed=~/F/) {
                   4501: 	return 'F';
                   4502:     }
1.29      www      4503: 
1.52      www      4504:     unless ($thisallowed) {
                   4505:         return '';
                   4506:     }
1.29      www      4507: 
1.52      www      4508: # Restrictions exist, deal with them
                   4509: #
                   4510: #   C:according to course preferences
                   4511: #   R:according to resource settings
                   4512: #   L:unless locked
                   4513: #   X:according to user session state
                   4514: #
                   4515: 
                   4516: # Possibly locked functionality, check all courses
1.54      www      4517: # Locks might take effect only after 10 minutes cache expiration for other
                   4518: # courses, and 2 minutes for current course
1.52      www      4519: 
                   4520:     my $envkey;
                   4521:     if ($thisallowed=~/L/) {
1.620     albertel 4522:         foreach $envkey (keys %env) {
1.54      www      4523:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4524:                my $courseid=$2;
                   4525:                my $roleid=$1.'.'.$2;
1.92      www      4526:                $courseid=~s/^\///;
1.54      www      4527:                my $expiretime=600;
1.620     albertel 4528:                if ($env{'request.role'} eq $roleid) {
1.54      www      4529: 		  $expiretime=120;
                   4530:                }
                   4531: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4532:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4533:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4534: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4535:                }
1.620     albertel 4536:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4537:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4538: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4539:                        &log($env{'user.domain'},$env{'user.name'},
                   4540:                             $env{'user.home'},
1.57      www      4541:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4542:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4543:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4544: 		       return '';
                   4545:                    }
                   4546:                }
1.620     albertel 4547:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4548:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4549: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4550:                        &log($env{'user.domain'},$env{'user.name'},
                   4551:                             $env{'user.home'},
1.57      www      4552:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4553:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4554:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4555: 		       return '';
                   4556:                    }
                   4557:                }
                   4558: 	   }
1.29      www      4559:        }
1.52      www      4560:     }
                   4561:    
                   4562: #
                   4563: # Rest of the restrictions depend on selected course
                   4564: #
                   4565: 
1.620     albertel 4566:     unless ($env{'request.course.id'}) {
1.766     albertel 4567: 	if ($thisallowed eq 'A') {
                   4568: 	    return 'A';
1.814     raeburn  4569:         } elsif ($thisallowed eq 'B') {
                   4570:             return 'B';
1.766     albertel 4571: 	} else {
                   4572: 	    return '1';
                   4573: 	}
1.52      www      4574:     }
1.29      www      4575: 
1.52      www      4576: #
                   4577: # Now user is definitely in a course
                   4578: #
1.53      www      4579: 
                   4580: 
                   4581: # Course preferences
                   4582: 
                   4583:    if ($thisallowed=~/C/) {
1.620     albertel 4584:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4585:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4586:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4587: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4588: 	   if ($priv ne 'pch') { 
                   4589: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4590: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4591: 			$env{'request.course.id'});
                   4592: 	   }
1.237     www      4593:            return '';
                   4594:        }
                   4595: 
1.620     albertel 4596:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4597: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4598: 	   if ($priv ne 'pch') { 
                   4599: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4600: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4601: 			$env{'request.course.id'});
                   4602: 	   }
1.54      www      4603:            return '';
                   4604:        }
1.53      www      4605:    }
                   4606: 
                   4607: # Resource preferences
                   4608: 
                   4609:    if ($thisallowed=~/R/) {
1.620     albertel 4610:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4611:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4612: 	   if ($priv ne 'pch') { 
                   4613: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4614: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4615: 	   }
                   4616: 	   return '';
1.54      www      4617:        }
1.53      www      4618:    }
1.30      www      4619: 
1.246     www      4620: # Restricted by state or randomout?
1.30      www      4621: 
1.52      www      4622:    if ($thisallowed=~/X/) {
1.620     albertel 4623:       if ($env{'acc.randomout'}) {
1.579     albertel 4624: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4625:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4626:             return ''; 
                   4627:          }
1.247     www      4628:       }
                   4629:       if (&condval($statecond)) {
1.52      www      4630: 	 return '2';
                   4631:       } else {
                   4632:          return '';
                   4633:       }
                   4634:    }
1.30      www      4635: 
1.766     albertel 4636:     if ($thisallowed eq 'A') {
                   4637: 	return 'A';
1.814     raeburn  4638:     } elsif ($thisallowed eq 'B') {
                   4639:         return 'B';
1.766     albertel 4640:     }
1.52      www      4641:    return 'F';
1.232     www      4642: }
                   4643: 
1.710     albertel 4644: sub split_uri_for_cond {
                   4645:     my $uri=&deversion(&declutter(shift));
                   4646:     my @uriparts=split(/\//,$uri);
                   4647:     my $filename=pop(@uriparts);
                   4648:     my $pathname=join('/',@uriparts);
                   4649:     return ($pathname,$filename);
                   4650: }
1.232     www      4651: # --------------------------------------------------- Is a resource on the map?
                   4652: 
                   4653: sub is_on_map {
1.710     albertel 4654:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4655:     #Trying to find the conditional for the file
1.620     albertel 4656:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4657: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4658:     if ($match) {
1.289     bowersj2 4659: 	return (1,$1);
                   4660:     } else {
1.434     www      4661: 	return (0,0);
1.289     bowersj2 4662:     }
1.12      www      4663: }
                   4664: 
1.427     www      4665: # --------------------------------------------------------- Get symb from alias
                   4666: 
                   4667: sub get_symb_from_alias {
                   4668:     my $symb=shift;
                   4669:     my ($map,$resid,$url)=&decode_symb($symb);
                   4670: # Already is a symb
                   4671:     if ($url) { return $symb; }
                   4672: # Must be an alias
                   4673:     my $aliassymb='';
                   4674:     my %bighash;
1.620     albertel 4675:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4676:                             &GDBM_READER(),0640)) {
                   4677:         my $rid=$bighash{'mapalias_'.$symb};
                   4678: 	if ($rid) {
                   4679: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4680: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4681: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4682: 	}
                   4683:         untie %bighash;
                   4684:     }
                   4685:     return $aliassymb;
                   4686: }
                   4687: 
1.12      www      4688: # ----------------------------------------------------------------- Define Role
                   4689: 
                   4690: sub definerole {
                   4691:   if (allowed('mcr','/')) {
                   4692:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4693:     foreach my $role (split(':',$sysrole)) {
                   4694: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4695:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4696:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4697: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4698:                return "refused:s:$crole&$cqual"; 
                   4699:             }
                   4700:         }
1.191     harris41 4701:     }
1.800     albertel 4702:     foreach my $role (split(':',$domrole)) {
                   4703: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4704:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4705:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4706: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4707:                return "refused:d:$crole&$cqual"; 
                   4708:             }
                   4709:         }
1.191     harris41 4710:     }
1.800     albertel 4711:     foreach my $role (split(':',$courole)) {
                   4712: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4713:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4714:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4715: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4716:                return "refused:c:$crole&$cqual"; 
                   4717:             }
                   4718:         }
1.191     harris41 4719:     }
1.620     albertel 4720:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4721:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4722: 	        "rolesdef_$rolename=".
                   4723:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4724:     return reply($command,$env{'user.home'});
1.12      www      4725:   } else {
                   4726:     return 'refused';
                   4727:   }
1.105     harris41 4728: }
                   4729: 
                   4730: # ---------------- Make a metadata query against the network of library servers
                   4731: 
                   4732: sub metadata_query {
1.244     matthew  4733:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4734:     my %rhash;
1.845     albertel 4735:     my %libserv = &all_library();
1.244     matthew  4736:     my @server_list = (defined($server_array) ? @$server_array
                   4737:                                               : keys(%libserv) );
                   4738:     for my $server (@server_list) {
1.118     harris41 4739: 	unless ($custom or $customshow) {
                   4740: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4741: 	    $rhash{$server}=$reply;
                   4742: 	}
                   4743: 	else {
                   4744: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4745: 			     &escape($custom).':'.&escape($customshow),
                   4746: 			     $server);
                   4747: 	    $rhash{$server}=$reply;
                   4748: 	}
1.112     harris41 4749:     }
1.118     harris41 4750:     return \%rhash;
1.240     www      4751: }
                   4752: 
                   4753: # ----------------------------------------- Send log queries and wait for reply
                   4754: 
                   4755: sub log_query {
                   4756:     my ($uname,$udom,$query,%filters)=@_;
                   4757:     my $uhome=&homeserver($uname,$udom);
                   4758:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4759:     my $uhost=&hostname($uhome);
1.800     albertel 4760:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4761:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4762:                        $uhome);
1.479     albertel 4763:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4764:     return get_query_reply($queryid);
                   4765: }
                   4766: 
1.818     raeburn  4767: # -------------------------- Update MySQL table for portfolio file
                   4768: 
                   4769: sub update_portfolio_table {
1.821     raeburn  4770:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4771:     my $homeserver = &homeserver($uname,$udom);
                   4772:     my $queryid=
1.821     raeburn  4773:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4774:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4775:     my $reply = &get_query_reply($queryid);
                   4776:     return $reply;
                   4777: }
                   4778: 
1.899     raeburn  4779: # -------------------------- Update MySQL allusers table
                   4780: 
                   4781: sub update_allusers_table {
                   4782:     my ($uname,$udom,$names) = @_;
                   4783:     my $homeserver = &homeserver($uname,$udom);
                   4784:     my $queryid=
                   4785:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4786:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4787:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4788:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4789:                'generation='.&escape($names->{'generation'}).'%%'.
                   4790:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4791:                'id='.&escape($names->{'id'}),$homeserver);
                   4792:     my $reply = &get_query_reply($queryid);
                   4793:     return $reply;
                   4794: }
                   4795: 
1.508     raeburn  4796: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4797: 
                   4798: sub fetch_enrollment_query {
1.511     raeburn  4799:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4800:     my $homeserver;
1.547     raeburn  4801:     my $maxtries = 1;
1.508     raeburn  4802:     if ($context eq 'automated') {
                   4803:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4804:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4805:     } else {
                   4806:         $homeserver = &homeserver($cnum,$dom);
                   4807:     }
1.838     albertel 4808:     my $host=&hostname($homeserver);
1.506     raeburn  4809:     my $cmd = '';
1.800     albertel 4810:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4811:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4812:     }
                   4813:     $cmd =~ s/%%$//;
                   4814:     $cmd = &escape($cmd);
                   4815:     my $query = 'fetchenrollment';
1.620     albertel 4816:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4817:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4818:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4819:         return 'error: '.$queryid;
                   4820:     }
1.506     raeburn  4821:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4822:     my $tries = 1;
                   4823:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4824:         $reply = &get_query_reply($queryid);
                   4825:         $tries ++;
                   4826:     }
1.526     raeburn  4827:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4828:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4829:     } else {
1.901     albertel 4830:         my @responses = split(/:/,$reply);
1.515     raeburn  4831:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4832:             foreach my $line (@responses) {
                   4833:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4834:                 $$replyref{$key} = $value;
                   4835:             }
                   4836:         } else {
1.506     raeburn  4837:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4838:             foreach my $line (@responses) {
                   4839:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4840:                 $$replyref{$key} = $value;
                   4841:                 if ($value > 0) {
1.800     albertel 4842:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4843:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4844:                         my $destname = $pathname.'/'.$filename;
                   4845:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4846:                         if ($xml_classlist =~ /^error/) {
                   4847:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4848:                         } else {
1.506     raeburn  4849:                             if ( open(FILE,">$destname") ) {
                   4850:                                 print FILE &unescape($xml_classlist);
                   4851:                                 close(FILE);
1.526     raeburn  4852:                             } else {
                   4853:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4854:                             }
                   4855:                         }
                   4856:                     }
                   4857:                 }
                   4858:             }
                   4859:         }
                   4860:         return 'ok';
                   4861:     }
                   4862:     return 'error';
                   4863: }
                   4864: 
1.242     www      4865: sub get_query_reply {
                   4866:     my $queryid=shift;
1.240     www      4867:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4868:     my $reply='';
                   4869:     for (1..100) {
                   4870: 	sleep 2;
                   4871:         if (-e $replyfile.'.end') {
1.448     albertel 4872: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4873: 		$reply = join('',<$fh>);
                   4874: 		close($fh);
1.240     www      4875: 	   } else { return 'error: reply_file_error'; }
1.242     www      4876:            return &unescape($reply);
                   4877: 	}
1.240     www      4878:     }
1.242     www      4879:     return 'timeout:'.$queryid;
1.240     www      4880: }
                   4881: 
                   4882: sub courselog_query {
1.241     www      4883: #
                   4884: # possible filters:
                   4885: # url: url or symb
                   4886: # username
                   4887: # domain
                   4888: # action: view, submit, grade
                   4889: # start: timestamp
                   4890: # end: timestamp
                   4891: #
1.240     www      4892:     my (%filters)=@_;
1.620     albertel 4893:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4894:     if ($filters{'url'}) {
                   4895: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4896:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4897:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4898:     }
1.620     albertel 4899:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4900:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4901:     return &log_query($cname,$cdom,'courselog',%filters);
                   4902: }
                   4903: 
                   4904: sub userlog_query {
1.858     raeburn  4905: #
                   4906: # possible filters:
                   4907: # action: log check role
                   4908: # start: timestamp
                   4909: # end: timestamp
                   4910: #
1.240     www      4911:     my ($uname,$udom,%filters)=@_;
                   4912:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4913: }
                   4914: 
1.506     raeburn  4915: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4916: 
                   4917: sub auto_run {
1.508     raeburn  4918:     my ($cnum,$cdom) = @_;
1.876     raeburn  4919:     my $response = 0;
                   4920:     my $settings;
                   4921:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4922:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4923:         $settings = $domconfig{'autoenroll'};
                   4924:         if ($settings->{'run'} eq '1') {
                   4925:             $response = 1;
                   4926:         }
                   4927:     } else {
1.934     raeburn  4928:         my $homeserver;
                   4929:         if (&is_course($cdom,$cnum)) {
                   4930:             $homeserver = &homeserver($cnum,$cdom);
                   4931:         } else {
                   4932:             $homeserver = &domain($cdom,'primary');
                   4933:         }
                   4934:         if ($homeserver ne 'no_host') {
                   4935:             $response = &reply('autorun:'.$cdom,$homeserver);
                   4936:         }
1.876     raeburn  4937:     }
1.506     raeburn  4938:     return $response;
                   4939: }
1.776     albertel 4940: 
1.506     raeburn  4941: sub auto_get_sections {
1.508     raeburn  4942:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4943:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4944:     my @secs = ();
1.511     raeburn  4945:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4946:     unless ($response eq 'refused') {
1.901     albertel 4947:         @secs = split(/:/,$response);
1.506     raeburn  4948:     }
                   4949:     return @secs;
                   4950: }
1.776     albertel 4951: 
1.506     raeburn  4952: sub auto_new_course {
1.508     raeburn  4953:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4954:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4955:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4956:     return $response;
                   4957: }
1.776     albertel 4958: 
1.506     raeburn  4959: sub auto_validate_courseID {
1.508     raeburn  4960:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4961:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4962:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4963:     return $response;
                   4964: }
1.776     albertel 4965: 
1.506     raeburn  4966: sub auto_create_password {
1.873     raeburn  4967:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4968:     my ($homeserver,$response);
1.506     raeburn  4969:     my $create_passwd = 0;
                   4970:     my $authchk = '';
1.873     raeburn  4971:     if ($udom =~ /^$match_domain$/) {
                   4972:         $homeserver = &domain($udom,'primary');
                   4973:     }
                   4974:     if ($homeserver eq '') {
                   4975:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4976:             $homeserver = &homeserver($cnum,$cdom);
                   4977:         }
                   4978:     }
                   4979:     if ($homeserver eq '') {
                   4980:         $authchk = 'nodomain';
1.506     raeburn  4981:     } else {
1.873     raeburn  4982:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4983:         if ($response eq 'refused') {
                   4984:             $authchk = 'refused';
                   4985:         } else {
1.901     albertel 4986:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4987:         }
1.506     raeburn  4988:     }
                   4989:     return ($authparam,$create_passwd,$authchk);
                   4990: }
                   4991: 
1.706     raeburn  4992: sub auto_photo_permission {
                   4993:     my ($cnum,$cdom,$students) = @_;
                   4994:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4995:     my ($outcome,$perm_reqd,$conditions) = 
                   4996: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4997:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4998: 	return (undef,undef);
                   4999:     }
1.706     raeburn  5000:     return ($outcome,$perm_reqd,$conditions);
                   5001: }
                   5002: 
                   5003: sub auto_checkphotos {
                   5004:     my ($uname,$udom,$pid) = @_;
                   5005:     my $homeserver = &homeserver($uname,$udom);
                   5006:     my ($result,$resulttype);
                   5007:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5008: 				   &escape($uname).':'.&escape($pid),
                   5009: 				   $homeserver));
1.709     albertel 5010:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5011: 	return (undef,undef);
                   5012:     }
1.706     raeburn  5013:     if ($outcome) {
                   5014:         ($result,$resulttype) = split(/:/,$outcome);
                   5015:     } 
                   5016:     return ($result,$resulttype);
                   5017: }
                   5018: 
                   5019: sub auto_photochoice {
                   5020:     my ($cnum,$cdom) = @_;
                   5021:     my $homeserver = &homeserver($cnum,$cdom);
                   5022:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5023: 						       &escape($cdom),
                   5024: 						       $homeserver)));
1.709     albertel 5025:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5026: 	return (undef,undef);
                   5027:     }
1.706     raeburn  5028:     return ($update,$comment);
                   5029: }
                   5030: 
                   5031: sub auto_photoupdate {
                   5032:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5033:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5034:     my $host=&hostname($homeserver);
1.706     raeburn  5035:     my $cmd = '';
                   5036:     my $maxtries = 1;
1.800     albertel 5037:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5038:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5039:     }
                   5040:     $cmd =~ s/%%$//;
                   5041:     $cmd = &escape($cmd);
                   5042:     my $query = 'institutionalphotos';
                   5043:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5044:     unless ($queryid=~/^\Q$host\E\_/) {
                   5045:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5046:         return 'error: '.$queryid;
                   5047:     }
                   5048:     my $reply = &get_query_reply($queryid);
                   5049:     my $tries = 1;
                   5050:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5051:         $reply = &get_query_reply($queryid);
                   5052:         $tries ++;
                   5053:     }
                   5054:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5055:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5056:     } else {
                   5057:         my @responses = split(/:/,$reply);
                   5058:         my $outcome = shift(@responses); 
                   5059:         foreach my $item (@responses) {
                   5060:             my ($key,$value) = split(/=/,$item);
                   5061:             $$photo{$key} = $value;
                   5062:         }
                   5063:         return $outcome;
                   5064:     }
                   5065:     return 'error';
                   5066: }
                   5067: 
1.521     raeburn  5068: sub auto_instcode_format {
1.793     albertel 5069:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5070: 	$cat_order) = @_;
1.521     raeburn  5071:     my $courses = '';
1.772     raeburn  5072:     my @homeservers;
1.521     raeburn  5073:     if ($caller eq 'global') {
1.841     albertel 5074: 	my %servers = &get_servers($codedom,'library');
                   5075: 	foreach my $tryserver (keys(%servers)) {
                   5076: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5077: 		push(@homeservers,$tryserver);
                   5078: 	    }
1.584     raeburn  5079:         }
1.521     raeburn  5080:     } else {
1.772     raeburn  5081:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5082:     }
1.793     albertel 5083:     foreach my $code (keys(%{$instcodes})) {
                   5084:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5085:     }
                   5086:     chop($courses);
1.772     raeburn  5087:     my $ok_response = 0;
                   5088:     my $response;
                   5089:     while (@homeservers > 0 && $ok_response == 0) {
                   5090:         my $server = shift(@homeservers); 
                   5091:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5092:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5093:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5094: 		split(/:/,$response);
1.772     raeburn  5095:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5096:             push(@{$codetitles},&str2array($codetitles_str));
                   5097:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5098:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5099:             $ok_response = 1;
                   5100:         }
                   5101:     }
                   5102:     if ($ok_response) {
1.521     raeburn  5103:         return 'ok';
1.772     raeburn  5104:     } else {
                   5105:         return $response;
1.521     raeburn  5106:     }
                   5107: }
                   5108: 
1.792     raeburn  5109: sub auto_instcode_defaults {
                   5110:     my ($domain,$returnhash,$code_order) = @_;
                   5111:     my @homeservers;
1.841     albertel 5112: 
                   5113:     my %servers = &get_servers($domain,'library');
                   5114:     foreach my $tryserver (keys(%servers)) {
                   5115: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5116: 	    push(@homeservers,$tryserver);
                   5117: 	}
1.792     raeburn  5118:     }
1.841     albertel 5119: 
1.792     raeburn  5120:     my $response;
1.841     albertel 5121:     foreach my $server (@homeservers) {
1.792     raeburn  5122:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5123:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5124: 	
                   5125: 	foreach my $pair (split(/\&/,$response)) {
                   5126: 	    my ($name,$value)=split(/\=/,$pair);
                   5127: 	    if ($name eq 'code_order') {
                   5128: 		@{$code_order} = split(/\&/,&unescape($value));
                   5129: 	    } else {
                   5130: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5131: 	    }
                   5132: 	}
                   5133: 	return 'ok';
1.792     raeburn  5134:     }
1.841     albertel 5135: 
                   5136:     return $response;
1.792     raeburn  5137: } 
                   5138: 
1.777     albertel 5139: sub auto_validate_class_sec {
1.918     raeburn  5140:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5141:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5142:     my $ownerlist;
                   5143:     if (ref($owners) eq 'ARRAY') {
                   5144:         $ownerlist = join(',',@{$owners});
                   5145:     } else {
                   5146:         $ownerlist = $owners;
                   5147:     }
1.773     raeburn  5148:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5149:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5150:     return $response;
                   5151: }
                   5152: 
1.679     raeburn  5153: # ------------------------------------------------------- Course Group routines
                   5154: 
                   5155: sub get_coursegroups {
1.809     raeburn  5156:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5157:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5158: }
                   5159: 
1.679     raeburn  5160: sub modify_coursegroup {
                   5161:     my ($cdom,$cnum,$groupsettings) = @_;
                   5162:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5163: }
                   5164: 
1.809     raeburn  5165: sub toggle_coursegroup_status {
                   5166:     my ($cdom,$cnum,$group,$action) = @_;
                   5167:     my ($from_namespace,$to_namespace);
                   5168:     if ($action eq 'delete') {
                   5169:         $from_namespace = 'coursegroups';
                   5170:         $to_namespace = 'deleted_groups';
                   5171:     } else {
                   5172:         $from_namespace = 'deleted_groups';
                   5173:         $to_namespace = 'coursegroups';
                   5174:     }
                   5175:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5176:     if (my $tmp = &error(%curr_group)) {
                   5177:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5178:         return ('read error',$tmp);
                   5179:     } else {
                   5180:         my %savedsettings = %curr_group; 
1.809     raeburn  5181:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5182:         my $deloutcome;
                   5183:         if ($result eq 'ok') {
1.809     raeburn  5184:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5185:         } else {
                   5186:             return ('write error',$result);
                   5187:         }
                   5188:         if ($deloutcome eq 'ok') {
                   5189:             return 'ok';
                   5190:         } else {
                   5191:             return ('delete error',$deloutcome);
                   5192:         }
                   5193:     }
                   5194: }
                   5195: 
1.679     raeburn  5196: sub modify_group_roles {
                   5197:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5198:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5199:     my $role = 'gr/'.&escape($userprivs);
                   5200:     my ($uname,$udom) = split(/:/,$user);
                   5201:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5202:     if ($result eq 'ok') {
                   5203:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5204:     }
1.679     raeburn  5205:     return $result;
                   5206: }
                   5207: 
                   5208: sub modify_coursegroup_membership {
                   5209:     my ($cdom,$cnum,$membership) = @_;
                   5210:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5211:     return $result;
                   5212: }
                   5213: 
1.682     raeburn  5214: sub get_active_groups {
                   5215:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5216:     my $now = time;
                   5217:     my %groups = ();
                   5218:     foreach my $key (keys(%env)) {
1.811     albertel 5219:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5220:             my ($start,$end) = split(/\./,$env{$key});
                   5221:             if (($end!=0) && ($end<$now)) { next; }
                   5222:             if (($start!=0) && ($start>$now)) { next; }
                   5223:             if ($1 eq $cdom && $2 eq $cnum) {
                   5224:                 $groups{$3} = $env{$key} ;
                   5225:             }
                   5226:         }
                   5227:     }
                   5228:     return %groups;
                   5229: }
                   5230: 
1.683     raeburn  5231: sub get_group_membership {
                   5232:     my ($cdom,$cnum,$group) = @_;
                   5233:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5234: }
                   5235: 
                   5236: sub get_users_groups {
                   5237:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5238:     my @usersgroups;
1.683     raeburn  5239:     my $cachetime=1800;
                   5240: 
                   5241:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5242:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5243:     if (defined($cached)) {
1.734     albertel 5244:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5245:     } else {  
                   5246:         $grouplist = '';
1.816     raeburn  5247:         my $courseurl = &courseid_to_courseurl($courseid);
                   5248:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5249:         my $access_end = $env{'course.'.$courseid.
                   5250:                               '.default_enrollment_end_date'};
                   5251:         my $now = time;
                   5252:         foreach my $key (keys(%roleshash)) {
                   5253:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5254:                 my $group = $1;
                   5255:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5256:                     my $start = $2;
                   5257:                     my $end = $1;
                   5258:                     if ($start == -1) { next; } # deleted from group
                   5259:                     if (($start!=0) && ($start>$now)) { next; }
                   5260:                     if (($end!=0) && ($end<$now)) {
                   5261:                         if ($access_end && $access_end < $now) {
                   5262:                             if ($access_end - $end < 86400) {
                   5263:                                 push(@usersgroups,$group);
1.733     raeburn  5264:                             }
                   5265:                         }
1.817     raeburn  5266:                         next;
1.733     raeburn  5267:                     }
1.817     raeburn  5268:                     push(@usersgroups,$group);
1.683     raeburn  5269:                 }
                   5270:             }
                   5271:         }
1.817     raeburn  5272:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5273:         $grouplist = join(':',@usersgroups);
                   5274:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5275:     }
1.733     raeburn  5276:     return @usersgroups;
1.683     raeburn  5277: }
                   5278: 
                   5279: sub devalidate_getgroups_cache {
                   5280:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5281:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5282: 
1.683     raeburn  5283:     my $hashid="$udom:$uname:$courseid";
                   5284:     &devalidate_cache_new('getgroups',$hashid);
                   5285: }
                   5286: 
1.12      www      5287: # ------------------------------------------------------------------ Plain Text
                   5288: 
                   5289: sub plaintext {
1.742     raeburn  5290:     my ($short,$type,$cid) = @_;
1.758     albertel 5291:     if ($short =~ /^cr/) {
                   5292: 	return (split('/',$short))[-1];
                   5293:     }
1.742     raeburn  5294:     if (!defined($cid)) {
                   5295:         $cid = $env{'request.course.id'};
                   5296:     }
                   5297:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5298:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5299:                                           '.plaintext'});
                   5300:     }
                   5301:     my %rolenames = (
                   5302:                       Course => 'std',
                   5303:                       Group => 'alt1',
                   5304:                     );
                   5305:     if (defined($type) && 
                   5306:          defined($rolenames{$type}) && 
                   5307:          defined($prp{$short}{$rolenames{$type}})) {
                   5308:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5309:     } else {
                   5310:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5311:     }
1.12      www      5312: }
                   5313: 
                   5314: # ----------------------------------------------------------------- Assign Role
                   5315: 
                   5316: sub assignrole {
1.947   ! raeburn  5317:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
1.21      www      5318:     my $mrole;
                   5319:     if ($role =~ /^cr\//) {
1.393     www      5320:         my $cwosec=$url;
1.811     albertel 5321:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5322: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5323:            &logthis('Refused custom assignrole: '.
                   5324:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5325: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5326:            return 'refused'; 
                   5327:         }
1.21      www      5328:         $mrole='cr';
1.678     raeburn  5329:     } elsif ($role =~ /^gr\//) {
                   5330:         my $cwogrp=$url;
1.811     albertel 5331:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5332:         unless (&allowed('mdg',$cwogrp)) {
                   5333:             &logthis('Refused group assignrole: '.
                   5334:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5335:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5336:             return 'refused';
                   5337:         }
                   5338:         $mrole='gr';
1.21      www      5339:     } else {
1.82      www      5340:         my $cwosec=$url;
1.811     albertel 5341:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5342:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5343:             my $refused;
                   5344:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5345:                 if (!(&allowed('c'.$role,$url))) {
                   5346:                     $refused = 1;
                   5347:                 }
                   5348:             } else {
                   5349:                 $refused = 1;
                   5350:             }
1.947   ! raeburn  5351:             if ($refused) {
        !          5352:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
        !          5353:                     $refused = '';
        !          5354:                 } else {
        !          5355:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
        !          5356:                              ' '.$role.' '.$end.' '.$start.' by '.
        !          5357: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
        !          5358:                     return 'refused';
        !          5359:                 }
1.932     raeburn  5360:             }
1.104     www      5361:         }
1.21      www      5362:         $mrole=$role;
                   5363:     }
1.620     albertel 5364:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5365:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5366:     if ($end) { $command.='_'.$end; }
1.21      www      5367:     if ($start) {
                   5368: 	if ($end) { 
1.81      www      5369:            $command.='_'.$start; 
1.21      www      5370:         } else {
1.81      www      5371:            $command.='_0_'.$start;
1.21      www      5372:         }
                   5373:     }
1.739     raeburn  5374:     my $origstart = $start;
                   5375:     my $origend = $end;
1.357     www      5376: # actually delete
                   5377:     if ($deleteflag) {
1.373     www      5378: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5379: # modify command to delete the role
1.620     albertel 5380:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5381:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5382: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5383: # set start and finish to negative values for userrolelog
                   5384:            $start=-1;
                   5385:            $end=-1;
                   5386:         }
                   5387:     }
                   5388: # send command
1.349     www      5389:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5390: # log new user role if status is ok
1.349     www      5391:     if ($answer eq 'ok') {
1.663     raeburn  5392: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5393: # for course roles, perform group memberships changes triggered by role change.
                   5394:         unless ($role =~ /^gr/) {
                   5395:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5396:                                              $origstart);
                   5397:         }
1.349     www      5398:     }
                   5399:     return $answer;
1.169     harris41 5400: }
                   5401: 
                   5402: # -------------------------------------------------- Modify user authentication
1.197     www      5403: # Overrides without validation
                   5404: 
1.169     harris41 5405: sub modifyuserauth {
                   5406:     my ($udom,$uname,$umode,$upass)=@_;
                   5407:     my $uhome=&homeserver($uname,$udom);
1.197     www      5408:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5409:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5410:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5411:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5412:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5413: 		     &escape($upass),$uhome);
1.620     albertel 5414:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5415:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5416:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5417:     &log($udom,,$uname,$uhome,
1.620     albertel 5418:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5419:                                      $env{'user.name'}.', '.$umode.
1.197     www      5420:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5421:     unless ($reply eq 'ok') {
1.197     www      5422:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5423: 	return 'error: '.$reply;
                   5424:     }   
1.170     harris41 5425:     return 'ok';
1.80      www      5426: }
                   5427: 
1.81      www      5428: # --------------------------------------------------------------- Modify a user
1.80      www      5429: 
1.81      www      5430: sub modifyuser {
1.206     matthew  5431:     my ($udom,    $uname, $uid,
                   5432:         $umode,   $upass, $first,
                   5433:         $middle,  $last,  $gene,
1.387     www      5434:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5435:     $udom= &LONCAPA::clean_domain($udom);
                   5436:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5437:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5438:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5439: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5440:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5441:                                      ' desiredhome not specified'). 
1.620     albertel 5442:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5443:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5444:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5445: # ----------------------------------------------------------------- Create User
1.406     albertel 5446:     if (($uhome eq 'no_host') && 
                   5447: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5448:         my $unhome='';
1.844     albertel 5449:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5450:             $unhome = $desiredhome;
1.620     albertel 5451: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5452: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5453:         } else { # load balancing routine for determining $unhome
1.81      www      5454:             my $loadm=10000000;
1.841     albertel 5455: 	    my %servers = &get_servers($udom,'library');
                   5456: 	    foreach my $tryserver (keys(%servers)) {
                   5457: 		my $answer=reply('load',$tryserver);
                   5458: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5459: 		    $loadm=$answer;
                   5460: 		    $unhome=$tryserver;
                   5461: 		}
1.80      www      5462: 	    }
                   5463:         }
                   5464:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5465: 	    return 'error: unable to find a home server for '.$uname.
                   5466:                    ' in domain '.$udom;
1.80      www      5467:         }
                   5468:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5469:                          &escape($upass),$unhome);
                   5470: 	unless ($reply eq 'ok') {
                   5471:             return 'error: '.$reply;
                   5472:         }   
1.230     stredwic 5473:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5474:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5475: 	    return 'error: unable verify users home machine.';
1.80      www      5476:         }
1.209     matthew  5477:     }   # End of creation of new user
1.80      www      5478: # ---------------------------------------------------------------------- Add ID
                   5479:     if ($uid) {
                   5480:        $uid=~tr/A-Z/a-z/;
                   5481:        my %uidhash=&idrget($udom,$uname);
1.196     www      5482:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5483:          && (!$forceid)) {
1.80      www      5484: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5485: 	      return 'error: user id "'.$uid.'" does not match '.
                   5486:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5487:           }
                   5488:        } else {
                   5489: 	  &idput($udom,($uname => $uid));
                   5490:        }
                   5491:     }
                   5492: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5493:     my @tmp=&get('environment',
1.899     raeburn  5494: 		   ['firstname','middlename','lastname','generation','id',
                   5495:                     'permanentemail'],
1.134     albertel 5496: 		   $udom,$uname);
1.313     matthew  5497:     my %names;
                   5498:     if ($tmp[0] =~ m/^error:.*/) { 
                   5499:         %names=(); 
                   5500:     } else {
                   5501:         %names = @tmp;
                   5502:     }
1.388     www      5503: #
                   5504: # Make sure to not trash student environment if instructor does not bother
                   5505: # to supply name and email information
                   5506: #
                   5507:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5508:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5509:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5510:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5511:     if ($email) {
                   5512:        $email=~s/[^\w\@\.\-\,]//gs;
                   5513:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5514: 			   $names{'critnotification'} = $email;
                   5515: 			   $names{'permanentemail'} = $email; }
                   5516:     }
1.899     raeburn  5517:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5518:     my $reply = &put('environment', \%names, $udom,$uname);
                   5519:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5520:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5521:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5522:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5523:              $umode.', '.$first.', '.$middle.', '.
                   5524: 	     $last.', '.$gene.' by '.
1.620     albertel 5525:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5526:     return 'ok';
1.80      www      5527: }
                   5528: 
1.81      www      5529: # -------------------------------------------------------------- Modify student
1.80      www      5530: 
1.81      www      5531: sub modifystudent {
                   5532:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5533:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5534:     if (!$cid) {
1.620     albertel 5535: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5536: 	    return 'not_in_class';
                   5537: 	}
1.80      www      5538:     }
                   5539: # --------------------------------------------------------------- Make the user
1.81      www      5540:     my $reply=&modifyuser
1.209     matthew  5541: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5542:          $desiredhome,$email);
1.80      www      5543:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5544:     # This will cause &modify_student_enrollment to get the uid from the
                   5545:     # students environment
                   5546:     $uid = undef if (!$forceid);
1.455     albertel 5547:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5548: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5549:     return $reply;
                   5550: }
                   5551: 
                   5552: sub modify_student_enrollment {
1.947   ! raeburn  5553:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
1.455     albertel 5554:     my ($cdom,$cnum,$chome);
                   5555:     if (!$cid) {
1.620     albertel 5556: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5557: 	    return 'not_in_class';
                   5558: 	}
1.620     albertel 5559: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5560: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5561:     } else {
                   5562: 	($cdom,$cnum)=split(/_/,$cid);
                   5563:     }
1.620     albertel 5564:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5565:     if (!$chome) {
1.457     raeburn  5566: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5567:     }
1.455     albertel 5568:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5569:     # Make sure the user exists
1.81      www      5570:     my $uhome=&homeserver($uname,$udom);
                   5571:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5572: 	return 'error: no such user';
                   5573:     }
1.297     matthew  5574:     # Get student data if we were not given enough information
                   5575:     if (!defined($first)  || $first  eq '' || 
                   5576:         !defined($last)   || $last   eq '' || 
                   5577:         !defined($uid)    || $uid    eq '' || 
                   5578:         !defined($middle) || $middle eq '' || 
                   5579:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5580:         # They did not supply us with enough data to enroll the student, so
                   5581:         # we need to pick up more information.
1.297     matthew  5582:         my %tmp = &get('environment',
1.294     matthew  5583:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5584:                        ,$udom,$uname);
                   5585: 
1.800     albertel 5586:         #foreach my $key (keys(%tmp)) {
                   5587:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5588:         #}
1.294     matthew  5589:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5590:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5591:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5592:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5593:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5594:     }
1.556     albertel 5595:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5596:     my $reply=cput('classlist',
                   5597: 		   {"$uname:$udom" => 
1.515     raeburn  5598: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5599: 		   $cdom,$cnum);
1.81      www      5600:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5601: 	return 'error: '.$reply;
1.652     albertel 5602:     } else {
                   5603: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5604:     }
1.297     matthew  5605:     # Add student role to user
1.83      www      5606:     my $uurl='/'.$cid;
1.81      www      5607:     $uurl=~s/\_/\//g;
                   5608:     if ($usec) {
                   5609: 	$uurl.='/'.$usec;
                   5610:     }
1.947   ! raeburn  5611:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
1.21      www      5612: }
                   5613: 
1.556     albertel 5614: sub format_name {
                   5615:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5616:     my $name;
                   5617:     if ($first ne 'lastname') {
                   5618: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5619:     } else {
                   5620: 	if ($lastname=~/\S/) {
                   5621: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5622: 	    $name=~s/\s+,/,/;
                   5623: 	} else {
                   5624: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5625: 	}
                   5626:     }
                   5627:     $name=~s/^\s+//;
                   5628:     $name=~s/\s+$//;
                   5629:     $name=~s/\s+/ /g;
                   5630:     return $name;
                   5631: }
                   5632: 
1.84      www      5633: # ------------------------------------------------- Write to course preferences
                   5634: 
                   5635: sub writecoursepref {
                   5636:     my ($courseid,%prefs)=@_;
                   5637:     $courseid=~s/^\///;
                   5638:     $courseid=~s/\_/\//g;
                   5639:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5640:     my $chome=homeserver($cnum,$cdomain);
                   5641:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5642: 	return 'error: no such course';
                   5643:     }
                   5644:     my $cstring='';
1.800     albertel 5645:     foreach my $pref (keys(%prefs)) {
                   5646: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5647:     }
1.84      www      5648:     $cstring=~s/\&$//;
                   5649:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5650: }
                   5651: 
                   5652: # ---------------------------------------------------------- Make/modify course
                   5653: 
                   5654: sub createcourse {
1.741     raeburn  5655:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5656:         $course_owner,$crstype)=@_;
1.84      www      5657:     $url=&declutter($url);
                   5658:     my $cid='';
1.264     matthew  5659:     unless (&allowed('ccc',$udom)) {
1.84      www      5660:         return 'refused';
                   5661:     }
                   5662: # ------------------------------------------------------------------- Create ID
1.674     www      5663:    my $uname=int(1+rand(9)).
                   5664:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5665:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5666:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5667: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5668:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5669:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5670:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5671:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5672:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5673:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5674:            return 'error: unable to generate unique course-ID';
                   5675:        } 
                   5676:    }
1.264     matthew  5677: # ------------------------------------------------ Check supplied server name
1.620     albertel 5678:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5679:     if (! &is_library($course_server)) {
1.264     matthew  5680:         return 'error:bad server name '.$course_server;
                   5681:     }
1.84      www      5682: # ------------------------------------------------------------- Make the course
                   5683:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5684:                       $course_server);
1.84      www      5685:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5686:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5687:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5688: 	return 'error: no such course';
                   5689:     }
1.271     www      5690: # ----------------------------------------------------------------- Course made
1.516     raeburn  5691: # log existence
1.918     raeburn  5692:     my $newcourse = {
                   5693:                     $udom.'_'.$uname => {
1.921     raeburn  5694:                                      description => $description,
                   5695:                                      inst_code   => $inst_code,
                   5696:                                      owner       => $course_owner,
                   5697:                                      type        => $crstype,
1.918     raeburn  5698:                                                 },
                   5699:                     };
1.921     raeburn  5700:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5701: # set toplevel url
1.271     www      5702:     my $topurl=$url;
                   5703:     unless ($nonstandard) {
                   5704: # ------------------------------------------ For standard courses, make top url
                   5705:         my $mapurl=&clutter($url);
1.278     www      5706:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5707:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5708: <map>
                   5709: <resource id="1" type="start"></resource>
                   5710: <resource id="2" src="$mapurl"></resource>
                   5711: <resource id="3" type="finish"></resource>
                   5712: <link index="1" from="1" to="2"></link>
                   5713: <link index="2" from="2" to="3"></link>
                   5714: </map>
                   5715: ENDINITMAP
                   5716:         $topurl=&declutter(
1.638     albertel 5717:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5718:                           );
                   5719:     }
                   5720: # ----------------------------------------------------------- Write preferences
1.84      www      5721:     &writecoursepref($udom.'_'.$uname,
                   5722:                      ('description' => $description,
1.271     www      5723:                       'url'         => $topurl));
1.84      www      5724:     return '/'.$udom.'/'.$uname;
                   5725: }
                   5726: 
1.813     albertel 5727: sub is_course {
                   5728:     my ($cdom,$cnum) = @_;
                   5729:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5730: 				undef,'.');
1.813     albertel 5731:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5732:         return 1;
                   5733:     }
                   5734:     return 0;
                   5735: }
                   5736: 
1.21      www      5737: # ---------------------------------------------------------- Assign Custom Role
                   5738: 
                   5739: sub assigncustomrole {
1.357     www      5740:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5741:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5742:                        $end,$start,$deleteflag);
1.21      www      5743: }
                   5744: 
                   5745: # ----------------------------------------------------------------- Revoke Role
                   5746: 
                   5747: sub revokerole {
1.357     www      5748:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5749:     my $now=time;
1.357     www      5750:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5751: }
                   5752: 
                   5753: # ---------------------------------------------------------- Revoke Custom Role
                   5754: 
                   5755: sub revokecustomrole {
1.357     www      5756:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5757:     my $now=time;
1.357     www      5758:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5759:            $deleteflag);
1.17      www      5760: }
                   5761: 
1.533     banghart 5762: # ------------------------------------------------------------ Disk usage
1.535     albertel 5763: sub diskusage {
1.533     banghart 5764:     my ($udom,$uname,$directoryRoot)=@_;
                   5765:     $directoryRoot =~ s/\/$//;
1.535     albertel 5766:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5767:     return $listing;
1.512     banghart 5768: }
                   5769: 
1.566     banghart 5770: sub is_locked {
                   5771:     my ($file_name, $domain, $user) = @_;
                   5772:     my @check;
                   5773:     my $is_locked;
                   5774:     push @check, $file_name;
1.613     albertel 5775:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5776: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5777:     my ($tmp)=keys(%locked);
                   5778:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5779:     
1.566     banghart 5780:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5781:         $is_locked = 'false';
                   5782:         foreach my $entry (@{$locked{$file_name}}) {
                   5783:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5784:                $is_locked = 'true';
                   5785:                last;
1.745     raeburn  5786:            }
                   5787:        }
1.566     banghart 5788:     } else {
                   5789:         $is_locked = 'false';
                   5790:     }
                   5791: }
                   5792: 
1.759     albertel 5793: sub declutter_portfile {
                   5794:     my ($file) = @_;
1.833     albertel 5795:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5796:     return $file;
                   5797: }
                   5798: 
1.559     banghart 5799: # ------------------------------------------------------------- Mark as Read Only
                   5800: 
                   5801: sub mark_as_readonly {
                   5802:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5803:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5804:     my ($tmp)=keys(%current_permissions);
                   5805:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5806:     foreach my $file (@{$files}) {
1.759     albertel 5807: 	$file = &declutter_portfile($file);
1.561     banghart 5808:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5809:     }
1.613     albertel 5810:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5811:     return;
                   5812: }
                   5813: 
1.572     banghart 5814: # ------------------------------------------------------------Save Selected Files
                   5815: 
                   5816: sub save_selected_files {
                   5817:     my ($user, $path, @files) = @_;
                   5818:     my $filename = $user."savedfiles";
1.573     banghart 5819:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5820:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5821:     foreach my $file (@files) {
1.620     albertel 5822:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5823:     }
                   5824:     foreach my $file (@other_files) {
1.574     banghart 5825:         print (OUT $file."\n");
1.572     banghart 5826:     }
1.574     banghart 5827:     close (OUT);
1.572     banghart 5828:     return 'ok';
                   5829: }
                   5830: 
1.574     banghart 5831: sub clear_selected_files {
                   5832:     my ($user) = @_;
                   5833:     my $filename = $user."savedfiles";
                   5834:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5835:     print (OUT undef);
                   5836:     close (OUT);
                   5837:     return ("ok");    
                   5838: }
                   5839: 
1.572     banghart 5840: sub files_in_path {
                   5841:     my ($user, $path) = @_;
                   5842:     my $filename = $user."savedfiles";
                   5843:     my %return_files;
1.574     banghart 5844:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5845:     while (my $line_in = <IN>) {
1.574     banghart 5846:         chomp ($line_in);
                   5847:         my @paths_and_file = split (m!/!, $line_in);
                   5848:         my $file_part = pop (@paths_and_file);
                   5849:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5850:         $path_part.='/';
                   5851:         my $path_and_file = $path_part.$file_part;
                   5852:         if ($path_part eq $path) {
                   5853:             $return_files{$file_part}= 'selected';
                   5854:         }
                   5855:     }
1.574     banghart 5856:     close (IN);
                   5857:     return (\%return_files);
1.572     banghart 5858: }
                   5859: 
                   5860: # called in portfolio select mode, to show files selected NOT in current directory
                   5861: sub files_not_in_path {
                   5862:     my ($user, $path) = @_;
                   5863:     my $filename = $user."savedfiles";
                   5864:     my @return_files;
                   5865:     my $path_part;
1.800     albertel 5866:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5867:     while (my $line = <IN>) {
1.572     banghart 5868:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5869:         my @paths_and_file = split(m|/|, $line);
                   5870:         my $file_part = pop(@paths_and_file);
                   5871:         chomp($file_part);
                   5872:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5873:         $path_part .= '/';
                   5874:         my $path_and_file = $path_part.$file_part;
                   5875:         if ($path_part ne $path) {
1.800     albertel 5876:             push(@return_files, ($path_and_file));
1.572     banghart 5877:         }
                   5878:     }
1.800     albertel 5879:     close(OUT);
1.574     banghart 5880:     return (@return_files);
1.572     banghart 5881: }
                   5882: 
1.745     raeburn  5883: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5884: 
1.745     raeburn  5885: sub get_portfile_permissions {
                   5886:     my ($domain,$user) = @_;
1.613     albertel 5887:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5888:     my ($tmp)=keys(%current_permissions);
                   5889:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5890:     return \%current_permissions;
                   5891: }
                   5892: 
                   5893: #---------------------------------------------Get portfolio file access controls
                   5894: 
1.749     raeburn  5895: sub get_access_controls {
1.745     raeburn  5896:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5897:     my %access;
                   5898:     my $real_file = $file;
                   5899:     $file =~ s/\.meta$//;
1.745     raeburn  5900:     if (defined($file)) {
1.749     raeburn  5901:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5902:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5903:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5904:             }
                   5905:         }
1.745     raeburn  5906:     } else {
1.749     raeburn  5907:         foreach my $key (keys(%{$current_permissions})) {
                   5908:             if ($key =~ /\0accesscontrol$/) {
                   5909:                 if (defined($group)) {
                   5910:                     if ($key !~ m-^\Q$group\E/-) {
                   5911:                         next;
                   5912:                     }
                   5913:                 }
                   5914:                 my ($fullpath) = split(/\0/,$key);
                   5915:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5916:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5917:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5918:                     }
                   5919:                 }
                   5920:             }
                   5921:         }
                   5922:     }
                   5923:     return %access;
                   5924: }
                   5925: 
                   5926: sub modify_access_controls {
                   5927:     my ($file_name,$changes,$domain,$user)=@_;
                   5928:     my ($outcome,$deloutcome);
                   5929:     my %store_permissions;
                   5930:     my %new_values;
                   5931:     my %new_control;
                   5932:     my %translation;
                   5933:     my @deletions = ();
                   5934:     my $now = time;
                   5935:     if (exists($$changes{'activate'})) {
                   5936:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5937:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5938:             my $numnew = scalar(@newitems);
                   5939:             for (my $i=0; $i<$numnew; $i++) {
                   5940:                 my $newkey = $newitems[$i];
                   5941:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5942:                 if ($newkey =~ /^\d+:/) { 
                   5943:                     $newkey =~ s/^(\d+)/$newid/;
                   5944:                     $translation{$1} = $newid;
                   5945:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5946:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5947:                     $translation{$1} = $newid;
                   5948:                 }
1.749     raeburn  5949:                 $new_values{$file_name."\0".$newkey} = 
                   5950:                                           $$changes{'activate'}{$newitems[$i]};
                   5951:                 $new_control{$newkey} = $now;
                   5952:             }
                   5953:         }
                   5954:     }
                   5955:     my %todelete;
                   5956:     my %changed_items;
                   5957:     foreach my $action ('delete','update') {
                   5958:         if (exists($$changes{$action})) {
                   5959:             if (ref($$changes{$action}) eq 'HASH') {
                   5960:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5961:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5962:                     if ($action eq 'delete') { 
                   5963:                         $todelete{$itemnum} = 1;
                   5964:                     } else {
                   5965:                         $changed_items{$itemnum} = $key;
                   5966:                     }
                   5967:                 }
1.745     raeburn  5968:             }
                   5969:         }
1.749     raeburn  5970:     }
                   5971:     # get lock on access controls for file.
                   5972:     my $lockhash = {
                   5973:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5974:                                                        ':'.$env{'user.domain'},
                   5975:                    }; 
                   5976:     my $tries = 0;
                   5977:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5978:    
                   5979:     while (($gotlock ne 'ok') && $tries <3) {
                   5980:         $tries ++;
                   5981:         sleep 1;
                   5982:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5983:     }
                   5984:     if ($gotlock eq 'ok') {
                   5985:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5986:         my ($tmp)=keys(%curr_permissions);
                   5987:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5988:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5989:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5990:             if (ref($curr_controls) eq 'HASH') {
                   5991:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5992:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5993:                     if (defined($todelete{$itemnum})) {
                   5994:                         push(@deletions,$file_name."\0".$control_item);
                   5995:                     } else {
                   5996:                         if (defined($changed_items{$itemnum})) {
                   5997:                             $new_control{$changed_items{$itemnum}} = $now;
                   5998:                             push(@deletions,$file_name."\0".$control_item);
                   5999:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6000:                         } else {
                   6001:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6002:                         }
                   6003:                     }
1.745     raeburn  6004:                 }
                   6005:             }
                   6006:         }
1.749     raeburn  6007:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6008:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6009:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6010:         #  remove lock
                   6011:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6012:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6013:         my ($file,$group);
                   6014:         if (&is_course($domain,$user)) {
                   6015:             ($group,$file) = split(/\//,$file_name,2);
                   6016:         } else {
                   6017:             $file = $file_name;
                   6018:         }
                   6019:         my $sqlresult =
                   6020:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6021:                                     $group);
1.749     raeburn  6022:     } else {
                   6023:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6024:     }
1.749     raeburn  6025:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6026: }
                   6027: 
1.827     raeburn  6028: sub make_public_indefinitely {
                   6029:     my ($requrl) = @_;
                   6030:     my $now = time;
                   6031:     my $action = 'activate';
                   6032:     my $aclnum = 0;
                   6033:     if (&is_portfolio_url($requrl)) {
                   6034:         my (undef,$udom,$unum,$file_name,$group) =
                   6035:             &parse_portfolio_url($requrl);
                   6036:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6037:         my %access_controls = &get_access_controls($current_perms,
                   6038:                                                    $group,$file_name);
                   6039:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6040:             my ($num,$scope,$end,$start) = 
                   6041:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6042:             if ($scope eq 'public') {
                   6043:                 if ($start <= $now && $end == 0) {
                   6044:                     $action = 'none';
                   6045:                 } else {
                   6046:                     $action = 'update';
                   6047:                     $aclnum = $num;
                   6048:                 }
                   6049:                 last;
                   6050:             }
                   6051:         }
                   6052:         if ($action eq 'none') {
                   6053:              return 'ok';
                   6054:         } else {
                   6055:             my %changes;
                   6056:             my $newend = 0;
                   6057:             my $newstart = $now;
                   6058:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6059:             $changes{$action}{$newkey} = {
                   6060:                 type => 'public',
                   6061:                 time => {
                   6062:                     start => $newstart,
                   6063:                     end   => $newend,
                   6064:                 },
                   6065:             };
                   6066:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6067:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6068:             return $outcome;
                   6069:         }
                   6070:     } else {
                   6071:         return 'invalid';
                   6072:     }
                   6073: }
                   6074: 
1.745     raeburn  6075: #------------------------------------------------------Get Marked as Read Only
                   6076: 
                   6077: sub get_marked_as_readonly {
                   6078:     my ($domain,$user,$what,$group) = @_;
                   6079:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6080:     my @readonly_files;
1.629     banghart 6081:     my $cmp1=$what;
                   6082:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6083:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6084:         if (defined($group)) {
                   6085:             if ($file_name !~ m-^\Q$group\E/-) {
                   6086:                 next;
                   6087:             }
                   6088:         }
1.561     banghart 6089:         if (ref($value) eq "ARRAY"){
                   6090:             foreach my $stored_what (@{$value}) {
1.629     banghart 6091:                 my $cmp2=$stored_what;
1.759     albertel 6092:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6093:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6094:                 }
1.629     banghart 6095:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6096:                     push(@readonly_files, $file_name);
1.745     raeburn  6097:                     last;
1.563     banghart 6098:                 } elsif (!defined($what)) {
                   6099:                     push(@readonly_files, $file_name);
1.745     raeburn  6100:                     last;
1.561     banghart 6101:                 }
                   6102:             }
1.745     raeburn  6103:         }
1.561     banghart 6104:     }
                   6105:     return @readonly_files;
                   6106: }
1.577     banghart 6107: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6108: 
1.577     banghart 6109: sub get_marked_as_readonly_hash {
1.745     raeburn  6110:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6111:     my %readonly_files;
1.745     raeburn  6112:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6113:         if (defined($group)) {
                   6114:             if ($file_name !~ m-^\Q$group\E/-) {
                   6115:                 next;
                   6116:             }
                   6117:         }
1.577     banghart 6118:         if (ref($value) eq "ARRAY"){
                   6119:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6120:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6121:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6122:                         if ($lock_descriptor eq 'graded') {
                   6123:                             $readonly_files{$file_name} = 'graded';
                   6124:                         } elsif ($lock_descriptor eq 'handback') {
                   6125:                             $readonly_files{$file_name} = 'handback';
                   6126:                         } else {
                   6127:                             if (!exists($readonly_files{$file_name})) {
                   6128:                                 $readonly_files{$file_name} = 'locked';
                   6129:                             }
                   6130:                         }
1.745     raeburn  6131:                     }
1.750     banghart 6132:                 } 
1.577     banghart 6133:             }
                   6134:         } 
                   6135:     }
                   6136:     return %readonly_files;
                   6137: }
1.559     banghart 6138: # ------------------------------------------------------------ Unmark as Read Only
                   6139: 
                   6140: sub unmark_as_readonly {
1.629     banghart 6141:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6142:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6143:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6144:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6145:     my $symb_crs = $what;
                   6146:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6147:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6148:     my ($tmp)=keys(%current_permissions);
                   6149:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6150:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6151:     foreach my $file (@readonly_files) {
1.759     albertel 6152: 	my $clean_file = &declutter_portfile($file);
                   6153: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6154: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6155:         my @new_locks;
                   6156:         my @del_keys;
                   6157:         if (ref($current_locks) eq "ARRAY"){
                   6158:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6159:                 my $compare=$locker;
1.749     raeburn  6160:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6161:                     $compare=join('',@{$locker});
1.746     raeburn  6162:                     if ($compare ne $symb_crs) {
                   6163:                         push(@new_locks, $locker);
                   6164:                     }
1.563     banghart 6165:                 }
                   6166:             }
1.650     albertel 6167:             if (scalar(@new_locks) > 0) {
1.563     banghart 6168:                 $current_permissions{$file} = \@new_locks;
                   6169:             } else {
                   6170:                 push(@del_keys, $file);
1.613     albertel 6171:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6172:                 delete($current_permissions{$file});
1.563     banghart 6173:             }
                   6174:         }
1.561     banghart 6175:     }
1.613     albertel 6176:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6177:     return;
                   6178: }
1.512     banghart 6179: 
1.17      www      6180: # ------------------------------------------------------------ Directory lister
                   6181: 
                   6182: sub dirlist {
1.253     stredwic 6183:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   6184: 
1.18      www      6185:     $uri=~s/^\///;
                   6186:     $uri=~s/\/$//;
1.253     stredwic 6187:     my ($udom, $uname);
                   6188:     (undef,$udom,$uname)=split(/\//,$uri);
                   6189:     if(defined($userdomain)) {
                   6190:         $udom = $userdomain;
                   6191:     }
                   6192:     if(defined($username)) {
                   6193:         $uname = $username;
                   6194:     }
                   6195: 
                   6196:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6197:     if(defined($alternateDirectoryRoot)) {
                   6198:         $dirRoot = $alternateDirectoryRoot;
                   6199:         $dirRoot =~ s/\/$//;
1.751     banghart 6200:     }
1.253     stredwic 6201: 
                   6202:     if($udom) {
                   6203:         if($uname) {
1.800     albertel 6204:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6205: 				 &homeserver($uname,$udom));
1.605     matthew  6206:             my @listing_results;
                   6207:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6208:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6209: 				  &homeserver($uname,$udom));
1.605     matthew  6210:                 @listing_results = split(/:/,$listing);
                   6211:             } else {
                   6212:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6213:             }
                   6214:             return @listing_results;
1.253     stredwic 6215:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6216:             my %allusers;
1.841     albertel 6217: 	    my %servers = &get_servers($udom,'library');
                   6218: 	    foreach my $tryserver (keys(%servers)) {
                   6219: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6220: 				     $udom, $tryserver);
                   6221: 		my @listing_results;
                   6222: 		if ($listing eq 'unknown_cmd') {
                   6223: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6224: 				      $udom, $tryserver);
                   6225: 		    @listing_results = split(/:/,$listing);
                   6226: 		} else {
                   6227: 		    @listing_results =
                   6228: 			map { &unescape($_); } split(/:/,$listing);
                   6229: 		}
                   6230: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6231: 		    $listing_results[0] ne 'empty'       &&
                   6232: 		    $listing_results[0] ne 'con_lost') {
                   6233: 		    foreach my $line (@listing_results) {
                   6234: 			my ($entry) = split(/&/,$line,2);
                   6235: 			$allusers{$entry} = 1;
                   6236: 		    }
                   6237: 		}
1.253     stredwic 6238:             }
                   6239:             my $alluserstr='';
1.800     albertel 6240:             foreach my $user (sort(keys(%allusers))) {
                   6241:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6242:             }
                   6243:             $alluserstr=~s/:$//;
                   6244:             return split(/:/,$alluserstr);
                   6245:         } else {
1.800     albertel 6246:             return ('missing user name');
1.253     stredwic 6247:         }
                   6248:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6249:         my @all_domains = sort(&all_domains());
                   6250:          foreach my $domain (@all_domains) {
                   6251:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6252:          }
                   6253:          return @all_domains;
                   6254:      } else {
1.800     albertel 6255:         return ('missing domain');
1.275     stredwic 6256:     }
                   6257: }
                   6258: 
                   6259: # --------------------------------------------- GetFileTimestamp
                   6260: # This function utilizes dirlist and returns the date stamp for
                   6261: # when it was last modified.  It will also return an error of -1
                   6262: # if an error occurs
                   6263: 
1.410     matthew  6264: ##
                   6265: ## FIXME: This subroutine assumes its caller knows something about the
                   6266: ## directory structure of the home server for the student ($root).
                   6267: ## Not a good assumption to make.  Since this is for looking up files
                   6268: ## in user directories, the full path should be constructed by lond, not
                   6269: ## whatever machine we request data from.
                   6270: ##
1.275     stredwic 6271: sub GetFileTimestamp {
                   6272:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6273:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6274:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6275:     my $subdir=$studentName.'__';
                   6276:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6277:     my $proname="$studentDomain/$subdir/$studentName";
                   6278:     $proname .= '/'.$filename;
1.375     matthew  6279:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6280:                                               $studentName, $root);
1.275     stredwic 6281:     my @stats = split('&', $fileStat);
                   6282:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6283:         # @stats contains first the filename, then the stat output
                   6284:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6285:     } else {
                   6286:         return -1;
1.253     stredwic 6287:     }
1.26      www      6288: }
                   6289: 
1.712     albertel 6290: sub stat_file {
                   6291:     my ($uri) = @_;
1.787     albertel 6292:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6293: 
1.712     albertel 6294:     my ($udom,$uname,$file,$dir);
                   6295:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6296: 	($udom,$uname,$file) =
1.811     albertel 6297: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6298: 	$file = 'userfiles/'.$file;
1.740     www      6299: 	$dir = &propath($udom,$uname);
1.712     albertel 6300:     }
                   6301:     if ($uri =~ m-^/res/-) {
                   6302: 	($udom,$uname) = 
1.807     albertel 6303: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6304: 	$file = $uri;
                   6305:     }
                   6306: 
                   6307:     if (!$udom || !$uname || !$file) {
                   6308: 	# unable to handle the uri
                   6309: 	return ();
                   6310:     }
                   6311: 
                   6312:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6313:     my @stats = split('&', $result);
1.721     banghart 6314:     
1.712     albertel 6315:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6316: 	shift(@stats); #filename is first
                   6317: 	return @stats;
                   6318:     }
                   6319:     return ();
                   6320: }
                   6321: 
1.26      www      6322: # -------------------------------------------------------- Value of a Condition
                   6323: 
1.713     albertel 6324: # gets the value of a specific preevaluated condition
                   6325: #    stored in the string  $env{user.state.<cid>}
                   6326: # or looks up a condition reference in the bighash and if if hasn't
                   6327: # already been evaluated recurses into docondval to get the value of
                   6328: # the condition, then memoizing it to 
                   6329: #   $env{user.state.<cid>.<condition>}
1.40      www      6330: sub directcondval {
                   6331:     my $number=shift;
1.620     albertel 6332:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6333: 	&Apache::lonuserstate::evalstate();
                   6334:     }
1.713     albertel 6335:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6336: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6337:     } elsif ($number =~ /^_/) {
                   6338: 	my $sub_condition;
                   6339: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6340: 		&GDBM_READER(),0640)) {
                   6341: 	    $sub_condition=$bighash{'conditions'.$number};
                   6342: 	    untie(%bighash);
                   6343: 	}
                   6344: 	my $value = &docondval($sub_condition);
                   6345: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6346: 	return $value;
                   6347:     }
1.620     albertel 6348:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6349:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6350:     } else {
                   6351:        return 2;
                   6352:     }
                   6353: }
                   6354: 
1.713     albertel 6355: # get the collection of conditions for this resource
1.26      www      6356: sub condval {
                   6357:     my $condidx=shift;
1.54      www      6358:     my $allpathcond='';
1.713     albertel 6359:     foreach my $cond (split(/\|/,$condidx)) {
                   6360: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6361: 	    $allpathcond.=
                   6362: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6363: 	}
1.191     harris41 6364:     }
1.54      www      6365:     $allpathcond=~s/\|$//;
1.713     albertel 6366:     return &docondval($allpathcond);
                   6367: }
                   6368: 
                   6369: #evaluates an expression of conditions
                   6370: sub docondval {
                   6371:     my ($allpathcond) = @_;
                   6372:     my $result=0;
                   6373:     if ($env{'request.course.id'}
                   6374: 	&& defined($allpathcond)) {
                   6375: 	my $operand='|';
                   6376: 	my @stack;
                   6377: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6378: 	    if ($chunk eq '(') {
                   6379: 		push @stack,($operand,$result);
                   6380: 	    } elsif ($chunk eq ')') {
                   6381: 		my $before=pop @stack;
                   6382: 		if (pop @stack eq '&') {
                   6383: 		    $result=$result>$before?$before:$result;
                   6384: 		} else {
                   6385: 		    $result=$result>$before?$result:$before;
                   6386: 		}
                   6387: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6388: 		$operand=$chunk;
                   6389: 	    } else {
                   6390: 		my $new=directcondval($chunk);
                   6391: 		if ($operand eq '&') {
                   6392: 		    $result=$result>$new?$new:$result;
                   6393: 		} else {
                   6394: 		    $result=$result>$new?$result:$new;
                   6395: 		}
                   6396: 	    }
                   6397: 	}
1.26      www      6398:     }
                   6399:     return $result;
1.421     albertel 6400: }
                   6401: 
                   6402: # ---------------------------------------------------- Devalidate courseresdata
                   6403: 
                   6404: sub devalidatecourseresdata {
                   6405:     my ($coursenum,$coursedomain)=@_;
                   6406:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6407:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6408: }
                   6409: 
1.763     www      6410: 
1.200     www      6411: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6412: #
                   6413: #  Parameters:
                   6414: #      $coursenum    - Number of the course.
                   6415: #      $coursedomain - Domain at which the course was created.
                   6416: #  Returns:
                   6417: #     A hash of the course parameters along (I think) with timestamps
                   6418: #     and version info.
1.877     foxr     6419: 
1.624     albertel 6420: sub get_courseresdata {
                   6421:     my ($coursenum,$coursedomain)=@_;
1.200     www      6422:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6423:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6424:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6425:     my %dumpreply;
1.417     albertel 6426:     unless (defined($cached)) {
1.624     albertel 6427: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6428: 	$result=\%dumpreply;
1.251     albertel 6429: 	my ($tmp) = keys(%dumpreply);
                   6430: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6431: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6432: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6433: 	    return $tmp;
1.416     albertel 6434: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6435: 	    $result=undef;
1.599     albertel 6436: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6437: 	}
                   6438:     }
1.624     albertel 6439:     return $result;
                   6440: }
                   6441: 
1.633     albertel 6442: sub devalidateuserresdata {
                   6443:     my ($uname,$udom)=@_;
                   6444:     my $hashid="$udom:$uname";
                   6445:     &devalidate_cache_new('userres',$hashid);
                   6446: }
                   6447: 
1.624     albertel 6448: sub get_userresdata {
                   6449:     my ($uname,$udom)=@_;
                   6450:     #most student don\'t have any data set, check if there is some data
                   6451:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6452: 
                   6453:     my $hashid="$udom:$uname";
                   6454:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6455:     if (!defined($cached)) {
                   6456: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6457: 	$result=\%resourcedata;
                   6458: 	&do_cache_new('userres',$hashid,$result,600);
                   6459:     }
                   6460:     my ($tmp)=keys(%$result);
                   6461:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6462: 	return $result;
                   6463:     }
                   6464:     #error 2 occurs when the .db doesn't exist
                   6465:     if ($tmp!~/error: 2 /) {
1.672     albertel 6466: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6467: 		 " Trying to get resource data for ".
                   6468: 		 $uname." at ".$udom.": ".
                   6469: 		 $tmp."</font>");
                   6470:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6471: 	#&EXT_cache_set($udom,$uname);
                   6472: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6473: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6474:     }
                   6475:     return $tmp;
                   6476: }
1.879     foxr     6477: #----------------------------------------------- resdata - return resource data
                   6478: #  Purpose:
                   6479: #    Return resource data for either users or for a course.
                   6480: #  Parameters:
                   6481: #     $name      - Course/user name.
                   6482: #     $domain    - Name of the domain the user/course is registered on.
                   6483: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6484: #     @which     - Array of names of resources desired.
                   6485: #  Returns:
                   6486: #     The value of the first reasource in @which that is found in the
                   6487: #     resource hash.
                   6488: #  Exceptional Conditions:
                   6489: #     If the $type passed in is not valid (not the string 'course' or 
                   6490: #     'user', an undefined  reference is returned.
                   6491: #     If none of the resources are found, an undef is returned
1.624     albertel 6492: sub resdata {
                   6493:     my ($name,$domain,$type,@which)=@_;
                   6494:     my $result;
                   6495:     if ($type eq 'course') {
                   6496: 	$result=&get_courseresdata($name,$domain);
                   6497:     } elsif ($type eq 'user') {
                   6498: 	$result=&get_userresdata($name,$domain);
                   6499:     }
                   6500:     if (!ref($result)) { return $result; }    
1.251     albertel 6501:     foreach my $item (@which) {
1.927     albertel 6502: 	if (defined($result->{$item->[0]})) {
                   6503: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6504: 	}
1.250     albertel 6505:     }
1.291     albertel 6506:     return undef;
1.200     www      6507: }
                   6508: 
1.379     matthew  6509: #
                   6510: # EXT resource caching routines
                   6511: #
                   6512: 
                   6513: sub clear_EXT_cache_status {
1.383     albertel 6514:     &delenv('cache.EXT.');
1.379     matthew  6515: }
                   6516: 
                   6517: sub EXT_cache_status {
                   6518:     my ($target_domain,$target_user) = @_;
1.383     albertel 6519:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6520:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6521:         # We know already the user has no data
                   6522:         return 1;
                   6523:     } else {
                   6524:         return 0;
                   6525:     }
                   6526: }
                   6527: 
                   6528: sub EXT_cache_set {
                   6529:     my ($target_domain,$target_user) = @_;
1.383     albertel 6530:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6531:     #&appenv($cachename => time);
1.379     matthew  6532: }
                   6533: 
1.28      www      6534: # --------------------------------------------------------- Value of a Variable
1.58      www      6535: sub EXT {
1.715     albertel 6536: 
1.395     albertel 6537:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6538:     unless ($varname) { return ''; }
1.218     albertel 6539:     #get real user name/domain, courseid and symb
                   6540:     my $courseid;
1.359     albertel 6541:     my $publicuser;
1.427     www      6542:     if ($symbparm) {
                   6543: 	$symbparm=&get_symb_from_alias($symbparm);
                   6544:     }
1.218     albertel 6545:     if (!($uname && $udom)) {
1.790     albertel 6546:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6547:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6548:     } else {
1.620     albertel 6549: 	$courseid=$env{'request.course.id'};
1.218     albertel 6550:     }
1.48      www      6551:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6552:     my $rest;
1.320     albertel 6553:     if (defined($therest[0])) {
1.48      www      6554:        $rest=join('.',@therest);
                   6555:     } else {
                   6556:        $rest='';
                   6557:     }
1.320     albertel 6558: 
1.57      www      6559:     my $qualifierrest=$qualifier;
                   6560:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6561:     my $spacequalifierrest=$space;
                   6562:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6563:     if ($realm eq 'user') {
1.48      www      6564: # --------------------------------------------------------------- user.resource
                   6565: 	if ($space eq 'resource') {
1.651     albertel 6566: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6567: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6568: 		 &&
1.744     albertel 6569: 		 ($symbparm eq &symbread()) ) {	
                   6570: 		# if we are in the middle of processing the resource the
                   6571: 		# get the value we are planning on committing
                   6572:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6573:                     return $Apache::lonhomework::results{$qualifierrest};
                   6574:                 } else {
                   6575:                     return $Apache::lonhomework::history{$qualifierrest};
                   6576:                 }
1.335     albertel 6577: 	    } else {
1.359     albertel 6578: 		my %restored;
1.620     albertel 6579: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6580: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6581: 		} else {
                   6582: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6583: 		}
1.335     albertel 6584: 		return $restored{$qualifierrest};
                   6585: 	    }
1.48      www      6586: # ----------------------------------------------------------------- user.access
                   6587:         } elsif ($space eq 'access') {
1.218     albertel 6588: 	    # FIXME - not supporting calls for a specific user
1.48      www      6589:             return &allowed($qualifier,$rest);
                   6590: # ------------------------------------------ user.preferences, user.environment
                   6591:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6592: 	    if (($uname eq $env{'user.name'}) &&
                   6593: 		($udom eq $env{'user.domain'})) {
                   6594: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6595: 	    } else {
1.359     albertel 6596: 		my %returnhash;
                   6597: 		if (!$publicuser) {
                   6598: 		    %returnhash=&userenvironment($udom,$uname,
                   6599: 						 $qualifierrest);
                   6600: 		}
1.218     albertel 6601: 		return $returnhash{$qualifierrest};
                   6602: 	    }
1.48      www      6603: # ----------------------------------------------------------------- user.course
                   6604:         } elsif ($space eq 'course') {
1.218     albertel 6605: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6606:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6607: # ------------------------------------------------------------------- user.role
                   6608:         } elsif ($space eq 'role') {
1.218     albertel 6609: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6610:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6611:             if ($qualifier eq 'value') {
                   6612: 		return $role;
                   6613:             } elsif ($qualifier eq 'extent') {
                   6614:                 return $where;
                   6615:             }
                   6616: # ----------------------------------------------------------------- user.domain
                   6617:         } elsif ($space eq 'domain') {
1.218     albertel 6618:             return $udom;
1.48      www      6619: # ------------------------------------------------------------------- user.name
                   6620:         } elsif ($space eq 'name') {
1.218     albertel 6621:             return $uname;
1.48      www      6622: # ---------------------------------------------------- Any other user namespace
1.29      www      6623:         } else {
1.359     albertel 6624: 	    my %reply;
                   6625: 	    if (!$publicuser) {
                   6626: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6627: 	    }
                   6628: 	    return $reply{$qualifierrest};
1.48      www      6629:         }
1.236     www      6630:     } elsif ($realm eq 'query') {
                   6631: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6632:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6633: 						[$spacequalifierrest]);
1.620     albertel 6634: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6635:    } elsif ($realm eq 'request') {
1.48      www      6636: # ------------------------------------------------------------- request.browser
                   6637:         if ($space eq 'browser') {
1.430     www      6638: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6639: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6640: 		    return 1;
                   6641: 		} else {
                   6642: 		    return 0;
                   6643: 		}
                   6644: 	    } else {
1.620     albertel 6645: 		return $env{'browser.'.$qualifier};
1.430     www      6646: 	    }
1.57      www      6647: # ------------------------------------------------------------ request.filename
                   6648:         } else {
1.620     albertel 6649:             return $env{'request.'.$spacequalifierrest};
1.29      www      6650:         }
1.28      www      6651:     } elsif ($realm eq 'course') {
1.48      www      6652: # ---------------------------------------------------------- course.description
1.620     albertel 6653:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6654:     } elsif ($realm eq 'resource') {
1.165     www      6655: 
1.620     albertel 6656: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6657: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6658: 	}
1.693     albertel 6659: 
                   6660: 	if ($space eq 'title') {
                   6661: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6662: 	    return &gettitle($symbparm);
                   6663: 	}
                   6664: 	
                   6665: 	if ($space eq 'map') {
                   6666: 	    my ($map) = &decode_symb($symbparm);
                   6667: 	    return &symbread($map);
                   6668: 	}
1.905     albertel 6669: 	if ($space eq 'filename') {
                   6670: 	    if ($symbparm) {
                   6671: 		return &clutter((&decode_symb($symbparm))[2]);
                   6672: 	    }
                   6673: 	    return &hreflocation('',$env{'request.filename'});
                   6674: 	}
1.693     albertel 6675: 
                   6676: 	my ($section, $group, @groups);
1.593     albertel 6677: 	my ($courselevelm,$courselevel);
1.539     albertel 6678: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6679: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6680: 
1.218     albertel 6681: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6682: 
1.60      www      6683: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6684: 	    my $symbp=$symbparm;
1.735     albertel 6685: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6686: 
                   6687: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6688: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6689: 
1.620     albertel 6690: 	    if (($env{'user.name'} eq $uname) &&
                   6691: 		($env{'user.domain'} eq $udom)) {
                   6692: 		$section=$env{'request.course.sec'};
1.733     raeburn  6693:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6694:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6695: 	    } else {
1.539     albertel 6696: 		if (! defined($usection)) {
1.551     albertel 6697: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6698: 		} else {
                   6699: 		    $section = $usection;
                   6700: 		}
1.733     raeburn  6701:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6702: 	    }
                   6703: 
                   6704: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6705: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6706: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6707: 
1.593     albertel 6708: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6709: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6710: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6711: 
1.60      www      6712: # ----------------------------------------------------------- first, check user
1.624     albertel 6713: 
                   6714: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6715: 				       ([$courselevelr,'resource'],
                   6716: 					[$courselevelm,'map'     ],
                   6717: 					[$courselevel, 'course'  ]));
1.931     albertel 6718: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6719: 
1.594     albertel 6720: # ------------------------------------------------ second, check some of course
1.684     raeburn  6721:             my $coursereply;
1.691     raeburn  6722:             if (@groups > 0) {
                   6723:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6724:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6725:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6726:             }
1.96      www      6727: 
1.684     raeburn  6728: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6729: 				  $env{'course.'.$courseid.'.domain'},
                   6730: 				  'course',
                   6731: 				  ([$seclevelr,   'resource'],
                   6732: 				   [$seclevelm,   'map'     ],
                   6733: 				   [$seclevel,    'course'  ],
                   6734: 				   [$courselevelr,'resource']));
                   6735: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6736: 
1.60      www      6737: # ------------------------------------------------------ third, check map parms
1.218     albertel 6738: 	    my %parmhash=();
                   6739: 	    my $thisparm='';
                   6740: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6741: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6742: 		    &GDBM_READER(),0640)) {
1.218     albertel 6743: 		$thisparm=$parmhash{$symbparm};
                   6744: 		untie(%parmhash);
                   6745: 	    }
1.927     albertel 6746: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6747: 	}
1.594     albertel 6748: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6749: 
1.218     albertel 6750: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6751: 	my $filename;
                   6752: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6753: 	if ($symbparm) {
1.409     www      6754: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6755: 	} else {
1.620     albertel 6756: 	    $filename=$env{'request.filename'};
1.282     albertel 6757: 	}
                   6758: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6759: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6760: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6761: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6762: 
1.927     albertel 6763: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6764: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6765: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6766: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6767: 				     $env{'course.'.$courseid.'.domain'},
                   6768: 				     'course',
1.927     albertel 6769: 				     ([$courselevelm,'map'   ],
                   6770: 				      [$courselevel, 'course']));
                   6771: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6772: 	}
1.145     www      6773: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6774: 	unless ($space eq '0') {
1.336     albertel 6775: 	    my @parts=split(/_/,$space);
                   6776: 	    my $id=pop(@parts);
                   6777: 	    my $part=join('_',@parts);
                   6778: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6779: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6780: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6781: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6782: 	}
1.395     albertel 6783: 	if ($recurse) { return undef; }
                   6784: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6785: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6786: # ---------------------------------------------------- Any other user namespace
                   6787:     } elsif ($realm eq 'environment') {
                   6788: # ----------------------------------------------------------------- environment
1.620     albertel 6789: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6790: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6791: 	} else {
1.770     albertel 6792: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6793: 		return '';
                   6794: 	    }
1.219     albertel 6795: 	    my %returnhash=&userenvironment($udom,$uname,
                   6796: 					    $spacequalifierrest);
                   6797: 	    return $returnhash{$spacequalifierrest};
                   6798: 	}
1.28      www      6799:     } elsif ($realm eq 'system') {
1.48      www      6800: # ----------------------------------------------------------------- system.time
                   6801: 	if ($space eq 'time') {
                   6802: 	    return time;
                   6803:         }
1.696     albertel 6804:     } elsif ($realm eq 'server') {
                   6805: # ----------------------------------------------------------------- system.time
                   6806: 	if ($space eq 'name') {
                   6807: 	    return $ENV{'SERVER_NAME'};
                   6808:         }
1.28      www      6809:     }
1.48      www      6810:     return '';
1.61      www      6811: }
                   6812: 
1.927     albertel 6813: sub get_reply {
                   6814:     my ($reply_value) = @_;
1.940     raeburn  6815:     if (ref($reply_value) eq 'ARRAY') {
                   6816:         if (wantarray) {
                   6817: 	    return @$reply_value;
                   6818:         }
                   6819:         return $reply_value->[0];
                   6820:     } else {
                   6821:         return $reply_value;
1.927     albertel 6822:     }
                   6823: }
                   6824: 
1.691     raeburn  6825: sub check_group_parms {
                   6826:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6827:     my @groupitems = ();
                   6828:     my $resultitem;
1.927     albertel 6829:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6830:     foreach my $group (@{$groups}) {
                   6831:         foreach my $level (@levels) {
1.927     albertel 6832:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6833:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6834:         }
                   6835:     }
                   6836:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6837:                             $env{'course.'.$courseid.'.domain'},
                   6838:                                      'course',@groupitems);
                   6839:     return $coursereply;
                   6840: }
                   6841: 
                   6842: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6843:     my ($courseid,@groups) = @_;
                   6844:     @groups = sort(@groups);
1.691     raeburn  6845:     return @groups;
                   6846: }
                   6847: 
1.395     albertel 6848: sub packages_tab_default {
                   6849:     my ($uri,$varname)=@_;
                   6850:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6851: 
                   6852:     my (@extension,@specifics,$do_default);
                   6853:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6854: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6855: 	if ($pack_type eq 'default') {
                   6856: 	    $do_default=1;
                   6857: 	} elsif ($pack_type eq 'extension') {
                   6858: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6859: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6860: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6861: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6862: 	}
                   6863:     }
                   6864:     # first look for a package that matches the requested part id
                   6865:     foreach my $package (@specifics) {
                   6866: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6867: 	next if ($pack_part ne $part);
                   6868: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6869: 	    return $packagetab{"$pack_type&$name&default"};
                   6870: 	}
                   6871:     }
                   6872:     # look for any possible matching non extension_ package
                   6873:     foreach my $package (@specifics) {
                   6874: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6875: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6876: 	    return $packagetab{"$pack_type&$name&default"};
                   6877: 	}
1.585     albertel 6878: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6879: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6880: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6881: 	}
                   6882:     }
1.738     albertel 6883:     # look for any posible extension_ match
                   6884:     foreach my $package (@extension) {
                   6885: 	my ($package,$pack_type)=@{$package};
                   6886: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6887: 	    return $packagetab{"$pack_type&$name&default"};
                   6888: 	}
                   6889: 	if (defined($packagetab{$package."&$name&default"})) {
                   6890: 	    return $packagetab{$package."&$name&default"};
                   6891: 	}
                   6892:     }
                   6893:     # look for a global default setting
                   6894:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6895: 	return $packagetab{"default&$name&default"};
                   6896:     }
1.395     albertel 6897:     return undef;
                   6898: }
                   6899: 
1.334     albertel 6900: sub add_prefix_and_part {
                   6901:     my ($prefix,$part)=@_;
                   6902:     my $keyroot;
                   6903:     if (defined($prefix) && $prefix !~ /^__/) {
                   6904: 	# prefix that has a part already
                   6905: 	$keyroot=$prefix;
                   6906:     } elsif (defined($prefix)) {
                   6907: 	# prefix that is missing a part
                   6908: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6909:     } else {
                   6910: 	# no prefix at all
                   6911: 	if (defined($part)) { $keyroot='_'.$part; }
                   6912:     }
                   6913:     return $keyroot;
                   6914: }
                   6915: 
1.71      www      6916: # ---------------------------------------------------------------- Get metadata
                   6917: 
1.599     albertel 6918: my %metaentry;
1.71      www      6919: sub metadata {
1.176     www      6920:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6921:     $uri=&declutter($uri);
1.288     albertel 6922:     # if it is a non metadata possible uri return quickly
1.529     albertel 6923:     if (($uri eq '') || 
                   6924: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6925: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 6926:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   6927: 	return undef;
                   6928:     }
                   6929:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   6930: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 6931: 	return undef;
1.288     albertel 6932:     }
1.73      www      6933:     my $filename=$uri;
                   6934:     $uri=~s/\.meta$//;
1.172     www      6935: #
                   6936: # Is the metadata already cached?
1.177     www      6937: # Look at timestamp of caching
1.172     www      6938: # Everything is cached by the main uri, libraries are never directly cached
                   6939: #
1.428     albertel 6940:     if (!defined($liburi)) {
1.599     albertel 6941: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6942: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6943:     }
                   6944:     {
1.172     www      6945: #
                   6946: # Is this a recursive call for a library?
                   6947: #
1.599     albertel 6948: #	if (! exists($metacache{$uri})) {
                   6949: #	    $metacache{$uri}={};
                   6950: #	}
1.924     albertel 6951: 	my $cachetime = 60*60;
1.171     www      6952:         if ($liburi) {
                   6953: 	    $liburi=&declutter($liburi);
                   6954:             $filename=$liburi;
1.401     bowersj2 6955:         } else {
1.599     albertel 6956: 	    &devalidate_cache_new('meta',$uri);
                   6957: 	    undef(%metaentry);
1.401     bowersj2 6958: 	}
1.140     www      6959:         my %metathesekeys=();
1.73      www      6960:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6961: 	my $metastring;
1.924     albertel 6962: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 6963: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 6964: 	    $metastring = 
1.929     albertel 6965: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 6966: 					  ('grade_target' => 'meta'));
                   6967: 	    $cachetime = 1; # only want this cached in the child not long term
                   6968: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 6969: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6970: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6971: 	    $metastring=&getfile($file);
1.489     albertel 6972: 	}
1.208     albertel 6973:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6974:         my $token;
1.140     www      6975:         undef %metathesekeys;
1.71      www      6976:         while ($token=$parser->get_token) {
1.339     albertel 6977: 	    if ($token->[0] eq 'S') {
                   6978: 		if (defined($token->[2]->{'package'})) {
1.172     www      6979: #
                   6980: # This is a package - get package info
                   6981: #
1.339     albertel 6982: 		    my $package=$token->[2]->{'package'};
                   6983: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6984: 		    if (defined($token->[2]->{'id'})) { 
                   6985: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6986: 		    }
1.599     albertel 6987: 		    if ($metaentry{':packages'}) {
                   6988: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6989: 		    } else {
1.599     albertel 6990: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6991: 		    }
1.736     albertel 6992: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6993: 			my $part=$keyroot;
                   6994: 			$part=~s/^\_//;
1.736     albertel 6995: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6996: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6997: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6998: 			    # ignore package.tab specified default values
                   6999:                             # here &package_tab_default() will fetch those
                   7000: 			    if ($subp eq 'default') { next; }
1.736     albertel 7001: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7002: 			    my $unikey;
                   7003: 			    if ($pack =~ /_0$/) {
                   7004: 				$unikey='parameter_0_'.$name;
                   7005: 				$part=0;
                   7006: 			    } else {
                   7007: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7008: 			    }
1.339     albertel 7009: 			    if ($subp eq 'display') {
                   7010: 				$value.=' [Part: '.$part.']';
                   7011: 			    }
1.599     albertel 7012: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7013: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7014: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7015: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7016: 			    }
1.599     albertel 7017: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7018: 				$metaentry{':'.$unikey}=
                   7019: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7020: 			    }
1.339     albertel 7021: 			}
                   7022: 		    }
                   7023: 		} else {
1.172     www      7024: #
                   7025: # This is not a package - some other kind of start tag
1.339     albertel 7026: #
                   7027: 		    my $entry=$token->[1];
                   7028: 		    my $unikey;
                   7029: 		    if ($entry eq 'import') {
                   7030: 			$unikey='';
                   7031: 		    } else {
                   7032: 			$unikey=$entry;
                   7033: 		    }
                   7034: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7035: 
                   7036: 		    if (defined($token->[2]->{'id'})) { 
                   7037: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7038: 		    }
1.175     www      7039: 
1.339     albertel 7040: 		    if ($entry eq 'import') {
1.175     www      7041: #
                   7042: # Importing a library here
1.339     albertel 7043: #
                   7044: 			if ($depthcount<20) {
                   7045: 			    my $location=$parser->get_text('/import');
                   7046: 			    my $dir=$filename;
                   7047: 			    $dir=~s|[^/]*$||;
                   7048: 			    $location=&filelocation($dir,$location);
1.736     albertel 7049: 			    my $metadata = 
                   7050: 				&metadata($uri,'keys', $location,$unikey,
                   7051: 					  $depthcount+1);
                   7052: 			    foreach my $meta (split(',',$metadata)) {
                   7053: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7054: 				$metathesekeys{$meta}=1;
1.339     albertel 7055: 			    }
                   7056: 			}
                   7057: 		    } else { 
                   7058: 			
                   7059: 			if (defined($token->[2]->{'name'})) { 
                   7060: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7061: 			}
                   7062: 			$metathesekeys{$unikey}=1;
1.736     albertel 7063: 			foreach my $param (@{$token->[3]}) {
                   7064: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7065: 				$token->[2]->{$param};
1.339     albertel 7066: 			}
                   7067: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7068: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7069: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7070: 		 # only ws inside the tag, and not in default, so use default
                   7071: 		 # as value
1.599     albertel 7072: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7073: 			} elsif ( $internaltext =~ /\S/ ) {
                   7074: 		  # something interesting inside the tag
                   7075: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7076: 			} else {
1.908     albertel 7077: 		  # no interesting values, don't set a default
1.339     albertel 7078: 			}
1.172     www      7079: # end of not-a-package not-a-library import
1.339     albertel 7080: 		    }
1.172     www      7081: # end of not-a-package start tag
1.339     albertel 7082: 		}
1.172     www      7083: # the next is the end of "start tag"
1.339     albertel 7084: 	    }
                   7085: 	}
1.483     albertel 7086: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7087: 	$extension = lc($extension);
                   7088: 	if ($extension eq 'htm') { $extension='html'; }
                   7089: 
1.737     albertel 7090: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7091: 	    #no specific packages #how's our extension
                   7092: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7093: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7094: 					 \%metathesekeys);
                   7095: 	}
1.883     albertel 7096: 
                   7097: 	if (!exists($metaentry{':packages'})
                   7098: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7099: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7100: 		#no specific packages well let's get default then
                   7101: 		if ($key!~/^default&/) { next; }
1.488     albertel 7102: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7103: 					     \%metathesekeys);
                   7104: 	    }
                   7105: 	}
1.338     www      7106: # are there custom rights to evaluate
1.599     albertel 7107: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7108: 
1.338     www      7109:     #
                   7110:     # Importing a rights file here
1.339     albertel 7111:     #
                   7112: 	    unless ($depthcount) {
1.599     albertel 7113: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7114: 		my $dir=$filename;
                   7115: 		$dir=~s|[^/]*$||;
                   7116: 		$location=&filelocation($dir,$location);
1.736     albertel 7117: 		my $rights_metadata =
                   7118: 		    &metadata($uri,'keys',$location,'_rights',
                   7119: 			      $depthcount+1);
                   7120: 		foreach my $rights (split(',',$rights_metadata)) {
                   7121: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7122: 		    $metathesekeys{$rights}=1;
1.339     albertel 7123: 		}
                   7124: 	    }
                   7125: 	}
1.737     albertel 7126: 	# uniqifiy package listing
                   7127: 	my %seen;
                   7128: 	my @uniq_packages =
                   7129: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7130: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7131: 
                   7132: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7133: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7134: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7135: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7136: # this is the end of "was not already recently cached
1.71      www      7137:     }
1.599     albertel 7138:     return $metaentry{':'.$what};
1.261     albertel 7139: }
                   7140: 
1.488     albertel 7141: sub metadata_create_package_def {
1.483     albertel 7142:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7143:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7144:     if ($subp eq 'default') { next; }
                   7145:     
1.599     albertel 7146:     if (defined($metaentry{':packages'})) {
                   7147: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7148:     } else {
1.599     albertel 7149: 	$metaentry{':packages'}=$package;
1.483     albertel 7150:     }
                   7151:     my $value=$packagetab{$key};
                   7152:     my $unikey;
                   7153:     $unikey='parameter_0_'.$name;
1.599     albertel 7154:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7155:     $$metathesekeys{$unikey}=1;
1.599     albertel 7156:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7157: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7158:     }
1.599     albertel 7159:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7160: 	$metaentry{':'.$unikey}=
                   7161: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7162:     }
                   7163: }
                   7164: 
1.261     albertel 7165: sub metadata_generate_part0 {
                   7166:     my ($metadata,$metacache,$uri) = @_;
                   7167:     my %allnames;
1.737     albertel 7168:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7169: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7170: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7171: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7172: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7173: 	    $allnames{$name}=$part;
                   7174: 	  }
                   7175: 	}
                   7176:     }
                   7177:     foreach my $name (keys(%allnames)) {
                   7178:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7179:       my $key=":parameter_0_$name";
1.261     albertel 7180:       $$metacache{"$key.part"}='0';
                   7181:       $$metacache{"$key.name"}=$name;
1.428     albertel 7182:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7183: 					   $allnames{$name}.'_'.$name.
                   7184: 					   '.type'};
1.428     albertel 7185:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7186: 			     '.display'};
1.644     www      7187:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7188:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7189:       $$metacache{"$key.display"}=$olddis;
                   7190:     }
1.71      www      7191: }
                   7192: 
1.764     albertel 7193: # ------------------------------------------------------ Devalidate title cache
                   7194: 
                   7195: sub devalidate_title_cache {
                   7196:     my ($url)=@_;
                   7197:     if (!$env{'request.course.id'}) { return; }
                   7198:     my $symb=&symbread($url);
                   7199:     if (!$symb) { return; }
                   7200:     my $key=$env{'request.course.id'}."\0".$symb;
                   7201:     &devalidate_cache_new('title',$key);
                   7202: }
                   7203: 
1.301     www      7204: # ------------------------------------------------- Get the title of a resource
                   7205: 
                   7206: sub gettitle {
                   7207:     my $urlsymb=shift;
                   7208:     my $symb=&symbread($urlsymb);
1.534     albertel 7209:     if ($symb) {
1.620     albertel 7210: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7211: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7212: 	if (defined($cached)) { 
                   7213: 	    return $result;
                   7214: 	}
1.534     albertel 7215: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7216: 	my $title='';
1.907     albertel 7217: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7218: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7219: 	} else {
                   7220: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7221: 		    &GDBM_READER(),0640)) {
                   7222: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7223: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7224: 		untie(%bighash);
                   7225: 	    }
1.534     albertel 7226: 	}
                   7227: 	$title=~s/\&colon\;/\:/gs;
                   7228: 	if ($title) {
1.599     albertel 7229: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7230: 	}
                   7231: 	$urlsymb=$url;
                   7232:     }
                   7233:     my $title=&metadata($urlsymb,'title');
                   7234:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7235:     return $title;
1.301     www      7236: }
1.613     albertel 7237: 
1.614     albertel 7238: sub get_slot {
                   7239:     my ($which,$cnum,$cdom)=@_;
                   7240:     if (!$cnum || !$cdom) {
1.790     albertel 7241: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7242: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7243: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7244:     }
1.703     albertel 7245:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7246:     my %slotinfo;
                   7247:     if (exists($remembered{$key})) {
                   7248: 	$slotinfo{$which} = $remembered{$key};
                   7249:     } else {
                   7250: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7251: 	&Apache::lonhomework::showhash(%slotinfo);
                   7252: 	my ($tmp)=keys(%slotinfo);
                   7253: 	if ($tmp=~/^error:/) { return (); }
                   7254: 	$remembered{$key} = $slotinfo{$which};
                   7255:     }
1.616     albertel 7256:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7257: 	return %{$slotinfo{$which}};
                   7258:     }
                   7259:     return $slotinfo{$which};
1.614     albertel 7260: }
1.31      www      7261: # ------------------------------------------------- Update symbolic store links
                   7262: 
                   7263: sub symblist {
                   7264:     my ($mapname,%newhash)=@_;
1.438     www      7265:     $mapname=&deversion(&declutter($mapname));
1.31      www      7266:     my %hash;
1.620     albertel 7267:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7268:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7269:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7270: 	    foreach my $url (keys %newhash) {
                   7271: 		next if ($url eq 'last_known'
                   7272: 			 && $env{'form.no_update_last_known'});
                   7273: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7274: 						    $newhash{$url}->[1],
                   7275: 						    $newhash{$url}->[0]);
1.191     harris41 7276:             }
1.31      www      7277:             if (untie(%hash)) {
                   7278: 		return 'ok';
                   7279:             }
                   7280:         }
                   7281:     }
                   7282:     return 'error';
1.212     www      7283: }
                   7284: 
                   7285: # --------------------------------------------------------------- Verify a symb
                   7286: 
                   7287: sub symbverify {
1.510     www      7288:     my ($symb,$thisurl)=@_;
                   7289:     my $thisfn=$thisurl;
1.439     www      7290:     $thisfn=&declutter($thisfn);
1.215     www      7291: # direct jump to resource in page or to a sequence - will construct own symbs
                   7292:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7293: # check URL part
1.409     www      7294:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7295: 
1.431     www      7296:     unless ($url eq $thisfn) { return 0; }
1.213     www      7297: 
1.216     www      7298:     $symb=&symbclean($symb);
1.510     www      7299:     $thisurl=&deversion($thisurl);
1.439     www      7300:     $thisfn=&deversion($thisfn);
1.213     www      7301: 
                   7302:     my %bighash;
                   7303:     my $okay=0;
1.431     www      7304: 
1.620     albertel 7305:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7306:                             &GDBM_READER(),0640)) {
1.510     www      7307:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7308:         unless ($ids) { 
1.510     www      7309:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7310:         }
                   7311:         if ($ids) {
                   7312: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7313: 	    foreach my $id (split(/\,/,$ids)) {
                   7314: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7315:                if (
                   7316:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7317:    eq $symb) { 
1.620     albertel 7318: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7319: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7320: 		       $okay=1; 
                   7321: 		   }
                   7322: 	       }
1.216     www      7323: 	   }
                   7324:         }
1.213     www      7325: 	untie(%bighash);
                   7326:     }
                   7327:     return $okay;
1.31      www      7328: }
                   7329: 
1.210     www      7330: # --------------------------------------------------------------- Clean-up symb
                   7331: 
                   7332: sub symbclean {
                   7333:     my $symb=shift;
1.568     albertel 7334:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7335: # remove version from map
                   7336:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7337: 
1.210     www      7338: # remove version from URL
                   7339:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7340: 
1.507     www      7341: # remove wrapper
                   7342: 
1.510     www      7343:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7344:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7345:     return $symb;
1.409     www      7346: }
                   7347: 
                   7348: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7349: 
                   7350: sub encode_symb {
                   7351:     my ($map,$resid,$url)=@_;
                   7352:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7353: }
1.409     www      7354: 
                   7355: sub decode_symb {
1.568     albertel 7356:     my $symb=shift;
                   7357:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7358:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7359:     return (&fixversion($map),$resid,&fixversion($url));
                   7360: }
                   7361: 
                   7362: sub fixversion {
                   7363:     my $fn=shift;
1.609     banghart 7364:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7365:     my %bighash;
                   7366:     my $uri=&clutter($fn);
1.620     albertel 7367:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7368: # is this cached?
1.599     albertel 7369:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7370:     if (defined($cached)) { return $result; }
                   7371: # unfortunately not cached, or expired
1.620     albertel 7372:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7373: 	    &GDBM_READER(),0640)) {
                   7374:  	if ($bighash{'version_'.$uri}) {
                   7375:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7376:  	    unless (($version eq 'mostrecent') || 
                   7377: 		    ($version==&getversion($uri))) {
1.440     www      7378:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7379:  	    }
                   7380:  	}
                   7381:  	untie %bighash;
1.413     www      7382:     }
1.599     albertel 7383:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7384: }
                   7385: 
                   7386: sub deversion {
                   7387:     my $url=shift;
                   7388:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7389:     return $url;
1.210     www      7390: }
                   7391: 
1.31      www      7392: # ------------------------------------------------------ Return symb list entry
                   7393: 
                   7394: sub symbread {
1.249     www      7395:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7396:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7397:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7398: # no filename provided? try from environment
1.44      www      7399:     unless ($thisfn) {
1.620     albertel 7400:         if ($env{'request.symb'}) {
                   7401: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7402: 	}
1.620     albertel 7403: 	$thisfn=$env{'request.filename'};
1.44      www      7404:     }
1.569     albertel 7405:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7406: # is that filename actually a symb? Verify, clean, and return
                   7407:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7408: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7409: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7410: 	}
1.242     www      7411:     }
1.44      www      7412:     $thisfn=declutter($thisfn);
1.31      www      7413:     my %hash;
1.37      www      7414:     my %bighash;
                   7415:     my $syval='';
1.620     albertel 7416:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7417:         my $targetfn = $thisfn;
1.609     banghart 7418:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7419:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7420:         }
1.687     albertel 7421: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7422: 	    $targetfn=$1;
                   7423: 	}
1.620     albertel 7424:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7425:                       &GDBM_READER(),0640)) {
1.481     raeburn  7426: 	    $syval=$hash{$targetfn};
1.37      www      7427:             untie(%hash);
                   7428:         }
                   7429: # ---------------------------------------------------------- There was an entry
                   7430:         if ($syval) {
1.601     albertel 7431: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7432: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7433: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7434: 		    #return $env{$cache_str}='';
1.601     albertel 7435: 		#}    
                   7436: 		#$syval.=$1;
                   7437: 	    #}
1.37      www      7438:         } else {
                   7439: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7440:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7441:                             &GDBM_READER(),0640)) {
1.37      www      7442: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7443:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7444:               unless ($ids) { 
                   7445:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7446:               }
                   7447:               unless ($ids) {
                   7448: # alias?
                   7449: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7450:               }
1.37      www      7451:               if ($ids) {
                   7452: # ------------------------------------------------------------------- Has ID(s)
                   7453:                  my @possibilities=split(/\,/,$ids);
1.39      www      7454:                  if ($#possibilities==0) {
                   7455: # ----------------------------------------------- There is only one possibility
1.37      www      7456: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7457: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7458: 						    $resid,$thisfn);
1.249     www      7459:                  } elsif (!$donotrecurse) {
1.39      www      7460: # ------------------------------------------ There is more than one possibility
                   7461:                      my $realpossible=0;
1.800     albertel 7462:                      foreach my $id (@possibilities) {
                   7463: 			 my $file=$bighash{'src_'.$id};
1.39      www      7464:                          if (&allowed('bre',$file)) {
1.800     albertel 7465:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7466:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7467: 				$realpossible++;
1.626     albertel 7468:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7469: 						    $resid,$thisfn);
1.39      www      7470:                             }
                   7471: 			 }
1.191     harris41 7472:                      }
1.39      www      7473: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7474:                  } else {
                   7475:                      $syval='';
1.37      www      7476:                  }
                   7477: 	      }
                   7478:               untie(%bighash)
1.481     raeburn  7479:            }
1.31      www      7480:         }
1.62      www      7481:         if ($syval) {
1.620     albertel 7482: 	    return $env{$cache_str}=$syval;
1.62      www      7483:         }
1.31      www      7484:     }
1.44      www      7485:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7486:     return $env{$cache_str}='';
1.31      www      7487: }
                   7488: 
                   7489: # ---------------------------------------------------------- Return random seed
                   7490: 
1.32      www      7491: sub numval {
                   7492:     my $txt=shift;
                   7493:     $txt=~tr/A-J/0-9/;
                   7494:     $txt=~tr/a-j/0-9/;
                   7495:     $txt=~tr/K-T/0-9/;
                   7496:     $txt=~tr/k-t/0-9/;
                   7497:     $txt=~tr/U-Z/0-5/;
                   7498:     $txt=~tr/u-z/0-5/;
                   7499:     $txt=~s/\D//g;
1.564     albertel 7500:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7501:     return int($txt);
1.368     albertel 7502: }
                   7503: 
1.484     albertel 7504: sub numval2 {
                   7505:     my $txt=shift;
                   7506:     $txt=~tr/A-J/0-9/;
                   7507:     $txt=~tr/a-j/0-9/;
                   7508:     $txt=~tr/K-T/0-9/;
                   7509:     $txt=~tr/k-t/0-9/;
                   7510:     $txt=~tr/U-Z/0-5/;
                   7511:     $txt=~tr/u-z/0-5/;
                   7512:     $txt=~s/\D//g;
                   7513:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7514:     my $total;
                   7515:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7516:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7517:     return int($total);
                   7518: }
                   7519: 
1.575     albertel 7520: sub numval3 {
                   7521:     use integer;
                   7522:     my $txt=shift;
                   7523:     $txt=~tr/A-J/0-9/;
                   7524:     $txt=~tr/a-j/0-9/;
                   7525:     $txt=~tr/K-T/0-9/;
                   7526:     $txt=~tr/k-t/0-9/;
                   7527:     $txt=~tr/U-Z/0-5/;
                   7528:     $txt=~tr/u-z/0-5/;
                   7529:     $txt=~s/\D//g;
                   7530:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7531:     my $total;
                   7532:     foreach my $val (@txts) { $total+=$val; }
                   7533:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7534:     return $total;
                   7535: }
                   7536: 
1.675     albertel 7537: sub digest {
                   7538:     my ($data)=@_;
                   7539:     my $digest=&Digest::MD5::md5($data);
                   7540:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7541:     my ($e,$f);
                   7542:     {
                   7543:         use integer;
                   7544:         $e=($a+$b);
                   7545:         $f=($c+$d);
                   7546:         if ($_64bit) {
                   7547:             $e=(($e<<32)>>32);
                   7548:             $f=(($f<<32)>>32);
                   7549:         }
                   7550:     }
                   7551:     if (wantarray) {
                   7552: 	return ($e,$f);
                   7553:     } else {
                   7554: 	my $g;
                   7555: 	{
                   7556: 	    use integer;
                   7557: 	    $g=($e+$f);
                   7558: 	    if ($_64bit) {
                   7559: 		$g=(($g<<32)>>32);
                   7560: 	    }
                   7561: 	}
                   7562: 	return $g;
                   7563:     }
                   7564: }
                   7565: 
1.368     albertel 7566: sub latest_rnd_algorithm_id {
1.675     albertel 7567:     return '64bit5';
1.366     albertel 7568: }
1.32      www      7569: 
1.503     albertel 7570: sub get_rand_alg {
                   7571:     my ($courseid)=@_;
1.790     albertel 7572:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7573:     if ($courseid) {
1.620     albertel 7574: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7575:     }
                   7576:     return &latest_rnd_algorithm_id();
                   7577: }
                   7578: 
1.562     albertel 7579: sub validCODE {
                   7580:     my ($CODE)=@_;
                   7581:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7582:     return 0;
                   7583: }
                   7584: 
1.491     albertel 7585: sub getCODE {
1.620     albertel 7586:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7587:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7588: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7589: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7590: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7591:     }
                   7592:     return undef;
                   7593: }
                   7594: 
1.31      www      7595: sub rndseed {
1.155     albertel 7596:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7597:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7598:     if (!defined($symb)) {
1.366     albertel 7599: 	unless ($symb=$wsymb) { return time; }
                   7600:     }
                   7601:     if (!$courseid) { $courseid=$wcourseid; }
                   7602:     if (!$domain) { $domain=$wdomain; }
                   7603:     if (!$username) { $username=$wusername }
1.503     albertel 7604:     my $which=&get_rand_alg();
1.803     albertel 7605: 
1.491     albertel 7606:     if (defined(&getCODE())) {
1.675     albertel 7607: 	if ($which eq '64bit5') {
                   7608: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7609: 	} elsif ($which eq '64bit4') {
1.575     albertel 7610: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7611: 	} else {
                   7612: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7613: 	}
1.675     albertel 7614:     } elsif ($which eq '64bit5') {
                   7615: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7616:     } elsif ($which eq '64bit4') {
                   7617: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7618:     } elsif ($which eq '64bit3') {
                   7619: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7620:     } elsif ($which eq '64bit2') {
                   7621: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7622:     } elsif ($which eq '64bit') {
                   7623: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7624:     }
                   7625:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7626: }
                   7627: 
                   7628: sub rndseed_32bit {
                   7629:     my ($symb,$courseid,$domain,$username)=@_;
                   7630:     {
                   7631: 	use integer;
                   7632: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7633: 	my $symbseed=numval($symb) << 22;
                   7634: 	my $namechck=unpack("%32C*",$username) << 17;
                   7635: 	my $nameseed=numval($username) << 12;
                   7636: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7637: 	my $courseseed=unpack("%32C*",$courseid);
                   7638: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7639: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7640: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7641: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7642: 	return $num;
                   7643:     }
                   7644: }
                   7645: 
                   7646: sub rndseed_64bit {
                   7647:     my ($symb,$courseid,$domain,$username)=@_;
                   7648:     {
                   7649: 	use integer;
                   7650: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7651: 	my $symbseed=numval($symb) << 10;
                   7652: 	my $namechck=unpack("%32S*",$username);
                   7653: 	
                   7654: 	my $nameseed=numval($username) << 21;
                   7655: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7656: 	my $courseseed=unpack("%32S*",$courseid);
                   7657: 	
                   7658: 	my $num1=$symbchck+$symbseed+$namechck;
                   7659: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7660: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7661: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7662: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7663: 	return "$num1,$num2";
1.155     albertel 7664:     }
1.366     albertel 7665: }
                   7666: 
1.443     albertel 7667: sub rndseed_64bit2 {
                   7668:     my ($symb,$courseid,$domain,$username)=@_;
                   7669:     {
                   7670: 	use integer;
                   7671: 	# strings need to be an even # of cahracters long, it it is odd the
                   7672:         # last characters gets thrown away
                   7673: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7674: 	my $symbseed=numval($symb) << 10;
                   7675: 	my $namechck=unpack("%32S*",$username.' ');
                   7676: 	
                   7677: 	my $nameseed=numval($username) << 21;
1.501     albertel 7678: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7679: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7680: 	
                   7681: 	my $num1=$symbchck+$symbseed+$namechck;
                   7682: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7683: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7684: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7685: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7686: 	return "$num1,$num2";
                   7687:     }
                   7688: }
                   7689: 
                   7690: sub rndseed_64bit3 {
                   7691:     my ($symb,$courseid,$domain,$username)=@_;
                   7692:     {
                   7693: 	use integer;
                   7694: 	# strings need to be an even # of cahracters long, it it is odd the
                   7695:         # last characters gets thrown away
                   7696: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7697: 	my $symbseed=numval2($symb) << 10;
                   7698: 	my $namechck=unpack("%32S*",$username.' ');
                   7699: 	
                   7700: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7701: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7702: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7703: 	
                   7704: 	my $num1=$symbchck+$symbseed+$namechck;
                   7705: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7706: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7707: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7708: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7709: 	
1.503     albertel 7710: 	return "$num1:$num2";
1.443     albertel 7711:     }
                   7712: }
                   7713: 
1.575     albertel 7714: sub rndseed_64bit4 {
                   7715:     my ($symb,$courseid,$domain,$username)=@_;
                   7716:     {
                   7717: 	use integer;
                   7718: 	# strings need to be an even # of cahracters long, it it is odd the
                   7719:         # last characters gets thrown away
                   7720: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7721: 	my $symbseed=numval3($symb) << 10;
                   7722: 	my $namechck=unpack("%32S*",$username.' ');
                   7723: 	
                   7724: 	my $nameseed=numval3($username) << 21;
                   7725: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7726: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7727: 	
                   7728: 	my $num1=$symbchck+$symbseed+$namechck;
                   7729: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7730: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7731: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7732: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7733: 	
                   7734: 	return "$num1:$num2";
                   7735:     }
                   7736: }
                   7737: 
1.675     albertel 7738: sub rndseed_64bit5 {
                   7739:     my ($symb,$courseid,$domain,$username)=@_;
                   7740:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7741:     return "$num1:$num2";
                   7742: }
                   7743: 
1.366     albertel 7744: sub rndseed_CODE_64bit {
                   7745:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7746:     {
1.366     albertel 7747: 	use integer;
1.443     albertel 7748: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7749: 	my $symbseed=numval2($symb);
1.491     albertel 7750: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7751: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7752: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7753: 	my $num1=$symbseed+$CODEchck;
                   7754: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7755: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7756: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7757: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7758: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7759: 	return "$num1:$num2";
1.366     albertel 7760:     }
                   7761: }
                   7762: 
1.575     albertel 7763: sub rndseed_CODE_64bit4 {
                   7764:     my ($symb,$courseid,$domain,$username)=@_;
                   7765:     {
                   7766: 	use integer;
                   7767: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7768: 	my $symbseed=numval3($symb);
                   7769: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7770: 	my $CODEseed=numval3(&getCODE());
                   7771: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7772: 	my $num1=$symbseed+$CODEchck;
                   7773: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7774: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7775: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7776: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7777: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7778: 	return "$num1:$num2";
                   7779:     }
                   7780: }
                   7781: 
1.675     albertel 7782: sub rndseed_CODE_64bit5 {
                   7783:     my ($symb,$courseid,$domain,$username)=@_;
                   7784:     my $code = &getCODE();
                   7785:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7786:     return "$num1:$num2";
                   7787: }
                   7788: 
1.366     albertel 7789: sub setup_random_from_rndseed {
                   7790:     my ($rndseed)=@_;
1.503     albertel 7791:     if ($rndseed =~/([,:])/) {
                   7792: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7793: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7794:     } else {
                   7795: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7796:     }
1.36      albertel 7797: }
                   7798: 
1.474     albertel 7799: sub latest_receipt_algorithm_id {
1.835     albertel 7800:     return 'receipt3';
1.474     albertel 7801: }
                   7802: 
1.480     www      7803: sub recunique {
                   7804:     my $fucourseid=shift;
                   7805:     my $unique;
1.835     albertel 7806:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7807: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7808: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7809:     } else {
                   7810: 	$unique=$perlvar{'lonReceipt'};
                   7811:     }
                   7812:     return unpack("%32C*",$unique);
                   7813: }
                   7814: 
                   7815: sub recprefix {
                   7816:     my $fucourseid=shift;
                   7817:     my $prefix;
1.835     albertel 7818:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7819: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7820: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7821:     } else {
                   7822: 	$prefix=$perlvar{'lonHostID'};
                   7823:     }
                   7824:     return unpack("%32C*",$prefix);
                   7825: }
                   7826: 
1.76      www      7827: sub ireceipt {
1.474     albertel 7828:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7829: 
                   7830:     my $return =&recprefix($fucourseid).'-';
                   7831: 
                   7832:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7833: 	$env{'request.state'} eq 'construct') {
                   7834: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7835: 	return $return;
                   7836:     }
                   7837: 
1.76      www      7838:     my $cuname=unpack("%32C*",$funame);
                   7839:     my $cudom=unpack("%32C*",$fudom);
                   7840:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7841:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7842:     my $cunique=&recunique($fucourseid);
1.474     albertel 7843:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7844:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7845: 
1.790     albertel 7846: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7847: 			       
                   7848: 	$return.= ($cunique%$cuname+
                   7849: 		   $cunique%$cudom+
                   7850: 		   $cusymb%$cuname+
                   7851: 		   $cusymb%$cudom+
                   7852: 		   $cucourseid%$cuname+
                   7853: 		   $cucourseid%$cudom+
                   7854: 		   $cpart%$cuname+
                   7855: 		   $cpart%$cudom);
                   7856:     } else {
                   7857: 	$return.= ($cunique%$cuname+
                   7858: 		   $cunique%$cudom+
                   7859: 		   $cusymb%$cuname+
                   7860: 		   $cusymb%$cudom+
                   7861: 		   $cucourseid%$cuname+
                   7862: 		   $cucourseid%$cudom);
                   7863:     }
                   7864:     return $return;
1.76      www      7865: }
                   7866: 
                   7867: sub receipt {
1.474     albertel 7868:     my ($part)=@_;
1.790     albertel 7869:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7870:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7871: }
1.260     ng       7872: 
1.790     albertel 7873: sub whichuser {
                   7874:     my ($passedsymb)=@_;
                   7875:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7876:     if (defined($env{'form.grade_symb'})) {
                   7877: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7878: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7879: 	if (!$allowed &&
                   7880: 	    exists($env{'request.course.sec'}) &&
                   7881: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7882: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7883: 			      '/'.$env{'request.course.sec'});
                   7884: 	}
                   7885: 	if ($allowed) {
                   7886: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7887: 	    $courseid=$tmp_courseid;
                   7888: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7889: 	    ($name)=&get_env_multiple('form.grade_username');
                   7890: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7891: 	}
                   7892:     }
                   7893:     if (!$passedsymb) {
                   7894: 	$symb=&symbread();
                   7895:     } else {
                   7896: 	$symb=$passedsymb;
                   7897:     }
                   7898:     $courseid=$env{'request.course.id'};
                   7899:     $domain=$env{'user.domain'};
                   7900:     $name=$env{'user.name'};
                   7901:     if ($name eq 'public' && $domain eq 'public') {
                   7902: 	if (!defined($env{'form.username'})) {
                   7903: 	    $env{'form.username'}.=time.rand(10000000);
                   7904: 	}
                   7905: 	$name.=$env{'form.username'};
                   7906:     }
                   7907:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7908: 
                   7909: }
                   7910: 
1.36      albertel 7911: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7912: # returns either the contents of the file or 
                   7913: # -1 if the file doesn't exist
1.481     raeburn  7914: #
                   7915: # if the target is a file that was uploaded via DOCS, 
                   7916: # a check will be made to see if a current copy exists on the local server,
                   7917: # if it does this will be served, otherwise a copy will be retrieved from
                   7918: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7919: # the local server.   
1.472     albertel 7920: 
1.36      albertel 7921: sub getfile {
1.538     albertel 7922:     my ($file) = @_;
1.609     banghart 7923:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7924:     &repcopy($file);
                   7925:     return &readfile($file);
                   7926: }
                   7927: 
                   7928: sub repcopy_userfile {
                   7929:     my ($file)=@_;
1.609     banghart 7930:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7931:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7932:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7933: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7934:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7935:     if (-e "$file") {
1.828     www      7936: # we already have a local copy, check it out
1.538     albertel 7937: 	my @fileinfo = stat($file);
1.828     www      7938: 	my $rtncode;
                   7939: 	my $info;
1.538     albertel 7940: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7941: 	if ($lwpresp ne 'ok') {
1.828     www      7942: # there is no such file anymore, even though we had a local copy
1.482     albertel 7943: 	    if ($rtncode eq '404') {
1.538     albertel 7944: 		unlink($file);
1.482     albertel 7945: 	    }
                   7946: 	    return -1;
                   7947: 	}
                   7948: 	if ($info < $fileinfo[9]) {
1.828     www      7949: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7950: 	    return 'ok';
1.828     www      7951: 	} else {
                   7952: # the file is outdated, get rid of it
                   7953: 	    unlink($file);
1.482     albertel 7954: 	}
1.828     www      7955:     }
                   7956: # one way or the other, at this point, we don't have the file
                   7957: # construct the correct path for the file
                   7958:     my @parts = ($cdom,$cnum); 
                   7959:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7960: 	push @parts, split(/\//,$1);
                   7961:     }
                   7962:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7963:     foreach my $part (@parts) {
                   7964: 	$path .= '/'.$part;
                   7965: 	if (!-e $path) {
                   7966: 	    mkdir($path,0770);
1.482     albertel 7967: 	}
                   7968:     }
1.828     www      7969: # now the path exists for sure
                   7970: # get a user agent
                   7971:     my $ua=new LWP::UserAgent;
                   7972:     my $transferfile=$file.'.in.transfer';
                   7973: # FIXME: this should flock
                   7974:     if (-e $transferfile) { return 'ok'; }
                   7975:     my $request;
                   7976:     $uri=~s/^\///;
1.838     albertel 7977:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7978:     my $response=$ua->request($request,$transferfile);
                   7979: # did it work?
                   7980:     if ($response->is_error()) {
                   7981: 	unlink($transferfile);
                   7982: 	&logthis("Userfile repcopy failed for $uri");
                   7983: 	return -1;
                   7984:     }
                   7985: # worked, rename the transfer file
                   7986:     rename($transferfile,$file);
1.607     raeburn  7987:     return 'ok';
1.481     raeburn  7988: }
                   7989: 
1.517     albertel 7990: sub tokenwrapper {
                   7991:     my $uri=shift;
1.552     albertel 7992:     $uri=~s|^http\://([^/]+)||;
                   7993:     $uri=~s|^/||;
1.620     albertel 7994:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7995:     my $token=$1;
1.552     albertel 7996:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7997:     if ($udom && $uname && $file) {
                   7998: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7999:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 8000:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8001:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8002:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8003:     } else {
                   8004:         return '/adm/notfound.html';
                   8005:     }
                   8006: }
                   8007: 
1.828     www      8008: # call with reqtype HEAD: get last modification time
                   8009: # call with reqtype GET: get the file contents
                   8010: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8011: #
1.481     raeburn  8012: sub getuploaded {
                   8013:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8014:     $uri=~s/^\///;
1.838     albertel 8015:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8016:     my $ua=new LWP::UserAgent;
                   8017:     my $request=new HTTP::Request($reqtype,$uri);
                   8018:     my $response=$ua->request($request);
                   8019:     $$rtncode = $response->code;
1.482     albertel 8020:     if (! $response->is_success()) {
                   8021: 	return 'failed';
                   8022:     }      
                   8023:     if ($reqtype eq 'HEAD') {
1.486     www      8024: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8025:     } elsif ($reqtype eq 'GET') {
                   8026: 	$$info = $response->content;
1.472     albertel 8027:     }
1.482     albertel 8028:     return 'ok';
1.36      albertel 8029: }
                   8030: 
1.481     raeburn  8031: sub readfile {
                   8032:     my $file = shift;
                   8033:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8034:     my $fh;
                   8035:     open($fh,"<$file");
                   8036:     my $a='';
1.800     albertel 8037:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8038:     return $a;
                   8039: }
                   8040: 
1.36      albertel 8041: sub filelocation {
1.590     banghart 8042:     my ($dir,$file) = @_;
                   8043:     my $location;
                   8044:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8045: 
                   8046:     if ($file =~ m-^/adm/-) {
                   8047: 	$file=~s-^/adm/wrapper/-/-;
                   8048: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8049:     }
1.882     albertel 8050: 
1.590     banghart 8051:     if ($file=~m:^/~:) { # is a contruction space reference
                   8052:         $location = $file;
                   8053:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8054:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8055: 	# is a correct contruction space reference
                   8056:         $location = $file;
1.609     banghart 8057:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8058:         my ($udom,$uname,$filename)=
1.811     albertel 8059:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8060:         my $home=&homeserver($uname,$udom);
                   8061:         my $is_me=0;
                   8062:         my @ids=&current_machine_ids();
                   8063:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8064:         if ($is_me) {
1.740     www      8065:   	    $location=&propath($udom,$uname).
1.590     banghart 8066:   	      '/userfiles/'.$filename;
                   8067:         } else {
                   8068:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8069:   	      $udom.'/'.$uname.'/'.$filename;
                   8070:         }
1.882     albertel 8071:     } elsif ($file =~ m-^/adm/-) {
                   8072: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8073:     } else {
                   8074:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8075:         $file=~s:^/res/:/:;
                   8076:         if ( !( $file =~ m:^/:) ) {
                   8077:             $location = $dir. '/'.$file;
                   8078:         } else {
                   8079:             $location = '/home/httpd/html/res'.$file;
                   8080:         }
1.59      albertel 8081:     }
1.590     banghart 8082:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8083:     while ($location=~m{/\.\./}) {
                   8084: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8085: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8086: 	} else {
                   8087: 	    $location=~ s{/\.\./}{/}g;
                   8088: 	}
                   8089:     } #remove dir/..
1.590     banghart 8090:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8091:     return $location;
1.46      www      8092: }
1.36      albertel 8093: 
1.46      www      8094: sub hreflocation {
                   8095:     my ($dir,$file)=@_;
1.460     albertel 8096:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8097: 	$file=filelocation($dir,$file);
1.700     albertel 8098:     } elsif ($file=~m-^/adm/-) {
                   8099: 	$file=~s-^/adm/wrapper/-/-;
                   8100: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8101:     }
                   8102:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8103: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8104:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8105: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8106:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8107: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8108: 	    -/uploaded/$1/$2/-x;
1.46      www      8109:     }
1.913     albertel 8110:     if ($file=~ m{^/userfiles/}) {
                   8111: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8112:     }
1.462     albertel 8113:     return $file;
1.465     albertel 8114: }
                   8115: 
                   8116: sub current_machine_domains {
1.853     albertel 8117:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8118: }
                   8119: 
                   8120: sub machine_domains {
                   8121:     my ($hostname) = @_;
1.465     albertel 8122:     my @domains;
1.838     albertel 8123:     my %hostname = &all_hostnames();
1.465     albertel 8124:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8125: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8126: 	if ($hostname eq $name) {
1.844     albertel 8127: 	    push(@domains,&host_domain($id));
1.465     albertel 8128: 	}
                   8129:     }
                   8130:     return @domains;
                   8131: }
                   8132: 
                   8133: sub current_machine_ids {
1.853     albertel 8134:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8135: }
                   8136: 
                   8137: sub machine_ids {
                   8138:     my ($hostname) = @_;
                   8139:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8140:     my @ids;
1.888     albertel 8141:     my %name_to_host = &all_names();
1.889     albertel 8142:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8143: 	return @{ $name_to_host{$hostname} };
                   8144:     }
                   8145:     return;
1.31      www      8146: }
                   8147: 
1.824     raeburn  8148: sub additional_machine_domains {
                   8149:     my @domains;
                   8150:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8151:     while( my $line = <$fh>) {
                   8152:         $line =~ s/\s//g;
                   8153:         push(@domains,$line);
                   8154:     }
                   8155:     return @domains;
                   8156: }
                   8157: 
                   8158: sub default_login_domain {
                   8159:     my $domain = $perlvar{'lonDefDomain'};
                   8160:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8161:     foreach my $posdom (&current_machine_domains(),
                   8162:                         &additional_machine_domains()) {
                   8163:         if (lc($posdom) eq lc($testdomain)) {
                   8164:             $domain=$posdom;
                   8165:             last;
                   8166:         }
                   8167:     }
                   8168:     return $domain;
                   8169: }
                   8170: 
1.31      www      8171: # ------------------------------------------------------------- Declutters URLs
                   8172: 
                   8173: sub declutter {
                   8174:     my $thisfn=shift;
1.569     albertel 8175:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8176:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8177:     $thisfn=~s/^\///;
1.697     albertel 8178:     $thisfn=~s|^adm/wrapper/||;
                   8179:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8180:     $thisfn=~s/^res\///;
1.235     www      8181:     $thisfn=~s/\?.+$//;
1.268     www      8182:     return $thisfn;
                   8183: }
                   8184: 
                   8185: # ------------------------------------------------------------- Clutter up URLs
                   8186: 
                   8187: sub clutter {
                   8188:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8189:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8190: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8191:        $thisfn='/res'.$thisfn; 
                   8192:     }
1.694     albertel 8193:     if ($thisfn !~m|/adm|) {
1.695     albertel 8194: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8195: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8196: 	} else {
                   8197: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8198: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8199: 	    if ($embstyle eq 'ssi'
                   8200: 		|| ($embstyle eq 'hdn')
                   8201: 		|| ($embstyle eq 'rat')
                   8202: 		|| ($embstyle eq 'prv')
                   8203: 		|| ($embstyle eq 'ign')) {
                   8204: 		#do nothing with these
                   8205: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8206: 		|| ($embstyle eq 'emb')
                   8207: 		|| ($embstyle eq 'wrp')) {
                   8208: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8209: 	    } elsif ($embstyle eq 'unk'
                   8210: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8211: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8212: 	    } else {
1.718     www      8213: #		&logthis("Got a blank emb style");
1.695     albertel 8214: 	    }
1.694     albertel 8215: 	}
                   8216:     }
1.31      www      8217:     return $thisfn;
1.12      www      8218: }
                   8219: 
1.787     albertel 8220: sub clutter_with_no_wrapper {
                   8221:     my $uri = &clutter(shift);
                   8222:     if ($uri =~ m-^/adm/-) {
                   8223: 	$uri =~ s-^/adm/wrapper/-/-;
                   8224: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8225:     }
                   8226:     return $uri;
                   8227: }
                   8228: 
1.557     albertel 8229: sub freeze_escape {
                   8230:     my ($value)=@_;
                   8231:     if (ref($value)) {
                   8232: 	$value=&nfreeze($value);
                   8233: 	return '__FROZEN__'.&escape($value);
                   8234:     }
                   8235:     return &escape($value);
                   8236: }
                   8237: 
1.11      www      8238: 
1.557     albertel 8239: sub thaw_unescape {
                   8240:     my ($value)=@_;
                   8241:     if ($value =~ /^__FROZEN__/) {
                   8242: 	substr($value,0,10,undef);
                   8243: 	$value=&unescape($value);
                   8244: 	return &thaw($value);
                   8245:     }
                   8246:     return &unescape($value);
                   8247: }
                   8248: 
1.436     albertel 8249: sub correct_line_ends {
                   8250:     my ($result)=@_;
                   8251:     $$result =~s/\r\n/\n/mg;
                   8252:     $$result =~s/\r/\n/mg;
1.415     albertel 8253: }
1.1       albertel 8254: # ================================================================ Main Program
                   8255: 
1.184     www      8256: sub goodbye {
1.204     albertel 8257:    &logthis("Starting Shut down");
1.443     albertel 8258: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8259:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8260: #converted
1.599     albertel 8261: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8262:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8263: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8264: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8265: #1.1 only
1.870     albertel 8266: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8267: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8268: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8269: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8270:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8271:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8272:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8273:    &flushcourselogs();
                   8274:    &logthis("Shutting down");
                   8275: }
                   8276: 
1.852     albertel 8277: sub get_dns {
1.869     albertel 8278:     my ($url,$func,$ignore_cache) = @_;
                   8279:     if (!$ignore_cache) {
                   8280: 	my ($content,$cached)=
                   8281: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8282: 	if ($cached) {
                   8283: 	    &$func($content);
                   8284: 	    return;
                   8285: 	}
                   8286:     }
                   8287: 
                   8288:     my %alldns;
1.852     albertel 8289:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8290:     foreach my $dns (<$config>) {
                   8291: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8292: 	$alldns{$1} = 1;
                   8293:     }
                   8294:     while (%alldns) {
                   8295: 	my ($dns) = keys(%alldns);
                   8296: 	delete($alldns{$dns});
1.852     albertel 8297: 	my $ua=new LWP::UserAgent;
                   8298: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8299: 	my $response=$ua->request($request);
                   8300: 	next if ($response->is_error());
                   8301: 	my @content = split("\n",$response->content);
1.869     albertel 8302: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8303: 	&$func(\@content);
1.869     albertel 8304: 	return;
1.852     albertel 8305:     }
                   8306:     close($config);
1.871     albertel 8307:     my $which = (split('/',$url))[3];
                   8308:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8309:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8310:     my @content = <$config>;
                   8311:     &$func(\@content);
                   8312:     return;
1.852     albertel 8313: }
1.327     albertel 8314: # ------------------------------------------------------------ Read domain file
                   8315: {
1.852     albertel 8316:     my $loaded;
1.846     albertel 8317:     my %domain;
                   8318: 
1.852     albertel 8319:     sub parse_domain_tab {
                   8320: 	my ($lines) = @_;
                   8321: 	foreach my $line (@$lines) {
                   8322: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8323: 
1.846     albertel 8324: 	    chomp($line);
1.852     albertel 8325: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8326: 	    my %this_domain;
                   8327: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8328: 			       'lang_def', 'city', 'longi', 'lati',
                   8329: 			       'primary') {
                   8330: 		$this_domain{$field} = shift(@elements);
                   8331: 	    }
                   8332: 	    $domain{$name} = \%this_domain;
1.852     albertel 8333: 	}
                   8334:     }
1.864     albertel 8335: 
                   8336:     sub reset_domain_info {
                   8337: 	undef($loaded);
                   8338: 	undef(%domain);
                   8339:     }
                   8340: 
1.852     albertel 8341:     sub load_domain_tab {
1.869     albertel 8342: 	my ($ignore_cache) = @_;
                   8343: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8344: 	my $fh;
                   8345: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8346: 	    my @lines = <$fh>;
                   8347: 	    &parse_domain_tab(\@lines);
1.448     albertel 8348: 	}
1.852     albertel 8349: 	close($fh);
                   8350: 	$loaded = 1;
1.327     albertel 8351:     }
1.846     albertel 8352: 
                   8353:     sub domain {
1.852     albertel 8354: 	&load_domain_tab() if (!$loaded);
                   8355: 
1.846     albertel 8356: 	my ($name,$what) = @_;
                   8357: 	return if ( !exists($domain{$name}) );
                   8358: 
                   8359: 	if (!$what) {
                   8360: 	    return $domain{$name}{'description'};
                   8361: 	}
                   8362: 	return $domain{$name}{$what};
                   8363:     }
1.327     albertel 8364: }
                   8365: 
                   8366: 
1.1       albertel 8367: # ------------------------------------------------------------- Read hosts file
                   8368: {
1.838     albertel 8369:     my %hostname;
1.844     albertel 8370:     my %hostdom;
1.845     albertel 8371:     my %libserv;
1.852     albertel 8372:     my $loaded;
1.888     albertel 8373:     my %name_to_host;
1.852     albertel 8374: 
                   8375:     sub parse_hosts_tab {
                   8376: 	my ($file) = @_;
                   8377: 	foreach my $configline (@$file) {
                   8378: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8379: 	    next if ($configline =~ /^\^/);
                   8380: 	    chomp($configline);
                   8381: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8382: 	    $name=~s/\s//g;
                   8383: 	    if ($id && $domain && $role && $name) {
                   8384: 		$hostname{$id}=$name;
1.888     albertel 8385: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8386: 		$hostdom{$id}=$domain;
                   8387: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8388: 	    }
                   8389: 	}
                   8390:     }
1.864     albertel 8391:     
                   8392:     sub reset_hosts_info {
1.897     albertel 8393: 	&purge_remembered();
1.864     albertel 8394: 	&reset_domain_info();
                   8395: 	&reset_hosts_ip_info();
1.892     albertel 8396: 	undef(%name_to_host);
1.864     albertel 8397: 	undef(%hostname);
                   8398: 	undef(%hostdom);
                   8399: 	undef(%libserv);
                   8400: 	undef($loaded);
                   8401:     }
1.1       albertel 8402: 
1.852     albertel 8403:     sub load_hosts_tab {
1.869     albertel 8404: 	my ($ignore_cache) = @_;
                   8405: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8406: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8407: 	my @config = <$config>;
                   8408: 	&parse_hosts_tab(\@config);
                   8409: 	close($config);
                   8410: 	$loaded=1;
1.1       albertel 8411:     }
1.852     albertel 8412: 
1.838     albertel 8413:     sub hostname {
1.852     albertel 8414: 	&load_hosts_tab() if (!$loaded);
                   8415: 
1.838     albertel 8416: 	my ($lonid) = @_;
                   8417: 	return $hostname{$lonid};
                   8418:     }
1.845     albertel 8419: 
1.838     albertel 8420:     sub all_hostnames {
1.852     albertel 8421: 	&load_hosts_tab() if (!$loaded);
                   8422: 
1.838     albertel 8423: 	return %hostname;
                   8424:     }
1.845     albertel 8425: 
1.888     albertel 8426:     sub all_names {
                   8427: 	&load_hosts_tab() if (!$loaded);
                   8428: 
                   8429: 	return %name_to_host;
                   8430:     }
                   8431: 
1.845     albertel 8432:     sub is_library {
1.852     albertel 8433: 	&load_hosts_tab() if (!$loaded);
                   8434: 
1.845     albertel 8435: 	return exists($libserv{$_[0]});
                   8436:     }
                   8437: 
                   8438:     sub all_library {
1.852     albertel 8439: 	&load_hosts_tab() if (!$loaded);
                   8440: 
1.845     albertel 8441: 	return %libserv;
                   8442:     }
                   8443: 
1.841     albertel 8444:     sub get_servers {
1.852     albertel 8445: 	&load_hosts_tab() if (!$loaded);
                   8446: 
1.841     albertel 8447: 	my ($domain,$type) = @_;
                   8448: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8449: 	                                          : %hostname;
                   8450: 	my %result;
1.842     albertel 8451: 	if (ref($domain) eq 'ARRAY') {
                   8452: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8453: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8454: 		    $result{$host} = $hostname;
                   8455: 		}
                   8456: 	    }
                   8457: 	} else {
                   8458: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8459: 		if ($hostdom{$host} eq $domain) {
                   8460: 		    $result{$host} = $hostname;
                   8461: 		}
1.841     albertel 8462: 	    }
                   8463: 	}
                   8464: 	return %result;
                   8465:     }
1.845     albertel 8466: 
1.844     albertel 8467:     sub host_domain {
1.852     albertel 8468: 	&load_hosts_tab() if (!$loaded);
                   8469: 
1.844     albertel 8470: 	my ($lonid) = @_;
                   8471: 	return $hostdom{$lonid};
                   8472:     }
                   8473: 
1.841     albertel 8474:     sub all_domains {
1.852     albertel 8475: 	&load_hosts_tab() if (!$loaded);
                   8476: 
1.841     albertel 8477: 	my %seen;
                   8478: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8479: 	return @uniq;
                   8480:     }
1.1       albertel 8481: }
                   8482: 
1.847     albertel 8483: { 
                   8484:     my %iphost;
1.856     albertel 8485:     my %name_to_ip;
                   8486:     my %lonid_to_ip;
1.869     albertel 8487: 
1.847     albertel 8488:     sub get_hosts_from_ip {
                   8489: 	my ($ip) = @_;
                   8490: 	my %iphosts = &get_iphost();
                   8491: 	if (ref($iphosts{$ip})) {
                   8492: 	    return @{$iphosts{$ip}};
                   8493: 	}
                   8494: 	return;
1.839     albertel 8495:     }
1.864     albertel 8496:     
                   8497:     sub reset_hosts_ip_info {
                   8498: 	undef(%iphost);
                   8499: 	undef(%name_to_ip);
                   8500: 	undef(%lonid_to_ip);
                   8501:     }
1.856     albertel 8502: 
                   8503:     sub get_host_ip {
                   8504: 	my ($lonid) = @_;
                   8505: 	if (exists($lonid_to_ip{$lonid})) {
                   8506: 	    return $lonid_to_ip{$lonid};
                   8507: 	}
                   8508: 	my $name=&hostname($lonid);
                   8509:    	my $ip = gethostbyname($name);
                   8510: 	return if (!$ip || length($ip) ne 4);
                   8511: 	$ip=inet_ntoa($ip);
                   8512: 	$name_to_ip{$name}   = $ip;
                   8513: 	$lonid_to_ip{$lonid} = $ip;
                   8514: 	return $ip;
                   8515:     }
1.847     albertel 8516:     
                   8517:     sub get_iphost {
1.869     albertel 8518: 	my ($ignore_cache) = @_;
1.894     albertel 8519: 
1.869     albertel 8520: 	if (!$ignore_cache) {
                   8521: 	    if (%iphost) {
                   8522: 		return %iphost;
                   8523: 	    }
                   8524: 	    my ($ip_info,$cached)=
                   8525: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8526: 	    if ($cached) {
                   8527: 		%iphost      = %{$ip_info->[0]};
                   8528: 		%name_to_ip  = %{$ip_info->[1]};
                   8529: 		%lonid_to_ip = %{$ip_info->[2]};
                   8530: 		return %iphost;
                   8531: 	    }
                   8532: 	}
1.894     albertel 8533: 
                   8534: 	# get yesterday's info for fallback
                   8535: 	my %old_name_to_ip;
                   8536: 	my ($ip_info,$cached)=
                   8537: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8538: 	if ($cached) {
                   8539: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8540: 	}
                   8541: 
1.888     albertel 8542: 	my %name_to_host = &all_names();
                   8543: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8544: 	    my $ip;
                   8545: 	    if (!exists($name_to_ip{$name})) {
                   8546: 		$ip = gethostbyname($name);
                   8547: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8548: 		    if (defined($old_name_to_ip{$name})) {
                   8549: 			$ip = $old_name_to_ip{$name};
                   8550: 			&logthis("Can't find $name defaulting to old $ip");
                   8551: 		    } else {
                   8552: 			&logthis("Name $name no IP found");
                   8553: 			next;
                   8554: 		    }
                   8555: 		} else {
                   8556: 		    $ip=inet_ntoa($ip);
1.847     albertel 8557: 		}
                   8558: 		$name_to_ip{$name} = $ip;
                   8559: 	    } else {
                   8560: 		$ip = $name_to_ip{$name};
1.653     albertel 8561: 	    }
1.888     albertel 8562: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8563: 		$lonid_to_ip{$id} = $ip;
                   8564: 	    }
                   8565: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8566: 	}
1.869     albertel 8567: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8568: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8569: 				      48*60*60);
1.869     albertel 8570: 
1.847     albertel 8571: 	return %iphost;
1.598     albertel 8572:     }
                   8573: }
                   8574: 
1.862     albertel 8575: BEGIN {
                   8576: 
                   8577: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8578:     unless ($readit) {
                   8579: {
                   8580:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8581:     %perlvar = (%perlvar,%{$configvars});
                   8582: }
                   8583: 
                   8584: 
1.1       albertel 8585: # ------------------------------------------------------ Read spare server file
                   8586: {
1.448     albertel 8587:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8588: 
                   8589:     while (my $configline=<$config>) {
                   8590:        chomp($configline);
1.284     matthew  8591:        if ($configline) {
1.784     albertel 8592: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8593: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8594: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8595:        }
                   8596:     }
1.448     albertel 8597:     close($config);
1.1       albertel 8598: }
1.11      www      8599: # ------------------------------------------------------------ Read permissions
                   8600: {
1.448     albertel 8601:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8602: 
                   8603:     while (my $configline=<$config>) {
1.448     albertel 8604: 	chomp($configline);
                   8605: 	if ($configline) {
                   8606: 	    my ($role,$perm)=split(/ /,$configline);
                   8607: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8608: 	}
1.11      www      8609:     }
1.448     albertel 8610:     close($config);
1.11      www      8611: }
                   8612: 
                   8613: # -------------------------------------------- Read plain texts for permissions
                   8614: {
1.448     albertel 8615:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8616: 
                   8617:     while (my $configline=<$config>) {
1.448     albertel 8618: 	chomp($configline);
                   8619: 	if ($configline) {
1.742     raeburn  8620: 	    my ($short,@plain)=split(/:/,$configline);
                   8621:             %{$prp{$short}} = ();
                   8622: 	    if (@plain > 0) {
                   8623:                 $prp{$short}{'std'} = $plain[0];
                   8624:                 for (my $i=1; $i<@plain; $i++) {
                   8625:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8626:                 }
                   8627:             }
1.448     albertel 8628: 	}
1.135     www      8629:     }
1.448     albertel 8630:     close($config);
1.135     www      8631: }
                   8632: 
                   8633: # ---------------------------------------------------------- Read package table
                   8634: {
1.448     albertel 8635:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8636: 
                   8637:     while (my $configline=<$config>) {
1.483     albertel 8638: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8639: 	chomp($configline);
                   8640: 	my ($short,$plain)=split(/:/,$configline);
                   8641: 	my ($pack,$name)=split(/\&/,$short);
                   8642: 	if ($plain ne '') {
                   8643: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8644: 	    $packagetab{$short}=$plain; 
                   8645: 	}
1.11      www      8646:     }
1.448     albertel 8647:     close($config);
1.329     matthew  8648: }
                   8649: 
                   8650: # ------------- set up temporary directory
                   8651: {
                   8652:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8653: 
1.11      www      8654: }
                   8655: 
1.794     albertel 8656: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8657: 				'compress_threshold'=> 20_000,
                   8658:  			        });
1.185     www      8659: 
1.281     www      8660: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8661: $dumpcount=0;
1.22      www      8662: 
1.163     harris41 8663: &logtouch();
1.672     albertel 8664: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8665: $readit=1;
1.564     albertel 8666:     {
                   8667: 	use integer;
                   8668: 	my $test=(2**32)+1;
1.568     albertel 8669: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8670: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8671:     }
1.195     www      8672: }
1.1       albertel 8673: }
1.179     www      8674: 
1.1       albertel 8675: 1;
1.191     harris41 8676: __END__
                   8677: 
1.243     albertel 8678: =pod
                   8679: 
1.191     harris41 8680: =head1 NAME
                   8681: 
1.243     albertel 8682: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8683: 
                   8684: =head1 SYNOPSIS
                   8685: 
1.243     albertel 8686: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8687: 
                   8688:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8689: 
1.243     albertel 8690: Common parameters:
                   8691: 
                   8692: =over 4
                   8693: 
                   8694: =item *
                   8695: 
                   8696: $uname : an internal username (if $cname expecting a course Id specifically)
                   8697: 
                   8698: =item *
                   8699: 
                   8700: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8701: 
                   8702: =item *
                   8703: 
                   8704: $symb : a resource instance identifier
                   8705: 
                   8706: =item *
                   8707: 
                   8708: $namespace : the name of a .db file that contains the data needed or
                   8709: being set.
                   8710: 
                   8711: =back
                   8712: 
1.394     bowersj2 8713: =head1 OVERVIEW
1.191     harris41 8714: 
1.394     bowersj2 8715: lonnet provides subroutines which interact with the
                   8716: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8717: about classes, users, and resources.
1.243     albertel 8718: 
                   8719: For many of these objects you can also use this to store data about
                   8720: them or modify them in various ways.
1.191     harris41 8721: 
1.394     bowersj2 8722: =head2 Symbs
1.191     harris41 8723: 
1.394     bowersj2 8724: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8725: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8726: map, the resource number of the resource in the map, and the URL of
                   8727: the resource itself. The latter is somewhat redundant, but might help
                   8728: if maps change.
                   8729: 
                   8730: An example is
                   8731: 
                   8732:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8733: 
                   8734: The respective map entry is
                   8735: 
                   8736:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8737:   title="Problem 2">
                   8738:  </resource>
                   8739: 
                   8740: Symbs are used by the random number generator, as well as to store and
                   8741: restore data specific to a certain instance of for example a problem.
                   8742: 
                   8743: =head2 Storing And Retrieving Data
                   8744: 
                   8745: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8746: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8747: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8748: is is the non-critical message twin of cstore. These functions are for
                   8749: handlers to store a perl hash to a user's permanent data space in an
                   8750: easy manner, and to retrieve it again on another call. It is expected
                   8751: that a handler would use this once at the beginning to retrieve data,
                   8752: and then again once at the end to send only the new data back.
                   8753: 
                   8754: The data is stored in the user's data directory on the user's
                   8755: homeserver under the ID of the course.
                   8756: 
                   8757: The hash that is returned by restore will have all of the previous
                   8758: value for all of the elements of the hash.
                   8759: 
                   8760: Example:
                   8761: 
                   8762:  #creating a hash
                   8763:  my %hash;
                   8764:  $hash{'foo'}='bar';
                   8765: 
                   8766:  #storing it
                   8767:  &Apache::lonnet::cstore(\%hash);
                   8768: 
                   8769:  #changing a value
                   8770:  $hash{'foo'}='notbar';
                   8771: 
                   8772:  #adding a new value
                   8773:  $hash{'bar'}='foo';
                   8774:  &Apache::lonnet::cstore(\%hash);
                   8775: 
                   8776:  #retrieving the hash
                   8777:  my %history=&Apache::lonnet::restore();
                   8778: 
                   8779:  #print the hash
                   8780:  foreach my $key (sort(keys(%history))) {
                   8781:    print("\%history{$key} = $history{$key}");
                   8782:  }
                   8783: 
                   8784: Will print out:
1.191     harris41 8785: 
1.394     bowersj2 8786:  %history{1:foo} = bar
                   8787:  %history{1:keys} = foo:timestamp
                   8788:  %history{1:timestamp} = 990455579
                   8789:  %history{2:bar} = foo
                   8790:  %history{2:foo} = notbar
                   8791:  %history{2:keys} = foo:bar:timestamp
                   8792:  %history{2:timestamp} = 990455580
                   8793:  %history{bar} = foo
                   8794:  %history{foo} = notbar
                   8795:  %history{timestamp} = 990455580
                   8796:  %history{version} = 2
                   8797: 
                   8798: Note that the special hash entries C<keys>, C<version> and
                   8799: C<timestamp> were added to the hash. C<version> will be equal to the
                   8800: total number of versions of the data that have been stored. The
                   8801: C<timestamp> attribute will be the UNIX time the hash was
                   8802: stored. C<keys> is available in every historical section to list which
                   8803: keys were added or changed at a specific historical revision of a
                   8804: hash.
                   8805: 
                   8806: B<Warning>: do not store the hash that restore returns directly. This
                   8807: will cause a mess since it will restore the historical keys as if the
                   8808: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8809: 
1.394     bowersj2 8810: Calling convention:
1.191     harris41 8811: 
1.394     bowersj2 8812:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8813:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8814: 
1.394     bowersj2 8815: For more detailed information, see lonnet specific documentation.
1.191     harris41 8816: 
1.394     bowersj2 8817: =head1 RETURN MESSAGES
1.191     harris41 8818: 
1.394     bowersj2 8819: =over 4
1.191     harris41 8820: 
1.394     bowersj2 8821: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8822: 
1.394     bowersj2 8823: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8824: when the connection is brought back up
1.191     harris41 8825: 
1.394     bowersj2 8826: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8827: for later delivery
1.191     harris41 8828: 
1.394     bowersj2 8829: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8830: 
1.394     bowersj2 8831: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8832: that was requested
1.191     harris41 8833: 
1.243     albertel 8834: =back
1.191     harris41 8835: 
1.243     albertel 8836: =head1 PUBLIC SUBROUTINES
1.191     harris41 8837: 
1.243     albertel 8838: =head2 Session Environment Functions
1.191     harris41 8839: 
1.243     albertel 8840: =over 4
1.191     harris41 8841: 
1.394     bowersj2 8842: =item * 
                   8843: X<appenv()>
                   8844: B<appenv(%hash)>: the value of %hash is written to
                   8845: the user envirnoment file, and will be restored for each access this
1.620     albertel 8846: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8847: process
1.191     harris41 8848: 
                   8849: =item *
1.394     bowersj2 8850: X<delenv()>
                   8851: B<delenv($regexp)>: removes all items from the session
                   8852: environment file that matches the regular expression in $regexp. The
1.620     albertel 8853: values are also delted from the current processes %env.
1.191     harris41 8854: 
1.795     albertel 8855: =item * get_env_multiple($name) 
                   8856: 
                   8857: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8858: values may be defined and end up as an array ref.
                   8859: 
                   8860: returns an array of values
                   8861: 
1.243     albertel 8862: =back
                   8863: 
                   8864: =head2 User Information
1.191     harris41 8865: 
1.243     albertel 8866: =over 4
1.191     harris41 8867: 
                   8868: =item *
1.394     bowersj2 8869: X<queryauthenticate()>
                   8870: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8871: authentication scheme
                   8872: 
                   8873: =item *
1.394     bowersj2 8874: X<authenticate()>
                   8875: B<authenticate($uname,$upass,$udom)>: try to
                   8876: authenticate user from domain's lib servers (first use the current
                   8877: one). C<$upass> should be the users password.
1.191     harris41 8878: 
                   8879: =item *
1.394     bowersj2 8880: X<homeserver()>
                   8881: B<homeserver($uname,$udom)>: find the server which has
                   8882: the user's directory and files (there must be only one), this caches
                   8883: the answer, and also caches if there is a borken connection.
1.191     harris41 8884: 
                   8885: =item *
1.394     bowersj2 8886: X<idget()>
                   8887: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8888: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8889: username, and only 1 username per ID in a specific domain) (returns
                   8890: hash: id=>name,id=>name)
1.191     harris41 8891: 
                   8892: =item *
1.394     bowersj2 8893: X<idrget()>
                   8894: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8895: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8896: 
                   8897: =item *
1.394     bowersj2 8898: X<idput()>
                   8899: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8900: 
                   8901: =item *
1.394     bowersj2 8902: X<rolesinit()>
                   8903: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8904: 
                   8905: =item *
1.551     albertel 8906: X<getsection()>
                   8907: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8908: course $cname, return section name/number or '' for "not in course"
                   8909: and '-1' for "no section"
                   8910: 
                   8911: =item *
1.394     bowersj2 8912: X<userenvironment()>
                   8913: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8914: passed in @what from the requested user's environment, returns a hash
                   8915: 
1.858     raeburn  8916: =item * 
                   8917: X<userlog_query()>
1.859     albertel 8918: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8919: activity.log file. %filters defines filters applied when parsing the
                   8920: log file. These can be start or end timestamps, or the type of action
                   8921: - log to look for Login or Logout events, check for Checkin or
                   8922: Checkout, role for role selection. The response is in the form
                   8923: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8924: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8925: 
1.243     albertel 8926: =back
                   8927: 
                   8928: =head2 User Roles
                   8929: 
                   8930: =over 4
                   8931: 
                   8932: =item *
                   8933: 
1.810     raeburn  8934: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8935:  F: full access
                   8936:  U,I,K: authentication modes (cxx only)
                   8937:  '': forbidden
                   8938:  1: user needs to choose course
                   8939:  2: browse allowed
1.766     albertel 8940:  A: passphrase authentication needed
1.243     albertel 8941: 
                   8942: =item *
                   8943: 
                   8944: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8945: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8946: and course level
                   8947: 
                   8948: =item *
                   8949: 
                   8950: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8951: explanation of a user role term
                   8952: 
1.832     raeburn  8953: =item *
                   8954: 
1.935     raeburn  8955: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  8956: All arguments are optional. Returns a hash of a roles, either for
                   8957: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8958: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  8959: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   8960: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   8961: For each key, value is set to colon-separated start and end times for
                   8962: the role.  If no username and domain are specified, will default to
1.934     raeburn  8963: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  8964: of role statuses (active, future or previous), roles 
                   8965: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8966: to restrict the list of roles reported. If no array ref is 
                   8967: provided for types, will default to return only active roles.
1.834     albertel 8968: 
1.243     albertel 8969: =back
                   8970: 
                   8971: =head2 User Modification
                   8972: 
                   8973: =over 4
                   8974: 
                   8975: =item *
                   8976: 
                   8977: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8978: user for the level given by URL.  Optional start and end dates (leave empty
                   8979: string or zero for "no date")
1.191     harris41 8980: 
                   8981: =item *
                   8982: 
1.243     albertel 8983: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8984: change a users, password, possible return values are: ok,
                   8985: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8986: refused
1.191     harris41 8987: 
                   8988: =item *
                   8989: 
1.243     albertel 8990: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8991: 
                   8992: =item *
                   8993: 
1.243     albertel 8994: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8995: modify user
1.191     harris41 8996: 
                   8997: =item *
                   8998: 
1.286     matthew  8999: modifystudent
                   9000: 
                   9001: modify a students enrollment and identification information.
                   9002: The course id is resolved based on the current users environment.  
                   9003: This means the envoking user must be a course coordinator or otherwise
                   9004: associated with a course.
                   9005: 
1.297     matthew  9006: This call is essentially a wrapper for lonnet::modifyuser and
                   9007: lonnet::modify_student_enrollment
1.286     matthew  9008: 
                   9009: Inputs: 
                   9010: 
                   9011: =over 4
                   9012: 
                   9013: =item B<$udom> Students loncapa domain
                   9014: 
                   9015: =item B<$uname> Students loncapa login name
                   9016: 
                   9017: =item B<$uid> Students id/student number
                   9018: 
                   9019: =item B<$umode> Students authentication mode
                   9020: 
                   9021: =item B<$upass> Students password
                   9022: 
                   9023: =item B<$first> Students first name
                   9024: 
                   9025: =item B<$middle> Students middle name
                   9026: 
                   9027: =item B<$last> Students last name
                   9028: 
                   9029: =item B<$gene> Students generation
                   9030: 
                   9031: =item B<$usec> Students section in course
                   9032: 
                   9033: =item B<$end> Unix time of the roles expiration
                   9034: 
                   9035: =item B<$start> Unix time of the roles start date
                   9036: 
                   9037: =item B<$forceid> If defined, allow $uid to be changed
                   9038: 
                   9039: =item B<$desiredhome> server to use as home server for student
                   9040: 
                   9041: =back
1.297     matthew  9042: 
                   9043: =item *
                   9044: 
                   9045: modify_student_enrollment
                   9046: 
                   9047: Change a students enrollment status in a class.  The environment variable
                   9048: 'role.request.course' must be defined for this function to proceed.
                   9049: 
                   9050: Inputs:
                   9051: 
                   9052: =over 4
                   9053: 
                   9054: =item $udom, students domain
                   9055: 
                   9056: =item $uname, students name
                   9057: 
                   9058: =item $uid, students user id
                   9059: 
                   9060: =item $first, students first name
                   9061: 
                   9062: =item $middle
                   9063: 
                   9064: =item $last
                   9065: 
                   9066: =item $gene
                   9067: 
                   9068: =item $usec
                   9069: 
                   9070: =item $end
                   9071: 
                   9072: =item $start
                   9073: 
                   9074: =back
                   9075: 
1.191     harris41 9076: 
                   9077: =item *
                   9078: 
1.243     albertel 9079: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9080: custom role; give a custom role to a user for the level given by URL.  Specify
                   9081: name and domain of role author, and role name
1.191     harris41 9082: 
                   9083: =item *
                   9084: 
1.243     albertel 9085: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9086: 
                   9087: =item *
                   9088: 
1.243     albertel 9089: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9090: 
                   9091: =back
                   9092: 
                   9093: =head2 Course Infomation
                   9094: 
                   9095: =over 4
1.191     harris41 9096: 
                   9097: =item *
                   9098: 
1.631     albertel 9099: coursedescription($courseid) : returns a hash of information about the
                   9100: specified course id, including all environment settings for the
                   9101: course, the description of the course will be in the hash under the
                   9102: key 'description'
1.191     harris41 9103: 
                   9104: =item *
                   9105: 
1.624     albertel 9106: resdata($name,$domain,$type,@which) : request for current parameter
                   9107: setting for a specific $type, where $type is either 'course' or 'user',
                   9108: @what should be a list of parameters to ask about. This routine caches
                   9109: answers for 5 minutes.
1.243     albertel 9110: 
1.877     foxr     9111: =item *
                   9112: 
                   9113: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9114: data base, returning a hash that is keyed by the resource name and has
                   9115: values that are the resource value.  I believe that the timestamps and
                   9116: versions are also returned.
                   9117: 
                   9118: 
1.243     albertel 9119: =back
                   9120: 
                   9121: =head2 Course Modification
                   9122: 
                   9123: =over 4
1.191     harris41 9124: 
                   9125: =item *
                   9126: 
1.243     albertel 9127: writecoursepref($courseid,%prefs) : write preferences (environment
                   9128: database) for a course
1.191     harris41 9129: 
                   9130: =item *
                   9131: 
1.243     albertel 9132: createcourse($udom,$description,$url) : make/modify course
                   9133: 
                   9134: =back
                   9135: 
                   9136: =head2 Resource Subroutines
                   9137: 
                   9138: =over 4
1.191     harris41 9139: 
                   9140: =item *
                   9141: 
1.243     albertel 9142: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9143: 
                   9144: =item *
                   9145: 
1.243     albertel 9146: repcopy($filename) : subscribes to the requested file, and attempts to
                   9147: replicate from the owning library server, Might return
1.607     raeburn  9148: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9149: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9150: resource. Expects the local filesystem pathname
                   9151: (/home/httpd/html/res/....)
                   9152: 
                   9153: =back
                   9154: 
                   9155: =head2 Resource Information
                   9156: 
                   9157: =over 4
1.191     harris41 9158: 
                   9159: =item *
                   9160: 
1.243     albertel 9161: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9162: a vairety of different possible values, $varname should be a request
                   9163: string, and the other parameters can be used to specify who and what
                   9164: one is asking about.
                   9165: 
                   9166: Possible values for $varname are environment.lastname (or other item
                   9167: from the envirnment hash), user.name (or someother aspect about the
                   9168: user), resource.0.maxtries (or some other part and parameter of a
                   9169: resource)
1.204     albertel 9170: 
                   9171: =item *
                   9172: 
1.243     albertel 9173: directcondval($number) : get current value of a condition; reads from a state
                   9174: string
1.204     albertel 9175: 
                   9176: =item *
                   9177: 
1.243     albertel 9178: condval($condidx) : value of condition index based on state
1.204     albertel 9179: 
                   9180: =item *
                   9181: 
1.243     albertel 9182: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9183: resource's metadata, $what should be either a specific key, or either
                   9184: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9185: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9186: 
                   9187: this function automatically caches all requests
1.191     harris41 9188: 
                   9189: =item *
                   9190: 
1.243     albertel 9191: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9192: network of library servers; returns file handle of where SQL and regex results
                   9193: will be stored for query
1.191     harris41 9194: 
                   9195: =item *
                   9196: 
1.243     albertel 9197: symbread($filename) : return symbolic list entry (filename argument optional);
                   9198: returns the data handle
1.191     harris41 9199: 
                   9200: =item *
                   9201: 
1.243     albertel 9202: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9203: a possible symb for the URL in $thisfn, and if is an encryypted
                   9204: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9205: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9206: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9207: 
1.191     harris41 9208: 
                   9209: =item *
                   9210: 
1.243     albertel 9211: symbclean($symb) : removes versions numbers from a symb, returns the
                   9212: cleaned symb
1.191     harris41 9213: 
                   9214: =item *
                   9215: 
1.243     albertel 9216: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9217: course map, user must be in a course for it to work.
1.191     harris41 9218: 
                   9219: =item *
                   9220: 
1.243     albertel 9221: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9222: 
                   9223: =item *
                   9224: 
1.243     albertel 9225: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9226: a random seed, all arguments are optional, if they aren't sent it uses the
                   9227: environment to derive them. Note: if symb isn't sent and it can't get one
                   9228: from &symbread it will use the current time as its return value
1.191     harris41 9229: 
                   9230: =item *
                   9231: 
1.243     albertel 9232: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9233: unfakeable, receipt
1.191     harris41 9234: 
                   9235: =item *
                   9236: 
1.620     albertel 9237: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9238: 
                   9239: =item *
                   9240: 
1.243     albertel 9241: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9242: 
                   9243: =item *
                   9244: 
1.243     albertel 9245: 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 9246: 
                   9247: =item *
                   9248: 
1.243     albertel 9249: 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 9250: 
                   9251: =item *
                   9252: 
1.243     albertel 9253: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9254: 
                   9255: =item *
                   9256: 
1.243     albertel 9257: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9258: forcing spreadsheet to reevaluate the resource scores next time.
                   9259: 
                   9260: =back
                   9261: 
                   9262: =head2 Storing/Retreiving Data
                   9263: 
                   9264: =over 4
1.191     harris41 9265: 
                   9266: =item *
                   9267: 
1.243     albertel 9268: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9269: for this url; hashref needs to be given and should be a \%hashname; the
                   9270: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9271: be derived from the env
1.191     harris41 9272: 
                   9273: =item *
                   9274: 
1.243     albertel 9275: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9276: uses critical subroutine
1.191     harris41 9277: 
                   9278: =item *
                   9279: 
1.243     albertel 9280: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9281: all args are optional
1.191     harris41 9282: 
                   9283: =item *
                   9284: 
1.717     albertel 9285: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9286: dumps the complete (or key matching regexp) namespace into a hash
                   9287: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9288: normally &store()ed into
                   9289: 
                   9290: $range should be either an integer '100' (give me the first 100
                   9291:                                            matching records)
                   9292:               or be  two integers sperated by a - with no spaces
                   9293:                  '30-50' (give me the 30th through the 50th matching
                   9294:                           records)
                   9295: 
                   9296: 
                   9297: =item *
                   9298: 
                   9299: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9300: replaces a &store() version of data with a replacement set of data
                   9301: for a particular resource in a namespace passed in the $storehash hash 
                   9302: reference
                   9303: 
                   9304: =item *
                   9305: 
1.243     albertel 9306: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9307: works very similar to store/cstore, but all data is stored in a
                   9308: temporary location and can be reset using tmpreset, $storehash should
                   9309: be a hash reference, returns nothing on success
1.191     harris41 9310: 
                   9311: =item *
                   9312: 
1.243     albertel 9313: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9314: similar to restore, but all data is stored in a temporary location and
                   9315: can be reset using tmpreset. Returns a hash of values on success,
                   9316: error string otherwise.
1.191     harris41 9317: 
                   9318: =item *
                   9319: 
1.243     albertel 9320: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9321: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9322: 
                   9323: =item *
                   9324: 
1.243     albertel 9325: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9326: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9327: 
                   9328: =item *
                   9329: 
1.243     albertel 9330: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9331: namesp ($udom and $uname are optional)
1.191     harris41 9332: 
                   9333: =item *
                   9334: 
1.702     albertel 9335: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9336: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9337: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9338: 
1.702     albertel 9339: $range should be either an integer '100' (give me the first 100
                   9340:                                            matching records)
                   9341:               or be  two integers sperated by a - with no spaces
                   9342:                  '30-50' (give me the 30th through the 50th matching
                   9343:                           records)
1.449     matthew  9344: =item *
                   9345: 
                   9346: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9347: $store can be a scalar, an array reference, or if the amount to be 
                   9348: incremented is > 1, a hash reference.
                   9349: 
                   9350: ($udom and $uname are optional)
1.191     harris41 9351: 
                   9352: =item *
                   9353: 
1.243     albertel 9354: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9355: ($udom and $uname are optional)
1.191     harris41 9356: 
                   9357: =item *
                   9358: 
1.243     albertel 9359: cput($namespace,$storehash,$udom,$uname) : critical put
                   9360: ($udom and $uname are optional)
1.191     harris41 9361: 
                   9362: =item *
                   9363: 
1.748     albertel 9364: newput($namespace,$storehash,$udom,$uname) :
                   9365: 
                   9366: Attempts to store the items in the $storehash, but only if they don't
                   9367: currently exist, if this succeeds you can be certain that you have 
                   9368: successfully created a new key value pair in the $namespace db.
                   9369: 
                   9370: 
                   9371: Args:
                   9372:  $namespace: name of database to store values to
                   9373:  $storehash: hashref to store to the db
                   9374:  $udom: (optional) domain of user containing the db
                   9375:  $uname: (optional) name of user caontaining the db
                   9376: 
                   9377: Returns:
                   9378:  'ok' -> succeeded in storing all keys of $storehash
                   9379:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9380:                         least <key> already existed in the db (other
                   9381:                         requested keys may also already exist)
                   9382:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9383:  'con_lost' -> unable to contact request server
                   9384:  'refused' -> action was not allowed by remote machine
                   9385: 
                   9386: 
                   9387: =item *
                   9388: 
1.243     albertel 9389: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9390: reference filled in from namesp (encrypts the return communication)
                   9391: ($udom and $uname are optional)
1.191     harris41 9392: 
                   9393: =item *
                   9394: 
1.243     albertel 9395: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9396: critical subroutine
                   9397: 
1.806     raeburn  9398: =item *
                   9399: 
1.860     raeburn  9400: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9401: array reference filled in from namespace found in domain level on either
                   9402: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9403: 
                   9404: =item *
                   9405: 
1.860     raeburn  9406: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9407: domain level either on specified domain server ($uhome) or primary domain 
                   9408: server ($udom and $uhome are optional)
1.806     raeburn  9409: 
1.943     raeburn  9410: =item * 
                   9411: 
                   9412: get_domain_defaults($target_domain) : returns hash with defaults for
                   9413: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9414: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9415: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9416: Values are retrieved from cache (if current), or from domain's configuration.db
                   9417: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9418: or lonTabs/domain.tab. 
                   9419: 
                   9420: %domdefaults = &get_auth_defaults($target_domain);
                   9421: 
1.243     albertel 9422: =back
                   9423: 
                   9424: =head2 Network Status Functions
                   9425: 
                   9426: =over 4
1.191     harris41 9427: 
                   9428: =item *
                   9429: 
                   9430: dirlist($uri) : return directory list based on URI
                   9431: 
                   9432: =item *
                   9433: 
1.243     albertel 9434: spareserver() : find server with least workload from spare.tab
                   9435: 
                   9436: =back
                   9437: 
                   9438: =head2 Apache Request
                   9439: 
                   9440: =over 4
1.191     harris41 9441: 
                   9442: =item *
                   9443: 
1.243     albertel 9444: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9445: localhost, posts hash
                   9446: 
                   9447: =back
                   9448: 
                   9449: =head2 Data to String to Data
                   9450: 
                   9451: =over 4
1.191     harris41 9452: 
                   9453: =item *
                   9454: 
1.243     albertel 9455: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9456: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9457: 
                   9458: =item *
                   9459: 
1.243     albertel 9460: hashref2str($hashref) : convert a hashref into a string complete with
                   9461: escaping and '=' and '&' separators, supports elements that are
                   9462: arrayrefs and hashrefs
1.191     harris41 9463: 
                   9464: =item *
                   9465: 
1.243     albertel 9466: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9467: with escaping and '&' separators, supports elements that are arrayrefs
                   9468: and hashrefs
1.191     harris41 9469: 
                   9470: =item *
                   9471: 
1.243     albertel 9472: str2hash($string) : convert string to hash using unescaping and
                   9473: splitting on '=' and '&', supports elements that are arrayrefs and
                   9474: hashrefs
1.191     harris41 9475: 
                   9476: =item *
                   9477: 
1.243     albertel 9478: str2array($string) : convert string to hash using unescaping and
                   9479: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9480: 
                   9481: =back
                   9482: 
                   9483: =head2 Logging Routines
                   9484: 
                   9485: =over 4
                   9486: 
                   9487: These routines allow one to make log messages in the lonnet.log and
                   9488: lonnet.perm logfiles.
1.191     harris41 9489: 
                   9490: =item *
                   9491: 
1.243     albertel 9492: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9493: 
                   9494: =item *
                   9495: 
1.243     albertel 9496: logthis() : append message to the normal lonnet.log file, it gets
                   9497: preiodically rolled over and deleted.
1.191     harris41 9498: 
                   9499: =item *
                   9500: 
1.243     albertel 9501: logperm() : append a permanent message to lonnet.perm.log, this log
                   9502: file never gets deleted by any automated portion of the system, only
                   9503: messages of critical importance should go in here.
                   9504: 
                   9505: =back
                   9506: 
                   9507: =head2 General File Helper Routines
                   9508: 
                   9509: =over 4
1.191     harris41 9510: 
                   9511: =item *
                   9512: 
1.481     raeburn  9513: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9514: (a) files in /uploaded
                   9515:   (i) If a local copy of the file exists - 
                   9516:       compares modification date of local copy with last-modified date for 
                   9517:       definitive version stored on home server for course. If local copy is 
                   9518:       stale, requests a new version from the home server and stores it. 
                   9519:       If the original has been removed from the home server, then local copy 
                   9520:       is unlinked.
                   9521:   (ii) If local copy does not exist -
                   9522:       requests the file from the home server and stores it. 
                   9523:   
                   9524:   If $caller is 'uploadrep':  
                   9525:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9526:     for request for files originally uploaded via DOCS. 
                   9527:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9528:   
                   9529:   Otherwise:
                   9530:      This indicates a call from the content generation phase of the request.
                   9531:      -  returns the entire contents of the file or -1.
                   9532:      
                   9533: (b) files in /res
                   9534:    - returns the entire contents of a file or -1; 
                   9535:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9536: 
1.712     albertel 9537: 
                   9538: =item *
                   9539: 
                   9540: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9541:                   reference
                   9542: 
                   9543: returns either a stat() list of data about the file or an empty list
                   9544: if the file doesn't exist or couldn't find out about it (connection
                   9545: problems or user unknown)
                   9546: 
1.191     harris41 9547: =item *
                   9548: 
1.243     albertel 9549: filelocation($dir,$file) : returns file system location of a file
                   9550: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9551: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9552: and a file of ../bob will become /a/bob)
1.191     harris41 9553: 
                   9554: =item *
                   9555: 
                   9556: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9557: filelocation except for hrefs
                   9558: 
                   9559: =item *
                   9560: 
                   9561: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9562: 
1.243     albertel 9563: =back
                   9564: 
1.608     albertel 9565: =head2 Usererfile file routines (/uploaded*)
                   9566: 
                   9567: =over 4
                   9568: 
                   9569: =item *
                   9570: 
                   9571: userfileupload(): main rotine for putting a file in a user or course's
                   9572:                   filespace, arguments are,
                   9573: 
1.620     albertel 9574:  formname - required - this is the name of the element in $env where the
1.608     albertel 9575:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9576:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9577:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9578:  coursedoc - if true, store the file in the course of the active role
                   9579:              of the current user
                   9580:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9581:          if undefined, it will be placed in "unknown"
                   9582: 
                   9583:  (This routine calls clean_filename() to remove any dangerous
                   9584:  characters from the filename, and then calls finuserfileupload() to
                   9585:  complete the transaction)
                   9586: 
                   9587:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9588:  and /adm/notfound.html if unsuccessful
                   9589: 
                   9590: =item *
                   9591: 
                   9592: clean_filename(): routine for cleaing a filename up for storage in
                   9593:                  userfile space, argument is:
                   9594: 
                   9595:  filename - proposed filename
                   9596: 
                   9597: returns: the new clean filename
                   9598: 
                   9599: =item *
                   9600: 
                   9601: finishuserfileupload(): routine that creaes and sends the file to
                   9602: userspace, probably shouldn't be called directly
                   9603: 
                   9604:   docuname: username or courseid of destination for the file
                   9605:   docudom: domain of user/course of destination for the file
                   9606:   formname: same as for userfileupload()
                   9607:   fname: filename (inculding subdirectories) for the file
                   9608: 
                   9609:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9610:  and /adm/notfound.html if unsuccessful
                   9611: 
                   9612: =item *
                   9613: 
                   9614: renameuserfile(): renames an existing userfile to a new name
                   9615: 
                   9616:   Args:
                   9617:    docuname: username or courseid of destination for the file
                   9618:    docudom: domain of user/course of destination for the file
                   9619:    old: current file name (including any subdirs under userfiles)
                   9620:    new: desired file name (including any subdirs under userfiles)
                   9621: 
                   9622: =item *
                   9623: 
                   9624: mkdiruserfile(): creates a directory is a userfiles dir
                   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:    dir: dir to create (including any subdirs under userfiles)
                   9630: 
                   9631: =item *
                   9632: 
                   9633: removeuserfile(): removes a file that exists in userfiles
                   9634: 
                   9635:   Args:
                   9636:    docuname: username or courseid of destination for the file
                   9637:    docudom: domain of user/course of destination for the file
                   9638:    fname: filname to delete (including any subdirs under userfiles)
                   9639: 
                   9640: =item *
                   9641: 
                   9642: removeuploadedurl(): convience function for removeuserfile()
                   9643: 
                   9644:   Args:
                   9645:    url:  a full /uploaded/... url to delete
                   9646: 
1.747     albertel 9647: =item * 
                   9648: 
                   9649: get_portfile_permissions():
                   9650:   Args:
                   9651:     domain: domain of user or course contain the portfolio files
                   9652:     user: name of user or num of course contain the portfolio files
                   9653:   Returns:
                   9654:     hashref of a dump of the proper file_permissions.db
                   9655:    
                   9656: 
                   9657: =item * 
                   9658: 
                   9659: get_access_controls():
                   9660: 
                   9661: Args:
                   9662:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9663:   group: (optional) the group you want the files associated with
                   9664:   file: (optional) the file you want access info on
                   9665: 
                   9666: Returns:
1.749     raeburn  9667:     a hash (keys are file names) of hashes containing
                   9668:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9669:         values are XML containing access control settings (see below) 
1.747     albertel 9670: 
                   9671: Internal notes:
                   9672: 
1.749     raeburn  9673:  access controls are stored in file_permissions.db as key=value pairs.
                   9674:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9675:         where scope -> public,guest,course,group,domains or users.
                   9676:               end -> UNIX time for end of access (0 -> no end date)
                   9677:               start -> UNIX time for start of access
                   9678: 
                   9679:     value -> XML description of access control
                   9680:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9681:             <start></start>
                   9682:             <end></end>
                   9683: 
                   9684:             <password></password>  for scope type = guest
                   9685: 
                   9686:             <domain></domain>     for scope type = course or group
                   9687:             <number></number>
                   9688:             <roles id="">
                   9689:              <role></role>
                   9690:              <access></access>
                   9691:              <section></section>
                   9692:              <group></group>
                   9693:             </roles>
                   9694: 
                   9695:             <dom></dom>         for scope type = domains
                   9696: 
                   9697:             <users>             for scope type = users
                   9698:              <user>
                   9699:               <uname></uname>
                   9700:               <udom></udom>
                   9701:              </user>
                   9702:             </users>
                   9703:            </scope> 
                   9704:               
                   9705:  Access data is also aggregated for each file in an additional key=value pair:
                   9706:  key -> path to file/file_name\0accesscontrol 
                   9707:  value -> reference to hash
                   9708:           hash contains key = value pairs
                   9709:           where key = uniqueID:scope_end_start
                   9710:                 value = UNIX time record was last updated
                   9711: 
                   9712:           Used to improve speed of look-ups of access controls for each file.  
                   9713:  
                   9714:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9715: 
                   9716: modify_access_controls():
                   9717: 
                   9718: Modifies access controls for a portfolio file
                   9719: Args
                   9720: 1. file name
                   9721: 2. reference to hash of required changes,
                   9722: 3. domain
                   9723: 4. username
                   9724:   where domain,username are the domain of the portfolio owner 
                   9725:   (either a user or a course) 
                   9726: 
                   9727: Returns:
                   9728: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9729: 2. result of deletions ('ok' or 'error', with error message).
                   9730: 3. reference to hash of any new or updated access controls.
                   9731: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9732:    key = integer (inbound ID)
                   9733:    value = uniqueID  
1.747     albertel 9734: 
1.608     albertel 9735: =back
                   9736: 
1.243     albertel 9737: =head2 HTTP Helper Routines
                   9738: 
                   9739: =over 4
                   9740: 
1.191     harris41 9741: =item *
                   9742: 
                   9743: escape() : unpack non-word characters into CGI-compatible hex codes
                   9744: 
                   9745: =item *
                   9746: 
                   9747: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9748: 
1.243     albertel 9749: =back
                   9750: 
                   9751: =head1 PRIVATE SUBROUTINES
                   9752: 
                   9753: =head2 Underlying communication routines (Shouldn't call)
                   9754: 
                   9755: =over 4
                   9756: 
                   9757: =item *
                   9758: 
                   9759: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9760: 
                   9761: =item *
                   9762: 
                   9763: reply() : uses subreply to send a message to remote machine, logs all failures
                   9764: 
                   9765: =item *
                   9766: 
                   9767: critical() : passes a critical message to another server; if cannot
                   9768: get through then place message in connection buffer directory and
                   9769: returns con_delayed, if incapable of saving message, returns
                   9770: con_failed
                   9771: 
                   9772: =item *
                   9773: 
                   9774: reconlonc() : tries to reconnect lonc client processes.
                   9775: 
                   9776: =back
                   9777: 
                   9778: =head2 Resource Access Logging
                   9779: 
                   9780: =over 4
                   9781: 
                   9782: =item *
                   9783: 
                   9784: flushcourselogs() : flush (save) buffer logs and access logs
                   9785: 
                   9786: =item *
                   9787: 
                   9788: courselog($what) : save message for course in hash
                   9789: 
                   9790: =item *
                   9791: 
                   9792: courseacclog($what) : save message for course using &courselog().  Perform
                   9793: special processing for specific resource types (problems, exams, quizzes, etc).
                   9794: 
1.191     harris41 9795: =item *
                   9796: 
                   9797: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9798: as a PerlChildExitHandler
1.243     albertel 9799: 
                   9800: =back
                   9801: 
                   9802: =head2 Other
                   9803: 
                   9804: =over 4
                   9805: 
                   9806: =item *
                   9807: 
                   9808: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9809: 
                   9810: =back
                   9811: 
                   9812: =cut
1.877     foxr     9813: 

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