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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.948   ! raeburn     4: # $Id: lonnet.pm,v 1.947 2008/03/09 17:22:21 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 {
1.948   ! raeburn  2452:     my ($cid,$codes) = @_;
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.948   ! raeburn  2477:         if ($codes) {
        !          2478:             if ($section) { $role .= ':'.$section; }
        !          2479:             if ($returnhash{$role}) {
        !          2480:                 $returnhash{$role}.=','.$username.':'.$domain;
        !          2481:             } else {
        !          2482:                 $returnhash{$role}=$username.':'.$domain;
        !          2483:             }
1.351     www      2484:         } else {
1.948   ! raeburn  2485:             my $key=&plaintext($role);
        !          2486:             if ($section) { $key.=' (Section '.$section.')'; }
        !          2487:             if ($returnhash{$key}) {
        !          2488: 	        $returnhash{$key}.=','.$username.':'.$domain;
        !          2489:             } else {
        !          2490:                 $returnhash{$key}=$username.':'.$domain;
        !          2491:             }
1.351     www      2492:         }
1.948   ! raeburn  2493:     }
1.400     www      2494:     return %returnhash;
                   2495: }
                   2496: 
                   2497: sub get_my_roles {
1.937     raeburn  2498:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2499:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2500:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2501:     my (%dumphash,%nothide);
1.858     raeburn  2502:     if ($context eq 'userroles') { 
                   2503:         %dumphash = &dump('roles',$udom,$uname);
                   2504:     } else {
                   2505:         %dumphash=
1.400     www      2506:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2507:         if ($hidepriv) {
                   2508:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2509:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2510:                 if ($user !~ /:/) {
                   2511:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2512:                 } else {
                   2513:                     $nothide{$user} = 1;
                   2514:                 }
                   2515:             }
                   2516:         }
1.858     raeburn  2517:     }
1.400     www      2518:     my %returnhash=();
                   2519:     my $now=time;
1.800     albertel 2520:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2521:         my ($role,$tend,$tstart);
                   2522:         if ($context eq 'userroles') {
                   2523: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2524:         } else {
                   2525:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2526:         }
1.400     www      2527:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2528:         my $status = 'active';
1.939     raeburn  2529:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2530:             $status = 'previous';
                   2531:         } 
                   2532:         if (($tstart) && ($now<$tstart)) {
                   2533:             $status = 'future';
                   2534:         }
                   2535:         if (ref($types) eq 'ARRAY') {
                   2536:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2537:                 next;
                   2538:             } 
                   2539:         } else {
                   2540:             if ($status ne 'active') {
                   2541:                 next;
                   2542:             }
                   2543:         }
1.867     raeburn  2544:         my ($rolecode,$username,$domain,$section,$area);
                   2545:         if ($context eq 'userroles') {
                   2546:             ($area,$rolecode) = split(/_/,$entry);
                   2547:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2548:         } else {
                   2549:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2550:         }
1.832     raeburn  2551:         if (ref($roledoms) eq 'ARRAY') {
                   2552:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2553:                 next;
                   2554:             }
                   2555:         }
                   2556:         if (ref($roles) eq 'ARRAY') {
                   2557:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2558:                 if ($role =~ /^cr\//) {
                   2559:                     if (!grep(/^cr$/,@{$roles})) {
                   2560:                         next;
                   2561:                     }
                   2562:                 } else {
                   2563:                     next;
                   2564:                 }
1.832     raeburn  2565:             }
1.867     raeburn  2566:         }
1.937     raeburn  2567:         if ($hidepriv) {
                   2568:             if ((&privileged($username,$domain)) &&
                   2569:                 (!$nothide{$username.':'.$domain})) { 
                   2570:                 next;
                   2571:             }
                   2572:         }
1.933     raeburn  2573:         if ($withsec) {
                   2574:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2575:                 $tstart.':'.$tend;
                   2576:         } else {
                   2577:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2578:         }
1.832     raeburn  2579:     }
1.373     www      2580:     return %returnhash;
1.399     www      2581: }
                   2582: 
                   2583: # ----------------------------------------------------- Frontpage Announcements
                   2584: #
                   2585: #
                   2586: 
                   2587: sub postannounce {
                   2588:     my ($server,$text)=@_;
1.844     albertel 2589:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2590:     unless ($text=~/\w/) { $text=''; }
                   2591:     return &reply('setannounce:'.&escape($text),$server);
                   2592: }
                   2593: 
                   2594: sub getannounce {
1.448     albertel 2595: 
                   2596:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2597: 	my $announcement='';
1.800     albertel 2598: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2599: 	close($fh);
1.399     www      2600: 	if ($announcement=~/\w/) { 
                   2601: 	    return 
                   2602:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2603:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2604: 	} else {
                   2605: 	    return '';
                   2606: 	}
                   2607:     } else {
                   2608: 	return '';
                   2609:     }
1.351     www      2610: }
1.353     www      2611: 
                   2612: # ---------------------------------------------------------- Course ID routines
                   2613: # Deal with domain's nohist_courseid.db files
                   2614: #
                   2615: 
                   2616: sub courseidput {
1.921     raeburn  2617:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2618:     my $outcome;
                   2619:     if ($caller eq 'timeonly') {
                   2620:         my $cids = '';
                   2621:         foreach my $item (keys(%$storehash)) {
                   2622:             $cids.=&escape($item).'&';
                   2623:         }
                   2624:         $cids=~s/\&$//;
                   2625:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2626:                           $coursehome);       
                   2627:     } else {
                   2628:         my $items = '';
                   2629:         foreach my $item (keys(%$storehash)) {
                   2630:             $items.= &escape($item).'='.
                   2631:                      &freeze_escape($$storehash{$item}).'&';
                   2632:         }
                   2633:         $items=~s/\&$//;
                   2634:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2635:                           $coursehome);
1.918     raeburn  2636:     }
                   2637:     if ($outcome eq 'unknown_cmd') {
                   2638:         my $what;
                   2639:         foreach my $cid (keys(%$storehash)) {
                   2640:             $what .= &escape($cid).'=';
1.921     raeburn  2641:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2642:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2643:             }
                   2644:             $what =~ s/\:$/&/;
                   2645:         }
                   2646:         $what =~ s/\&$//;  
                   2647:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2648:     } else {
                   2649:         return $outcome;
                   2650:     }
1.353     www      2651: }
                   2652: 
                   2653: sub courseiddump {
1.921     raeburn  2654:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2655:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
                   2656:         $selfenrollonly)=@_;
1.918     raeburn  2657:     my $as_hash = 1;
                   2658:     my %returnhash;
                   2659:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2660:     my %libserv = &all_library();
                   2661:     foreach my $tryserver (keys(%libserv)) {
                   2662:         if ( (  $hostidflag == 1 
                   2663: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2664: 	     || (!defined($hostidflag)) ) {
                   2665: 
1.918     raeburn  2666: 	    if (($domfilter eq '') ||
                   2667: 		(&host_domain($tryserver) eq $domfilter)) {
                   2668:                 my $rep = 
                   2669:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2670:                          $sincefilter.':'.&escape($descfilter).':'.
                   2671:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2672:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2673:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   2674:                          &escape($selfenrollonly),$tryserver);
1.918     raeburn  2675:                 my @pairs=split(/\&/,$rep);
                   2676:                 foreach my $item (@pairs) {
                   2677:                     my ($key,$value)=split(/\=/,$item,2);
                   2678:                     $key = &unescape($key);
                   2679:                     next if ($key =~ /^error: 2 /);
                   2680:                     my $result = &thaw_unescape($value);
                   2681:                     if (ref($result) eq 'HASH') {
                   2682:                         $returnhash{$key}=$result;
                   2683:                     } else {
1.921     raeburn  2684:                         my @responses = split(/:/,$value);
                   2685:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2686:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2687:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2688:                         }
                   2689:                     } 
1.353     www      2690:                 }
                   2691:             }
                   2692:         }
                   2693:     }
                   2694:     return %returnhash;
                   2695: }
                   2696: 
1.658     raeburn  2697: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2698: 
                   2699: sub dcmailput {
1.685     raeburn  2700:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2701:     my $status = &Apache::lonnet::critical(
1.740     www      2702:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2703:        &escape($message),$server);
1.662     raeburn  2704:     return $status;
                   2705: }
                   2706: 
1.658     raeburn  2707: sub dcmaildump {
                   2708:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2709:     my %returnhash=();
1.846     albertel 2710: 
                   2711:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2712:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2713:                                                          &escape($enddate).':';
                   2714: 	my @esc_senders=map { &escape($_)} @$senders;
                   2715: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2716: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2717:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2718:             if (($key) && ($value)) {
                   2719:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2720:             }
                   2721:         }
                   2722:     }
                   2723:     return %returnhash;
                   2724: }
1.662     raeburn  2725: # ---------------------------------------------------------- Domain roles
                   2726: 
                   2727: sub get_domain_roles {
                   2728:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2729:     if (undef($startdate) || $startdate eq '') {
                   2730:         $startdate = '.';
                   2731:     }
                   2732:     if (undef($enddate) || $enddate eq '') {
                   2733:         $enddate = '.';
                   2734:     }
1.922     raeburn  2735:     my $rolelist;
                   2736:     if (ref($roles) eq 'ARRAY') {
                   2737:         $rolelist = join(':',@{$roles});
                   2738:     }
1.662     raeburn  2739:     my %personnel = ();
1.841     albertel 2740: 
                   2741:     my %servers = &get_servers($dom,'library');
                   2742:     foreach my $tryserver (keys(%servers)) {
                   2743: 	%{$personnel{$tryserver}}=();
                   2744: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2745: 					    &escape($startdate).':'.
                   2746: 					    &escape($enddate).':'.
                   2747: 					    &escape($rolelist), $tryserver))) {
                   2748: 	    my ($key,$value) = split(/\=/,$line,2);
                   2749: 	    if (($key) && ($value)) {
                   2750: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2751: 	    }
                   2752: 	}
1.662     raeburn  2753:     }
                   2754:     return %personnel;
                   2755: }
1.658     raeburn  2756: 
1.149     www      2757: # ----------------------------------------------------------- Check out an item
                   2758: 
1.504     albertel 2759: sub get_first_access {
                   2760:     my ($type,$argsymb)=@_;
1.790     albertel 2761:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2762:     if ($argsymb) { $symb=$argsymb; }
                   2763:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2764:     if ($type eq 'course') {
                   2765: 	$res='course';
                   2766:     } elsif ($type eq 'map') {
1.588     albertel 2767: 	$res=&symbread($map);
                   2768:     } else {
                   2769: 	$res=$symb;
                   2770:     }
                   2771:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2772:     return $times{"$courseid\0$res"};
1.504     albertel 2773: }
                   2774: 
                   2775: sub set_first_access {
                   2776:     my ($type)=@_;
1.790     albertel 2777:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2778:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2779:     if ($type eq 'course') {
                   2780: 	$res='course';
                   2781:     } elsif ($type eq 'map') {
1.588     albertel 2782: 	$res=&symbread($map);
                   2783:     } else {
                   2784: 	$res=$symb;
                   2785:     }
                   2786:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2787:     if (!$firstaccess) {
1.588     albertel 2788: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2789:     }
                   2790:     return 'already_set';
1.504     albertel 2791: }
                   2792: 
1.149     www      2793: sub checkout {
                   2794:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2795:     my $now=time;
                   2796:     my $lonhost=$perlvar{'lonHostID'};
                   2797:     my $infostr=&escape(
1.234     www      2798:                  'CHECKOUTTOKEN&'.
1.149     www      2799:                  $tuname.'&'.
                   2800:                  $tudom.'&'.
                   2801:                  $tcrsid.'&'.
                   2802:                  $symb.'&'.
                   2803: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2804:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2805:     if ($token=~/^error\:/) { 
1.672     albertel 2806:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2807:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2808:                  "</font>");
                   2809:         return ''; 
                   2810:     }
                   2811: 
1.149     www      2812:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2813:     $token=~tr/a-z/A-Z/;
                   2814: 
1.153     www      2815:     my %infohash=('resource.0.outtoken' => $token,
                   2816:                   'resource.0.checkouttime' => $now,
                   2817:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2818: 
                   2819:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2820:        return '';
1.151     www      2821:     } else {
1.672     albertel 2822:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2823:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2824:                  "</font>");
1.149     www      2825:     }    
                   2826: 
                   2827:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2828:                          &escape('Checkout '.$infostr.' - '.
                   2829:                                                  $token)) ne 'ok') {
                   2830: 	return '';
1.151     www      2831:     } else {
1.672     albertel 2832:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2833:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2834:                  "</font>");
1.149     www      2835:     }
1.151     www      2836:     return $token;
1.149     www      2837: }
                   2838: 
                   2839: # ------------------------------------------------------------ Check in an item
                   2840: 
                   2841: sub checkin {
                   2842:     my $token=shift;
1.150     www      2843:     my $now=time;
                   2844:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2845:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2846:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2847:     $dtoken=~s/\W/\_/g;
1.234     www      2848:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2849:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2850: 
1.154     www      2851:     unless (($tuname) && ($tudom)) {
                   2852:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2853:         return '';
                   2854:     }
                   2855:     
                   2856:     unless (&allowed('mgr',$tcrsid)) {
                   2857:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2858:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2859:         return '';
                   2860:     }
                   2861: 
1.153     www      2862:     my %infohash=('resource.0.intoken' => $token,
                   2863:                   'resource.0.checkintime' => $now,
                   2864:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2865: 
                   2866:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2867:        return '';
                   2868:     }    
                   2869: 
                   2870:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2871:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2872: 	return '';
                   2873:     }
                   2874: 
                   2875:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2876: }
                   2877: 
                   2878: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2879: 
                   2880: sub expirespread {
                   2881:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2882:     my $cid=$env{'request.course.id'}; 
1.110     www      2883:     if ($cid) {
                   2884:        my $now=time;
                   2885:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2886:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2887:                             $env{'course.'.$cid.'.num'}.
1.110     www      2888: 	        	    ':nohist_expirationdates:'.
                   2889:                             &escape($key).'='.$now,
1.620     albertel 2890:                             $env{'course.'.$cid.'.home'})
1.110     www      2891:     }
                   2892:     return 'ok';
1.14      www      2893: }
                   2894: 
1.109     www      2895: # ----------------------------------------------------- Devalidate Spreadsheets
                   2896: 
                   2897: sub devalidate {
1.325     www      2898:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2899:     my $cid=$env{'request.course.id'}; 
1.109     www      2900:     if ($cid) {
1.391     matthew  2901:         # delete the stored spreadsheets for
                   2902:         # - the student level sheet of this user in course's homespace
                   2903:         # - the assessment level sheet for this resource 
                   2904:         #   for this user in user's homespace
1.553     albertel 2905: 	# - current conditional state info
1.325     www      2906: 	my $key=$uname.':'.$udom.':';
1.109     www      2907:         my $status=
1.299     matthew  2908: 	    &del('nohist_calculatedsheets',
1.391     matthew  2909: 		 [$key.'studentcalc:'],
1.620     albertel 2910: 		 $env{'course.'.$cid.'.domain'},
                   2911: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2912: 		.' '.
                   2913: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2914: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2915:         unless ($status eq 'ok ok') {
                   2916:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2917:                     $uname.' at '.$udom.' for '.
1.109     www      2918: 		    $symb.': '.$status);
1.133     albertel 2919:         }
1.553     albertel 2920: 	&delenv('user.state.'.$cid);
1.109     www      2921:     }
                   2922: }
                   2923: 
1.265     albertel 2924: sub get_scalar {
                   2925:     my ($string,$end) = @_;
                   2926:     my $value;
                   2927:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2928: 	$value = $1;
                   2929:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2930: 	$value = $1;
                   2931:     }
                   2932:     return &unescape($value);
                   2933: }
                   2934: 
                   2935: sub array2str {
                   2936:   my (@array) = @_;
                   2937:   my $result=&arrayref2str(\@array);
                   2938:   $result=~s/^__ARRAY_REF__//;
                   2939:   $result=~s/__END_ARRAY_REF__$//;
                   2940:   return $result;
                   2941: }
                   2942: 
1.204     albertel 2943: sub arrayref2str {
                   2944:   my ($arrayref) = @_;
1.265     albertel 2945:   my $result='__ARRAY_REF__';
1.204     albertel 2946:   foreach my $elem (@$arrayref) {
1.265     albertel 2947:     if(ref($elem) eq 'ARRAY') {
                   2948:       $result.=&arrayref2str($elem).'&';
                   2949:     } elsif(ref($elem) eq 'HASH') {
                   2950:       $result.=&hashref2str($elem).'&';
                   2951:     } elsif(ref($elem)) {
                   2952:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2953:     } else {
                   2954:       $result.=&escape($elem).'&';
                   2955:     }
                   2956:   }
                   2957:   $result=~s/\&$//;
1.265     albertel 2958:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2959:   return $result;
                   2960: }
                   2961: 
1.168     albertel 2962: sub hash2str {
1.204     albertel 2963:   my (%hash) = @_;
                   2964:   my $result=&hashref2str(\%hash);
1.265     albertel 2965:   $result=~s/^__HASH_REF__//;
                   2966:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2967:   return $result;
                   2968: }
                   2969: 
                   2970: sub hashref2str {
                   2971:   my ($hashref)=@_;
1.265     albertel 2972:   my $result='__HASH_REF__';
1.800     albertel 2973:   foreach my $key (sort(keys(%$hashref))) {
                   2974:     if (ref($key) eq 'ARRAY') {
                   2975:       $result.=&arrayref2str($key).'=';
                   2976:     } elsif (ref($key) eq 'HASH') {
                   2977:       $result.=&hashref2str($key).'=';
                   2978:     } elsif (ref($key)) {
1.265     albertel 2979:       $result.='=';
1.800     albertel 2980:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2981:     } else {
1.800     albertel 2982: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2983:     }
                   2984: 
1.800     albertel 2985:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2986:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2987:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2988:       $result.=&hashref2str($hashref->{$key}).'&';
                   2989:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2990:        $result.='&';
1.800     albertel 2991:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2992:     } else {
1.800     albertel 2993:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2994:     }
                   2995:   }
1.168     albertel 2996:   $result=~s/\&$//;
1.265     albertel 2997:   $result .= '__END_HASH_REF__';
1.168     albertel 2998:   return $result;
                   2999: }
                   3000: 
                   3001: sub str2hash {
1.265     albertel 3002:     my ($string)=@_;
                   3003:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3004:     return %$hash;
                   3005: }
                   3006: 
                   3007: sub str2hashref {
1.168     albertel 3008:   my ($string) = @_;
1.265     albertel 3009: 
                   3010:   my %hash;
                   3011: 
                   3012:   if($string !~ /^__HASH_REF__/) {
                   3013:       if (! ($string eq '' || !defined($string))) {
                   3014: 	  $hash{'error'}='Not hash reference';
                   3015:       }
                   3016:       return (\%hash, $string);
                   3017:   }
                   3018: 
                   3019:   $string =~ s/^__HASH_REF__//;
                   3020: 
                   3021:   while($string !~ /^__END_HASH_REF__/) {
                   3022:       #key
                   3023:       my $key='';
                   3024:       if($string =~ /^__HASH_REF__/) {
                   3025:           ($key, $string)=&str2hashref($string);
                   3026:           if(defined($key->{'error'})) {
                   3027:               $hash{'error'}='Bad data';
                   3028:               return (\%hash, $string);
                   3029:           }
                   3030:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3031:           ($key, $string)=&str2arrayref($string);
                   3032:           if($key->[0] eq 'Array reference error') {
                   3033:               $hash{'error'}='Bad data';
                   3034:               return (\%hash, $string);
                   3035:           }
                   3036:       } else {
                   3037:           $string =~ s/^(.*?)=//;
1.267     albertel 3038: 	  $key=&unescape($1);
1.265     albertel 3039:       }
                   3040:       $string =~ s/^=//;
                   3041: 
                   3042:       #value
                   3043:       my $value='';
                   3044:       if($string =~ /^__HASH_REF__/) {
                   3045:           ($value, $string)=&str2hashref($string);
                   3046:           if(defined($value->{'error'})) {
                   3047:               $hash{'error'}='Bad data';
                   3048:               return (\%hash, $string);
                   3049:           }
                   3050:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3051:           ($value, $string)=&str2arrayref($string);
                   3052:           if($value->[0] eq 'Array reference error') {
                   3053:               $hash{'error'}='Bad data';
                   3054:               return (\%hash, $string);
                   3055:           }
                   3056:       } else {
                   3057: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3058:       }
                   3059:       $string =~ s/^&//;
                   3060: 
                   3061:       $hash{$key}=$value;
1.204     albertel 3062:   }
1.265     albertel 3063: 
                   3064:   $string =~ s/^__END_HASH_REF__//;
                   3065: 
                   3066:   return (\%hash, $string);
1.204     albertel 3067: }
                   3068: 
                   3069: sub str2array {
1.265     albertel 3070:     my ($string)=@_;
                   3071:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3072:     return @$array;
                   3073: }
                   3074: 
                   3075: sub str2arrayref {
1.204     albertel 3076:   my ($string) = @_;
1.265     albertel 3077:   my @array;
                   3078: 
                   3079:   if($string !~ /^__ARRAY_REF__/) {
                   3080:       if (! ($string eq '' || !defined($string))) {
                   3081: 	  $array[0]='Array reference error';
                   3082:       }
                   3083:       return (\@array, $string);
                   3084:   }
                   3085: 
                   3086:   $string =~ s/^__ARRAY_REF__//;
                   3087: 
                   3088:   while($string !~ /^__END_ARRAY_REF__/) {
                   3089:       my $value='';
                   3090:       if($string =~ /^__HASH_REF__/) {
                   3091:           ($value, $string)=&str2hashref($string);
                   3092:           if(defined($value->{'error'})) {
                   3093:               $array[0] ='Array reference error';
                   3094:               return (\@array, $string);
                   3095:           }
                   3096:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3097:           ($value, $string)=&str2arrayref($string);
                   3098:           if($value->[0] eq 'Array reference error') {
                   3099:               $array[0] ='Array reference error';
                   3100:               return (\@array, $string);
                   3101:           }
                   3102:       } else {
                   3103: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3104:       }
                   3105:       $string =~ s/^&//;
                   3106: 
                   3107:       push(@array, $value);
1.191     harris41 3108:   }
1.265     albertel 3109: 
                   3110:   $string =~ s/^__END_ARRAY_REF__//;
                   3111: 
                   3112:   return (\@array, $string);
1.168     albertel 3113: }
                   3114: 
1.167     albertel 3115: # -------------------------------------------------------------------Temp Store
                   3116: 
1.168     albertel 3117: sub tmpreset {
                   3118:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3119:   if (!$symb) {
                   3120:     $symb=&symbread();
1.620     albertel 3121:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3122:   }
                   3123:   $symb=escape($symb);
                   3124: 
1.620     albertel 3125:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3126:   $namespace=~s/\//\_/g;
                   3127:   $namespace=~s/\W//g;
                   3128: 
1.620     albertel 3129:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3130:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3131:   if ($domain eq 'public' && $stuname eq 'public') {
                   3132:       $stuname=$ENV{'REMOTE_ADDR'};
                   3133:   }
1.168     albertel 3134:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3135:   my %hash;
                   3136:   if (tie(%hash,'GDBM_File',
                   3137: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3138: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3139:     foreach my $key (keys %hash) {
1.180     albertel 3140:       if ($key=~ /:$symb/) {
1.168     albertel 3141: 	delete($hash{$key});
                   3142:       }
                   3143:     }
                   3144:   }
                   3145: }
                   3146: 
1.167     albertel 3147: sub tmpstore {
1.168     albertel 3148:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3149: 
                   3150:   if (!$symb) {
                   3151:     $symb=&symbread();
1.620     albertel 3152:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3153:   }
                   3154:   $symb=escape($symb);
                   3155: 
                   3156:   if (!$namespace) {
                   3157:     # I don't think we would ever want to store this for a course.
                   3158:     # it seems this will only be used if we don't have a course.
1.620     albertel 3159:     #$namespace=$env{'request.course.id'};
1.168     albertel 3160:     #if (!$namespace) {
1.620     albertel 3161:       $namespace=$env{'request.state'};
1.168     albertel 3162:     #}
                   3163:   }
                   3164:   $namespace=~s/\//\_/g;
                   3165:   $namespace=~s/\W//g;
1.620     albertel 3166:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3167:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3168:   if ($domain eq 'public' && $stuname eq 'public') {
                   3169:       $stuname=$ENV{'REMOTE_ADDR'};
                   3170:   }
1.168     albertel 3171:   my $now=time;
                   3172:   my %hash;
                   3173:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3174:   if (tie(%hash,'GDBM_File',
                   3175: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3176: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3177:     $hash{"version:$symb"}++;
                   3178:     my $version=$hash{"version:$symb"};
                   3179:     my $allkeys=''; 
                   3180:     foreach my $key (keys(%$storehash)) {
                   3181:       $allkeys.=$key.':';
1.591     albertel 3182:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3183:     }
                   3184:     $hash{"$version:$symb:timestamp"}=$now;
                   3185:     $allkeys.='timestamp';
                   3186:     $hash{"$version:keys:$symb"}=$allkeys;
                   3187:     if (untie(%hash)) {
                   3188:       return 'ok';
                   3189:     } else {
                   3190:       return "error:$!";
                   3191:     }
                   3192:   } else {
                   3193:     return "error:$!";
                   3194:   }
                   3195: }
1.167     albertel 3196: 
1.168     albertel 3197: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3198: 
1.168     albertel 3199: sub tmprestore {
                   3200:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3201: 
1.168     albertel 3202:   if (!$symb) {
                   3203:     $symb=&symbread();
1.620     albertel 3204:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3205:   }
                   3206:   $symb=escape($symb);
                   3207: 
1.620     albertel 3208:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3209: 
1.620     albertel 3210:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3211:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3212:   if ($domain eq 'public' && $stuname eq 'public') {
                   3213:       $stuname=$ENV{'REMOTE_ADDR'};
                   3214:   }
1.168     albertel 3215:   my %returnhash;
                   3216:   $namespace=~s/\//\_/g;
                   3217:   $namespace=~s/\W//g;
                   3218:   my %hash;
                   3219:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3220:   if (tie(%hash,'GDBM_File',
                   3221: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3222: 	  &GDBM_READER(),0640)) {
1.168     albertel 3223:     my $version=$hash{"version:$symb"};
                   3224:     $returnhash{'version'}=$version;
                   3225:     my $scope;
                   3226:     for ($scope=1;$scope<=$version;$scope++) {
                   3227:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3228:       my @keys=split(/:/,$vkeys);
                   3229:       my $key;
                   3230:       $returnhash{"$scope:keys"}=$vkeys;
                   3231:       foreach $key (@keys) {
1.591     albertel 3232: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3233: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3234:       }
                   3235:     }
1.168     albertel 3236:     if (!(untie(%hash))) {
                   3237:       return "error:$!";
                   3238:     }
                   3239:   } else {
                   3240:     return "error:$!";
                   3241:   }
                   3242:   return %returnhash;
1.167     albertel 3243: }
                   3244: 
1.9       www      3245: # ----------------------------------------------------------------------- Store
                   3246: 
                   3247: sub store {
1.124     www      3248:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3249:     my $home='';
                   3250: 
1.168     albertel 3251:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3252: 
1.213     www      3253:     $symb=&symbclean($symb);
1.122     albertel 3254:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3255: 
1.620     albertel 3256:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3257:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3258: 
                   3259:     &devalidate($symb,$stuname,$domain);
1.109     www      3260: 
                   3261:     $symb=escape($symb);
1.187     www      3262:     if (!$namespace) { 
1.620     albertel 3263:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3264:           return ''; 
                   3265:        } 
                   3266:     }
1.620     albertel 3267:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3268: 
                   3269:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3270:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3271: 
1.12      www      3272:     my $namevalue='';
1.800     albertel 3273:     foreach my $key (keys(%$storehash)) {
                   3274:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3275:     }
1.12      www      3276:     $namevalue=~s/\&$//;
1.187     www      3277:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3278:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3279: }
                   3280: 
1.47      www      3281: # -------------------------------------------------------------- Critical Store
                   3282: 
                   3283: sub cstore {
1.124     www      3284:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3285:     my $home='';
                   3286: 
1.168     albertel 3287:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3288: 
1.213     www      3289:     $symb=&symbclean($symb);
1.122     albertel 3290:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3291: 
1.620     albertel 3292:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3293:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3294: 
                   3295:     &devalidate($symb,$stuname,$domain);
1.109     www      3296: 
                   3297:     $symb=escape($symb);
1.187     www      3298:     if (!$namespace) { 
1.620     albertel 3299:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3300:           return ''; 
                   3301:        } 
                   3302:     }
1.620     albertel 3303:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3304: 
                   3305:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3306:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3307: 
1.47      www      3308:     my $namevalue='';
1.800     albertel 3309:     foreach my $key (keys(%$storehash)) {
                   3310:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3311:     }
1.47      www      3312:     $namevalue=~s/\&$//;
1.187     www      3313:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3314:     return critical
                   3315:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3316: }
                   3317: 
1.9       www      3318: # --------------------------------------------------------------------- Restore
                   3319: 
                   3320: sub restore {
1.124     www      3321:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3322:     my $home='';
                   3323: 
1.168     albertel 3324:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3325: 
1.122     albertel 3326:     if (!$symb) {
                   3327:       unless ($symb=escape(&symbread())) { return ''; }
                   3328:     } else {
1.213     www      3329:       $symb=&escape(&symbclean($symb));
1.122     albertel 3330:     }
1.188     www      3331:     if (!$namespace) { 
1.620     albertel 3332:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3333:           return ''; 
                   3334:        } 
                   3335:     }
1.620     albertel 3336:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3337:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3338:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3339:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3340: 
1.12      www      3341:     my %returnhash=();
1.800     albertel 3342:     foreach my $line (split(/\&/,$answer)) {
                   3343: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3344:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3345:     }
1.75      www      3346:     my $version;
                   3347:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3348:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3349:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3350:        }
1.75      www      3351:     }
1.13      www      3352:     return %returnhash;
1.34      www      3353: }
                   3354: 
                   3355: # ---------------------------------------------------------- Course Description
                   3356: 
                   3357: sub coursedescription {
1.731     albertel 3358:     my ($courseid,$args)=@_;
1.34      www      3359:     $courseid=~s/^\///;
1.49      www      3360:     $courseid=~s/\_/\//g;
1.34      www      3361:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3362:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3363:     my $normalid=$cdomain.'_'.$cnum;
                   3364:     # need to always cache even if we get errors otherwise we keep 
                   3365:     # trying and trying and trying to get the course description.
                   3366:     my %envhash=();
                   3367:     my %returnhash=();
1.731     albertel 3368:     
                   3369:     my $expiretime=600;
                   3370:     if ($env{'request.course.id'} eq $normalid) {
                   3371: 	$expiretime=120;
                   3372:     }
                   3373: 
                   3374:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3375:     if (!$args->{'freshen_cache'}
                   3376: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3377: 	foreach my $key (keys(%env)) {
                   3378: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3379: 	    my ($setting) = $1;
                   3380: 	    $returnhash{$setting} = $env{$key};
                   3381: 	}
                   3382: 	return %returnhash;
                   3383:     }
                   3384: 
                   3385:     # get the data agin
                   3386:     if (!$args->{'one_time'}) {
                   3387: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3388:     }
1.811     albertel 3389: 
1.34      www      3390:     if ($chome ne 'no_host') {
1.302     albertel 3391:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3392:        if (!exists($returnhash{'con_lost'})) {
                   3393:            $returnhash{'home'}= $chome;
                   3394: 	   $returnhash{'domain'} = $cdomain;
                   3395: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3396:            if (!defined($returnhash{'type'})) {
                   3397:                $returnhash{'type'} = 'Course';
                   3398:            }
1.130     albertel 3399:            while (my ($name,$value) = each %returnhash) {
1.53      www      3400:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3401:            }
1.270     www      3402:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3403:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3404: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3405:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3406:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3407:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3408:        }
                   3409:     }
1.731     albertel 3410:     if (!$args->{'one_time'}) {
                   3411: 	&appenv(%envhash);
                   3412:     }
1.302     albertel 3413:     return %returnhash;
1.461     www      3414: }
                   3415: 
                   3416: # -------------------------------------------------See if a user is privileged
                   3417: 
                   3418: sub privileged {
                   3419:     my ($username,$domain)=@_;
                   3420:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3421: 			&homeserver($username,$domain));
                   3422:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3423:     my $now=time;
                   3424:     if ($rolesdump ne '') {
1.800     albertel 3425:         foreach my $entry (split(/&/,$rolesdump)) {
                   3426: 	    if ($entry!~/^rolesdef_/) {
                   3427: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3428: 		$area=~s/\_\w\w$//;
                   3429: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3430: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3431: 		    my $active=1;
                   3432: 		    if ($tend) {
                   3433: 			if ($tend<$now) { $active=0; }
                   3434: 		    }
                   3435: 		    if ($tstart) {
                   3436: 			if ($tstart>$now) { $active=0; }
                   3437: 		    }
                   3438: 		    if ($active) { return 1; }
                   3439: 		}
                   3440: 	    }
                   3441: 	}
                   3442:     }
                   3443:     return 0;
1.9       www      3444: }
1.1       albertel 3445: 
1.103     harris41 3446: # -------------------------------------------------------- Get user privileges
1.11      www      3447: 
                   3448: sub rolesinit {
                   3449:     my ($domain,$username,$authhost)=@_;
                   3450:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3451:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3452:     my %allroles=();
1.678     raeburn  3453:     my %allgroups=();   
1.11      www      3454:     my $now=time;
1.743     albertel 3455:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3456:     my $group_privs;
1.11      www      3457: 
                   3458:     if ($rolesdump ne '') {
1.800     albertel 3459:         foreach my $entry (split(/&/,$rolesdump)) {
                   3460: 	  if ($entry!~/^rolesdef_/) {
                   3461:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3462: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3463:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3464: 	    if ($role=~/^cr/) { 
1.807     albertel 3465: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3466: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3467: 		    ($tend,$tstart)=split('_',$trest);
                   3468: 		} else {
                   3469: 		    $trole=$role;
                   3470: 		}
1.678     raeburn  3471:             } elsif ($role =~ m|^gr/|) {
                   3472:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3473:                 ($trole,$group_privs) = split(/\//,$trole);
                   3474:                 $group_privs = &unescape($group_privs);
1.587     albertel 3475: 	    } else {
                   3476: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3477: 	    }
1.743     albertel 3478: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3479: 					 $username);
                   3480: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3481:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3482:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3483:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3484: 		my $spec=$trole.'.'.$area;
                   3485: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3486: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3487:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3488:                 } elsif ($trole eq 'gr') {
                   3489:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3490: 		} else {
1.567     raeburn  3491:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3492: 		}
1.12      www      3493:             }
1.662     raeburn  3494:           }
1.191     harris41 3495:         }
1.743     albertel 3496:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3497:         $userroles{'user.adv'}    = $adv;
                   3498: 	$userroles{'user.author'} = $author;
1.620     albertel 3499:         $env{'user.adv'}=$adv;
1.11      www      3500:     }
1.743     albertel 3501:     return \%userroles;  
1.11      www      3502: }
                   3503: 
1.567     raeburn  3504: sub set_arearole {
                   3505:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3506: # log the associated role with the area
                   3507:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3508:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3509: }
                   3510: 
                   3511: sub custom_roleprivs {
                   3512:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3513:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3514:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3515:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3516:         my ($rdummy,$roledef)=
                   3517:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3518:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3519:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3520:             if (defined($syspriv)) {
                   3521:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3522:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3523:             }
                   3524:             if ($tdomain ne '') {
                   3525:                 if (defined($dompriv)) {
                   3526:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3527:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3528:                 }
                   3529:                 if (($trest ne '') && (defined($coursepriv))) {
                   3530:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3531:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3532:                 }
                   3533:             }
                   3534:         }
                   3535:     }
                   3536: }
                   3537: 
1.678     raeburn  3538: sub group_roleprivs {
                   3539:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3540:     my $access = 1;
                   3541:     my $now = time;
                   3542:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3543:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3544:     if ($access) {
1.811     albertel 3545:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3546:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3547:     }
                   3548: }
1.567     raeburn  3549: 
                   3550: sub standard_roleprivs {
                   3551:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3552:     if (defined($pr{$trole.':s'})) {
                   3553:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3554:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3555:     }
                   3556:     if ($tdomain ne '') {
                   3557:         if (defined($pr{$trole.':d'})) {
                   3558:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3559:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3560:         }
                   3561:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3562:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3563:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3564:         }
                   3565:     }
                   3566: }
                   3567: 
                   3568: sub set_userprivs {
1.678     raeburn  3569:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3570:     my $author=0;
                   3571:     my $adv=0;
1.678     raeburn  3572:     my %grouproles = ();
                   3573:     if (keys(%{$allgroups}) > 0) {
                   3574:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3575:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3576:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3577:                 $trole = $1;
                   3578:                 $area = $2;
1.681     raeburn  3579:                 $sec = $3;
                   3580:                 $extendedarea = $area.$sec;
                   3581:                 if (exists($$allgroups{$area})) {
                   3582:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3583:                         my $spec = $trole.'.'.$extendedarea;
                   3584:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3585:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3586:                     }
                   3587:                 }
                   3588:             }
                   3589:         }
                   3590:     }
1.800     albertel 3591:     foreach my $group (keys(%grouproles)) {
                   3592:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3593:     }
1.800     albertel 3594:     foreach my $role (keys(%{$allroles})) {
                   3595:         my %thesepriv;
1.941     raeburn  3596:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3597:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3598:             if ($item ne '') {
                   3599:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3600:                 if ($restrictions eq '') {
                   3601:                     $thesepriv{$privilege}='F';
                   3602:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3603:                     $thesepriv{$privilege}.=$restrictions;
                   3604:                 }
                   3605:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3606:             }
                   3607:         }
                   3608:         my $thesestr='';
1.800     albertel 3609:         foreach my $priv (keys(%thesepriv)) {
                   3610: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3611: 	}
                   3612:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3613:     }
                   3614:     return ($author,$adv);
                   3615: }
                   3616: 
1.12      www      3617: # --------------------------------------------------------------- get interface
                   3618: 
                   3619: sub get {
1.131     albertel 3620:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3621:    my $items='';
1.800     albertel 3622:    foreach my $item (@$storearr) {
                   3623:        $items.=&escape($item).'&';
1.191     harris41 3624:    }
1.12      www      3625:    $items=~s/\&$//;
1.620     albertel 3626:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3627:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3628:    my $uhome=&homeserver($uname,$udomain);
                   3629: 
1.133     albertel 3630:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3631:    my @pairs=split(/\&/,$rep);
1.273     albertel 3632:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3633:      return @pairs;
                   3634:    }
1.15      www      3635:    my %returnhash=();
1.42      www      3636:    my $i=0;
1.800     albertel 3637:    foreach my $item (@$storearr) {
                   3638:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3639:       $i++;
1.191     harris41 3640:    }
1.15      www      3641:    return %returnhash;
1.27      www      3642: }
                   3643: 
                   3644: # --------------------------------------------------------------- del interface
                   3645: 
                   3646: sub del {
1.133     albertel 3647:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3648:    my $items='';
1.800     albertel 3649:    foreach my $item (@$storearr) {
                   3650:        $items.=&escape($item).'&';
1.191     harris41 3651:    }
1.27      www      3652:    $items=~s/\&$//;
1.620     albertel 3653:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3654:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3655:    my $uhome=&homeserver($uname,$udomain);
                   3656: 
                   3657:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3658: }
                   3659: 
                   3660: # -------------------------------------------------------------- dump interface
                   3661: 
                   3662: sub dump {
1.755     albertel 3663:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3664:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3665:     if (!$uname) { $uname=$env{'user.name'}; }
                   3666:     my $uhome=&homeserver($uname,$udomain);
                   3667:     if ($regexp) {
                   3668: 	$regexp=&escape($regexp);
                   3669:     } else {
                   3670: 	$regexp='.';
                   3671:     }
                   3672:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3673:     my @pairs=split(/\&/,$rep);
                   3674:     my %returnhash=();
                   3675:     foreach my $item (@pairs) {
                   3676: 	my ($key,$value)=split(/=/,$item,2);
                   3677: 	$key = &unescape($key);
                   3678: 	next if ($key =~ /^error: 2 /);
                   3679: 	$returnhash{$key}=&thaw_unescape($value);
                   3680:     }
                   3681:     return %returnhash;
1.407     www      3682: }
                   3683: 
1.717     albertel 3684: # --------------------------------------------------------- dumpstore interface
                   3685: 
                   3686: sub dumpstore {
                   3687:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3688:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3689:    if (!$uname) { $uname=$env{'user.name'}; }
                   3690:    my $uhome=&homeserver($uname,$udomain);
                   3691:    if ($regexp) {
                   3692:        $regexp=&escape($regexp);
                   3693:    } else {
                   3694:        $regexp='.';
                   3695:    }
                   3696:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3697:    my @pairs=split(/\&/,$rep);
                   3698:    my %returnhash=();
                   3699:    foreach my $item (@pairs) {
                   3700:        my ($key,$value)=split(/=/,$item,2);
                   3701:        next if ($key =~ /^error: 2 /);
                   3702:        $returnhash{$key}=&thaw_unescape($value);
                   3703:    }
                   3704:    return %returnhash;
1.717     albertel 3705: }
                   3706: 
1.407     www      3707: # -------------------------------------------------------------- keys interface
                   3708: 
                   3709: sub getkeys {
                   3710:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3711:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3712:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3713:    my $uhome=&homeserver($uname,$udomain);
                   3714:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3715:    my @keyarray=();
1.800     albertel 3716:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3717:       next if ($key =~ /^error: 2 /);
1.800     albertel 3718:       push(@keyarray,&unescape($key));
1.407     www      3719:    }
                   3720:    return @keyarray;
1.318     matthew  3721: }
                   3722: 
1.319     matthew  3723: # --------------------------------------------------------------- currentdump
                   3724: sub currentdump {
1.328     matthew  3725:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3726:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3727:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3728:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3729:    my $uhome = &homeserver($sname,$sdom);
                   3730:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3731:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3732:    #
1.318     matthew  3733:    my %returnhash=();
1.319     matthew  3734:    #
                   3735:    if ($rep eq "unknown_cmd") { 
                   3736:        # an old lond will not know currentdump
                   3737:        # Do a dump and make it look like a currentdump
1.822     albertel 3738:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3739:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3740:        my %hash = @tmp;
                   3741:        @tmp=();
1.424     matthew  3742:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3743:    } else {
                   3744:        my @pairs=split(/\&/,$rep);
1.800     albertel 3745:        foreach my $pair (@pairs) {
                   3746:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3747:            my ($symb,$param) = split(/:/,$key);
                   3748:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3749:                                                         &thaw_unescape($value);
1.319     matthew  3750:        }
1.191     harris41 3751:    }
1.12      www      3752:    return %returnhash;
1.424     matthew  3753: }
                   3754: 
                   3755: sub convert_dump_to_currentdump{
                   3756:     my %hash = %{shift()};
                   3757:     my %returnhash;
                   3758:     # Code ripped from lond, essentially.  The only difference
                   3759:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3760:     # we might run in to problems with parameter names =~ /^v\./
                   3761:     while (my ($key,$value) = each(%hash)) {
                   3762:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3763: 	$symb  = &unescape($symb);
                   3764: 	$param = &unescape($param);
1.424     matthew  3765:         next if ($v eq 'version' || $symb eq 'keys');
                   3766:         next if (exists($returnhash{$symb}) &&
                   3767:                  exists($returnhash{$symb}->{$param}) &&
                   3768:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3769:         $returnhash{$symb}->{$param}=$value;
                   3770:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3771:     }
                   3772:     #
                   3773:     # Remove all of the keys in the hashes which keep track of
                   3774:     # the version of the parameter.
                   3775:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3776:         # use a foreach because we are going to delete from the hash.
                   3777:         foreach my $key (keys(%$param_hash)) {
                   3778:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3779:         }
                   3780:     }
                   3781:     return \%returnhash;
1.12      www      3782: }
                   3783: 
1.627     albertel 3784: # ------------------------------------------------------ critical inc interface
                   3785: 
                   3786: sub cinc {
                   3787:     return &inc(@_,'critical');
                   3788: }
                   3789: 
1.449     matthew  3790: # --------------------------------------------------------------- inc interface
                   3791: 
                   3792: sub inc {
1.627     albertel 3793:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3794:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3795:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3796:     my $uhome=&homeserver($uname,$udomain);
                   3797:     my $items='';
                   3798:     if (! ref($store)) {
                   3799:         # got a single value, so use that instead
                   3800:         $items = &escape($store).'=&';
                   3801:     } elsif (ref($store) eq 'SCALAR') {
                   3802:         $items = &escape($$store).'=&';        
                   3803:     } elsif (ref($store) eq 'ARRAY') {
                   3804:         $items = join('=&',map {&escape($_);} @{$store});
                   3805:     } elsif (ref($store) eq 'HASH') {
                   3806:         while (my($key,$value) = each(%{$store})) {
                   3807:             $items.= &escape($key).'='.&escape($value).'&';
                   3808:         }
                   3809:     }
                   3810:     $items=~s/\&$//;
1.627     albertel 3811:     if ($critical) {
                   3812: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3813:     } else {
                   3814: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3815:     }
1.449     matthew  3816: }
                   3817: 
1.12      www      3818: # --------------------------------------------------------------- put interface
                   3819: 
                   3820: sub put {
1.134     albertel 3821:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3822:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3823:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3824:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3825:    my $items='';
1.800     albertel 3826:    foreach my $item (keys(%$storehash)) {
                   3827:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3828:    }
1.12      www      3829:    $items=~s/\&$//;
1.134     albertel 3830:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3831: }
                   3832: 
1.631     albertel 3833: # ------------------------------------------------------------ newput interface
                   3834: 
                   3835: sub newput {
                   3836:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3837:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3838:    if (!$uname) { $uname=$env{'user.name'}; }
                   3839:    my $uhome=&homeserver($uname,$udomain);
                   3840:    my $items='';
                   3841:    foreach my $key (keys(%$storehash)) {
                   3842:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3843:    }
                   3844:    $items=~s/\&$//;
                   3845:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3846: }
                   3847: 
                   3848: # ---------------------------------------------------------  putstore interface
                   3849: 
1.524     raeburn  3850: sub putstore {
1.715     albertel 3851:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3852:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3853:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3854:    my $uhome=&homeserver($uname,$udomain);
                   3855:    my $items='';
1.715     albertel 3856:    foreach my $key (keys(%$storehash)) {
                   3857:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3858:    }
1.715     albertel 3859:    $items=~s/\&$//;
1.716     albertel 3860:    my $esc_symb=&escape($symb);
                   3861:    my $esc_v=&escape($version);
1.715     albertel 3862:    my $reply =
1.716     albertel 3863:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3864: 	      $uhome);
                   3865:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3866:        # gfall back to way things use to be done
1.715     albertel 3867:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3868: 			    $uname);
1.524     raeburn  3869:    }
1.715     albertel 3870:    return $reply;
                   3871: }
                   3872: 
                   3873: sub old_putstore {
1.716     albertel 3874:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3875:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3876:     if (!$uname) { $uname=$env{'user.name'}; }
                   3877:     my $uhome=&homeserver($uname,$udomain);
                   3878:     my %newstorehash;
1.800     albertel 3879:     foreach my $item (keys(%$storehash)) {
                   3880: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3881: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3882:     }
                   3883:     my $items='';
                   3884:     my %allitems = ();
1.800     albertel 3885:     foreach my $item (keys(%newstorehash)) {
                   3886: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3887: 	    my $key = $1.':keys:'.$2;
                   3888: 	    $allitems{$key} .= $3.':';
                   3889: 	}
1.800     albertel 3890: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3891:     }
1.800     albertel 3892:     foreach my $item (keys(%allitems)) {
                   3893: 	$allitems{$item} =~ s/\:$//;
                   3894: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3895:     }
                   3896:     $items=~s/\&$//;
                   3897:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3898: }
                   3899: 
1.47      www      3900: # ------------------------------------------------------ critical put interface
                   3901: 
                   3902: sub cput {
1.134     albertel 3903:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3904:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3905:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3906:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3907:    my $items='';
1.800     albertel 3908:    foreach my $item (keys(%$storehash)) {
                   3909:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3910:    }
1.47      www      3911:    $items=~s/\&$//;
1.134     albertel 3912:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3913: }
                   3914: 
                   3915: # -------------------------------------------------------------- eget interface
                   3916: 
                   3917: sub eget {
1.133     albertel 3918:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3919:    my $items='';
1.800     albertel 3920:    foreach my $item (@$storearr) {
                   3921:        $items.=&escape($item).'&';
1.191     harris41 3922:    }
1.12      www      3923:    $items=~s/\&$//;
1.620     albertel 3924:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3925:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3926:    my $uhome=&homeserver($uname,$udomain);
                   3927:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3928:    my @pairs=split(/\&/,$rep);
                   3929:    my %returnhash=();
1.42      www      3930:    my $i=0;
1.800     albertel 3931:    foreach my $item (@$storearr) {
                   3932:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3933:       $i++;
1.191     harris41 3934:    }
1.12      www      3935:    return %returnhash;
                   3936: }
                   3937: 
1.667     albertel 3938: # ------------------------------------------------------------ tmpput interface
                   3939: sub tmpput {
1.802     raeburn  3940:     my ($storehash,$server,$context)=@_;
1.667     albertel 3941:     my $items='';
1.800     albertel 3942:     foreach my $item (keys(%$storehash)) {
                   3943: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3944:     }
                   3945:     $items=~s/\&$//;
1.802     raeburn  3946:     if (defined($context)) {
                   3947:         $items .= ':'.&escape($context);
                   3948:     }
1.667     albertel 3949:     return &reply("tmpput:$items",$server);
                   3950: }
                   3951: 
                   3952: # ------------------------------------------------------------ tmpget interface
                   3953: sub tmpget {
1.688     albertel 3954:     my ($token,$server)=@_;
                   3955:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3956:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3957:     my %returnhash;
                   3958:     foreach my $item (split(/\&/,$rep)) {
                   3959: 	my ($key,$value)=split(/=/,$item);
                   3960: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3961:     }
                   3962:     return %returnhash;
                   3963: }
                   3964: 
1.688     albertel 3965: # ------------------------------------------------------------ tmpget interface
                   3966: sub tmpdel {
                   3967:     my ($token,$server)=@_;
                   3968:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3969:     return &reply("tmpdel:$token",$server);
                   3970: }
                   3971: 
1.765     albertel 3972: # -------------------------------------------------- portfolio access checking
                   3973: 
                   3974: sub portfolio_access {
1.766     albertel 3975:     my ($requrl) = @_;
1.765     albertel 3976:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3977:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3978:     if ($result) {
                   3979:         my %setters;
                   3980:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3981:             my ($startblock,$endblock) =
                   3982:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3983:             if ($startblock && $endblock) {
                   3984:                 return 'B';
                   3985:             }
                   3986:         } else {
                   3987:             my ($startblock,$endblock) =
                   3988:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3989:             if ($startblock && $endblock) {
                   3990:                 return 'B';
                   3991:             }
                   3992:         }
                   3993:     }
1.765     albertel 3994:     if ($result eq 'ok') {
1.766     albertel 3995:        return 'F';
1.765     albertel 3996:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3997:        return 'A';
1.765     albertel 3998:     }
1.766     albertel 3999:     return '';
1.765     albertel 4000: }
                   4001: 
                   4002: sub get_portfolio_access {
1.767     albertel 4003:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4004: 
                   4005:     if (!ref($access_hash)) {
                   4006: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4007: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4008: 						   $file_name);
                   4009: 	$access_hash = $access_controls{$file_name};
                   4010:     }
                   4011: 
1.765     albertel 4012:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4013:     my $now = time;
                   4014:     if (ref($access_hash) eq 'HASH') {
                   4015:         foreach my $key (keys(%{$access_hash})) {
                   4016:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4017:             if ($start > $now) {
                   4018:                 next;
                   4019:             }
                   4020:             if ($end && $end<$now) {
                   4021:                 next;
                   4022:             }
                   4023:             if ($scope eq 'public') {
                   4024:                 $public = $key;
                   4025:                 last;
                   4026:             } elsif ($scope eq 'guest') {
                   4027:                 $guest = $key;
                   4028:             } elsif ($scope eq 'domains') {
                   4029:                 push(@domains,$key);
                   4030:             } elsif ($scope eq 'users') {
                   4031:                 push(@users,$key);
                   4032:             } elsif ($scope eq 'course') {
                   4033:                 push(@courses,$key);
                   4034:             } elsif ($scope eq 'group') {
                   4035:                 push(@groups,$key);
                   4036:             }
                   4037:         }
                   4038:         if ($public) {
                   4039:             return 'ok';
                   4040:         }
                   4041:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4042:             if ($guest) {
                   4043:                 return $guest;
                   4044:             }
                   4045:         } else {
                   4046:             if (@domains > 0) {
                   4047:                 foreach my $domkey (@domains) {
                   4048:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4049:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4050:                             return 'ok';
                   4051:                         }
                   4052:                     }
                   4053:                 }
                   4054:             }
                   4055:             if (@users > 0) {
                   4056:                 foreach my $userkey (@users) {
1.865     raeburn  4057:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4058:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4059:                             if (ref($item) eq 'HASH') {
                   4060:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4061:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4062:                                     return 'ok';
                   4063:                                 }
                   4064:                             }
                   4065:                         }
                   4066:                     } 
1.765     albertel 4067:                 }
                   4068:             }
                   4069:             my %roleshash;
                   4070:             my @courses_and_groups = @courses;
                   4071:             push(@courses_and_groups,@groups); 
                   4072:             if (@courses_and_groups > 0) {
                   4073:                 my (%allgroups,%allroles); 
                   4074:                 my ($start,$end,$role,$sec,$group);
                   4075:                 foreach my $envkey (%env) {
1.811     albertel 4076:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4077:                         my $cid = $2.'_'.$3; 
                   4078:                         if ($1 eq 'gr') {
                   4079:                             $group = $4;
                   4080:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4081:                         } else {
                   4082:                             if ($4 eq '') {
                   4083:                                 $sec = 'none';
                   4084:                             } else {
                   4085:                                 $sec = $4;
                   4086:                             }
                   4087:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4088:                         }
1.811     albertel 4089:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4090:                         my $cid = $2.'_'.$3;
                   4091:                         if ($4 eq '') {
                   4092:                             $sec = 'none';
                   4093:                         } else {
                   4094:                             $sec = $4;
                   4095:                         }
                   4096:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4097:                     }
                   4098:                 }
                   4099:                 if (keys(%allroles) == 0) {
                   4100:                     return;
                   4101:                 }
                   4102:                 foreach my $key (@courses_and_groups) {
                   4103:                     my %content = %{$$access_hash{$key}};
                   4104:                     my $cnum = $content{'number'};
                   4105:                     my $cdom = $content{'domain'};
                   4106:                     my $cid = $cdom.'_'.$cnum;
                   4107:                     if (!exists($allroles{$cid})) {
                   4108:                         next;
                   4109:                     }    
                   4110:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4111:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4112:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4113:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4114:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4115:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4116:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4117:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4118:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4119:                                         if (grep/^all$/,@sections) {
                   4120:                                             return 'ok';
                   4121:                                         } else {
                   4122:                                             if (grep/^$sec$/,@sections) {
                   4123:                                                 return 'ok';
                   4124:                                             }
                   4125:                                         }
                   4126:                                     }
                   4127:                                 }
                   4128:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4129:                                     if (grep/^none$/,@groups) {
                   4130:                                         return 'ok';
                   4131:                                     }
                   4132:                                 } else {
                   4133:                                     if (grep/^all$/,@groups) {
                   4134:                                         return 'ok';
                   4135:                                     } 
                   4136:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4137:                                         if (grep/^$group$/,@groups) {
                   4138:                                             return 'ok';
                   4139:                                         }
                   4140:                                     }
                   4141:                                 } 
                   4142:                             }
                   4143:                         }
                   4144:                     }
                   4145:                 }
                   4146:             }
                   4147:             if ($guest) {
                   4148:                 return $guest;
                   4149:             }
                   4150:         }
                   4151:     }
                   4152:     return;
                   4153: }
                   4154: 
                   4155: sub course_group_datechecker {
                   4156:     my ($dates,$now,$status) = @_;
                   4157:     my ($start,$end) = split(/\./,$dates);
                   4158:     if (!$start && !$end) {
                   4159:         return 'ok';
                   4160:     }
                   4161:     if (grep/^active$/,@{$status}) {
                   4162:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4163:             return 'ok';
                   4164:         }
                   4165:     }
                   4166:     if (grep/^previous$/,@{$status}) {
                   4167:         if ($end > $now ) {
                   4168:             return 'ok';
                   4169:         }
                   4170:     }
                   4171:     if (grep/^future$/,@{$status}) {
                   4172:         if ($start > $now) {
                   4173:             return 'ok';
                   4174:         }
                   4175:     }
                   4176:     return; 
                   4177: }
                   4178: 
                   4179: sub parse_portfolio_url {
                   4180:     my ($url) = @_;
                   4181: 
                   4182:     my ($type,$udom,$unum,$group,$file_name);
                   4183:     
1.823     albertel 4184:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4185: 	$type = 1;
                   4186:         $udom = $1;
                   4187:         $unum = $2;
                   4188:         $file_name = $3;
1.823     albertel 4189:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4190: 	$type = 2;
                   4191:         $udom = $1;
                   4192:         $unum = $2;
                   4193:         $group = $3;
                   4194:         $file_name = $3.'/'.$4;
                   4195:     }
                   4196:     if (wantarray) {
                   4197: 	return ($type,$udom,$unum,$file_name,$group);
                   4198:     }
                   4199:     return $type;
                   4200: }
                   4201: 
                   4202: sub is_portfolio_url {
                   4203:     my ($url) = @_;
                   4204:     return scalar(&parse_portfolio_url($url));
                   4205: }
                   4206: 
1.798     raeburn  4207: sub is_portfolio_file {
                   4208:     my ($file) = @_;
1.820     raeburn  4209:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4210:         return 1;
                   4211:     }
                   4212:     return;
                   4213: }
                   4214: 
                   4215: 
1.341     www      4216: # ---------------------------------------------- Custom access rule evaluation
                   4217: 
                   4218: sub customaccess {
                   4219:     my ($priv,$uri)=@_;
1.807     albertel 4220:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4221:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4222:     $udom = &LONCAPA::clean_domain($udom);
                   4223:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4224:     my $access=0;
1.800     albertel 4225:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4226: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4227: 	if ($type eq 'user') {
                   4228: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4229: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4230: 		if ($tdom) {
                   4231: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4232: 		}
1.896     albertel 4233: 		if ($tuname) {
                   4234: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4235: 		}
                   4236: 		$access=($effect eq 'allow');
                   4237: 		last;
                   4238: 	    }
                   4239: 	} else {
                   4240: 	    if ($role) {
                   4241: 		if ($role ne $urole) { next; }
                   4242: 	    }
                   4243: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4244: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4245: 		if ($tdom) {
                   4246: 		    if ($tdom ne $udom) { next; }
                   4247: 		}
                   4248: 		if ($tcrs) {
                   4249: 		    if ($tcrs ne $ucrs) { next; }
                   4250: 		}
                   4251: 		if ($tsec) {
                   4252: 		    if ($tsec ne $usec) { next; }
                   4253: 		}
                   4254: 		$access=($effect eq 'allow');
                   4255: 		last;
                   4256: 	    }
                   4257: 	    if ($realm eq '' && $role eq '') {
                   4258: 		$access=($effect eq 'allow');
                   4259: 	    }
1.402     bowersj2 4260: 	}
1.341     www      4261:     }
                   4262:     return $access;
                   4263: }
                   4264: 
1.103     harris41 4265: # ------------------------------------------------- Check for a user privilege
1.12      www      4266: 
                   4267: sub allowed {
1.810     raeburn  4268:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4269:     my $ver_orguri=$uri;
1.439     www      4270:     $uri=&deversion($uri);
1.152     www      4271:     my $orguri=$uri;
1.52      www      4272:     $uri=&declutter($uri);
1.809     raeburn  4273: 
1.810     raeburn  4274:     if ($priv eq 'evb') {
                   4275: # Evade communication block restrictions for specified role in a course
                   4276:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4277:             return $1;
                   4278:         } else {
                   4279:             return;
                   4280:         }
                   4281:     }
                   4282: 
1.620     albertel 4283:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4284: # Free bre access to adm and meta resources
1.775     albertel 4285:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4286: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4287: 	&& ($priv eq 'bre')) {
1.14      www      4288: 	return 'F';
1.159     www      4289:     }
                   4290: 
1.545     banghart 4291: # Free bre access to user's own portfolio contents
1.714     raeburn  4292:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4293:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4294: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4295:         my %setters;
                   4296:         my ($startblock,$endblock) = 
                   4297:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4298:         if ($startblock && $endblock) {
                   4299:             return 'B';
                   4300:         } else {
                   4301:             return 'F';
                   4302:         }
1.545     banghart 4303:     }
                   4304: 
1.762     raeburn  4305: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4306:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4307:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4308:         if (exists($env{'request.course.id'})) {
                   4309:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4310:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4311:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4312:                 my $courseprivid=$env{'request.course.id'};
                   4313:                 $courseprivid=~s/\_/\//;
                   4314:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4315:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4316:                     return $1; 
1.762     raeburn  4317:                 } else {
                   4318:                     if ($env{'request.course.sec'}) {
                   4319:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4320:                     }
                   4321:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4322:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4323:                         return $2;
                   4324:                     }
1.714     raeburn  4325:                 }
                   4326:             }
                   4327:         }
                   4328:     }
                   4329: 
1.159     www      4330: # Free bre to public access
                   4331: 
                   4332:     if ($priv eq 'bre') {
1.238     www      4333:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4334: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4335:            return 'F'; 
                   4336:         }
1.238     www      4337:         if ($copyright eq 'priv') {
                   4338:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4339: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4340: 		return '';
                   4341:             }
                   4342:         }
                   4343:         if ($copyright eq 'domain') {
                   4344:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4345: 	    unless (($env{'user.domain'} eq $1) ||
                   4346:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4347: 		return '';
                   4348:             }
1.262     matthew  4349:         }
1.620     albertel 4350:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4351:             # Library role, so allow browsing of resources in this domain.
                   4352:             return 'F';
1.238     www      4353:         }
1.341     www      4354:         if ($copyright eq 'custom') {
                   4355: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4356:         }
1.14      www      4357:     }
1.264     matthew  4358:     # Domain coordinator is trying to create a course
1.620     albertel 4359:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4360:         # uri is the requested domain in this case.
                   4361:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4362:         # a role of dc for the domain in question.
1.620     albertel 4363:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4364:     }
1.29      www      4365: 
1.52      www      4366:     my $thisallowed='';
                   4367:     my $statecond=0;
                   4368:     my $courseprivid='';
                   4369: 
                   4370: # Course
                   4371: 
1.620     albertel 4372:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4373:        $thisallowed.=$1;
                   4374:     }
1.29      www      4375: 
1.52      www      4376: # Domain
                   4377: 
1.620     albertel 4378:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4379:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4380:        $thisallowed.=$1;
                   4381:     }
1.52      www      4382: 
                   4383: # Course: uri itself is a course
1.66      www      4384:     my $courseuri=$uri;
                   4385:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4386:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4387: 
1.620     albertel 4388:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4389:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4390:        $thisallowed.=$1;
                   4391:     }
1.29      www      4392: 
1.665     albertel 4393: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4394: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4395:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4396: 	$thisallowed='';
1.671     raeburn  4397:         my ($match)=&is_on_map($uri);
                   4398:         if ($match) {
                   4399:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4400:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4401:                 $thisallowed.=$1;
                   4402:             }
                   4403:         } else {
1.705     albertel 4404:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4405:             if ($refuri) {
                   4406:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4407:                     $thisallowed='F';
1.671     raeburn  4408:                 } else {
                   4409:                     $refuri=&declutter($refuri);
                   4410:                     my ($match) = &is_on_map($refuri);
                   4411:                     if ($match) {
                   4412:                         $thisallowed='F';
                   4413:                     }
1.669     raeburn  4414:                 }
1.671     raeburn  4415:             }
                   4416:         }
1.314     www      4417:     }
1.492     albertel 4418: 
1.766     albertel 4419:     if ($priv eq 'bre'
                   4420: 	&& $thisallowed ne 'F' 
                   4421: 	&& $thisallowed ne '2'
                   4422: 	&& &is_portfolio_url($uri)) {
                   4423: 	$thisallowed = &portfolio_access($uri);
                   4424:     }
                   4425:     
1.52      www      4426: # Full access at system, domain or course-wide level? Exit.
1.29      www      4427: 
                   4428:     if ($thisallowed=~/F/) {
                   4429: 	return 'F';
                   4430:     }
                   4431: 
1.52      www      4432: # If this is generating or modifying users, exit with special codes
1.29      www      4433: 
1.643     www      4434:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4435: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4436: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4437: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4438: 	    unless ($auname) { return $thisallowed; }
                   4439: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4440: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4441: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4442: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4443: 	}
1.52      www      4444: 	return $thisallowed;
                   4445:     }
                   4446: #
1.103     harris41 4447: # Gathered so far: system, domain and course wide privileges
1.52      www      4448: #
                   4449: # Course: See if uri or referer is an individual resource that is part of 
                   4450: # the course
                   4451: 
1.620     albertel 4452:     if ($env{'request.course.id'}) {
1.232     www      4453: 
1.620     albertel 4454:        $courseprivid=$env{'request.course.id'};
                   4455:        if ($env{'request.course.sec'}) {
                   4456:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4457:        }
                   4458:        $courseprivid=~s/\_/\//;
                   4459:        my $checkreferer=1;
1.232     www      4460:        my ($match,$cond)=&is_on_map($uri);
                   4461:        if ($match) {
                   4462:            $statecond=$cond;
1.620     albertel 4463:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4464:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4465:                $thisallowed.=$1;
                   4466:                $checkreferer=0;
                   4467:            }
1.29      www      4468:        }
1.83      www      4469:        
1.148     www      4470:        if ($checkreferer) {
1.620     albertel 4471: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4472:             unless ($refuri) {
1.800     albertel 4473:                 foreach my $key (keys(%env)) {
                   4474: 		    if ($key=~/^httpref\..*\*/) {
                   4475: 			my $pattern=$key;
1.156     www      4476:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4477:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4478:                         $pattern=~s/\//\\\//g;
1.152     www      4479:                         if ($orguri=~/$pattern/) {
1.800     albertel 4480: 			    $refuri=$env{$key};
1.148     www      4481:                         }
                   4482:                     }
1.191     harris41 4483:                 }
1.148     www      4484:             }
1.232     www      4485: 
1.148     www      4486:          if ($refuri) { 
1.152     www      4487: 	  $refuri=&declutter($refuri);
1.232     www      4488:           my ($match,$cond)=&is_on_map($refuri);
                   4489:             if ($match) {
                   4490:               my $refstatecond=$cond;
1.620     albertel 4491:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4492:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4493:                   $thisallowed.=$1;
1.53      www      4494:                   $uri=$refuri;
                   4495:                   $statecond=$refstatecond;
1.52      www      4496:               }
                   4497:           }
1.148     www      4498:         }
1.29      www      4499:        }
1.52      www      4500:    }
1.29      www      4501: 
1.52      www      4502: #
1.103     harris41 4503: # Gathered now: all privileges that could apply, and condition number
1.52      www      4504: # 
                   4505: #
                   4506: # Full or no access?
                   4507: #
1.29      www      4508: 
1.52      www      4509:     if ($thisallowed=~/F/) {
                   4510: 	return 'F';
                   4511:     }
1.29      www      4512: 
1.52      www      4513:     unless ($thisallowed) {
                   4514:         return '';
                   4515:     }
1.29      www      4516: 
1.52      www      4517: # Restrictions exist, deal with them
                   4518: #
                   4519: #   C:according to course preferences
                   4520: #   R:according to resource settings
                   4521: #   L:unless locked
                   4522: #   X:according to user session state
                   4523: #
                   4524: 
                   4525: # Possibly locked functionality, check all courses
1.54      www      4526: # Locks might take effect only after 10 minutes cache expiration for other
                   4527: # courses, and 2 minutes for current course
1.52      www      4528: 
                   4529:     my $envkey;
                   4530:     if ($thisallowed=~/L/) {
1.620     albertel 4531:         foreach $envkey (keys %env) {
1.54      www      4532:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4533:                my $courseid=$2;
                   4534:                my $roleid=$1.'.'.$2;
1.92      www      4535:                $courseid=~s/^\///;
1.54      www      4536:                my $expiretime=600;
1.620     albertel 4537:                if ($env{'request.role'} eq $roleid) {
1.54      www      4538: 		  $expiretime=120;
                   4539:                }
                   4540: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4541:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4542:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4543: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4544:                }
1.620     albertel 4545:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4546:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4547: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4548:                        &log($env{'user.domain'},$env{'user.name'},
                   4549:                             $env{'user.home'},
1.57      www      4550:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4551:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4552:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4553: 		       return '';
                   4554:                    }
                   4555:                }
1.620     albertel 4556:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4557:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4558: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4559:                        &log($env{'user.domain'},$env{'user.name'},
                   4560:                             $env{'user.home'},
1.57      www      4561:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4562:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4563:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4564: 		       return '';
                   4565:                    }
                   4566:                }
                   4567: 	   }
1.29      www      4568:        }
1.52      www      4569:     }
                   4570:    
                   4571: #
                   4572: # Rest of the restrictions depend on selected course
                   4573: #
                   4574: 
1.620     albertel 4575:     unless ($env{'request.course.id'}) {
1.766     albertel 4576: 	if ($thisallowed eq 'A') {
                   4577: 	    return 'A';
1.814     raeburn  4578:         } elsif ($thisallowed eq 'B') {
                   4579:             return 'B';
1.766     albertel 4580: 	} else {
                   4581: 	    return '1';
                   4582: 	}
1.52      www      4583:     }
1.29      www      4584: 
1.52      www      4585: #
                   4586: # Now user is definitely in a course
                   4587: #
1.53      www      4588: 
                   4589: 
                   4590: # Course preferences
                   4591: 
                   4592:    if ($thisallowed=~/C/) {
1.620     albertel 4593:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4594:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4595:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4596: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4597: 	   if ($priv ne 'pch') { 
                   4598: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4599: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4600: 			$env{'request.course.id'});
                   4601: 	   }
1.237     www      4602:            return '';
                   4603:        }
                   4604: 
1.620     albertel 4605:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4606: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4607: 	   if ($priv ne 'pch') { 
                   4608: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4609: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4610: 			$env{'request.course.id'});
                   4611: 	   }
1.54      www      4612:            return '';
                   4613:        }
1.53      www      4614:    }
                   4615: 
                   4616: # Resource preferences
                   4617: 
                   4618:    if ($thisallowed=~/R/) {
1.620     albertel 4619:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4620:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4621: 	   if ($priv ne 'pch') { 
                   4622: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4623: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4624: 	   }
                   4625: 	   return '';
1.54      www      4626:        }
1.53      www      4627:    }
1.30      www      4628: 
1.246     www      4629: # Restricted by state or randomout?
1.30      www      4630: 
1.52      www      4631:    if ($thisallowed=~/X/) {
1.620     albertel 4632:       if ($env{'acc.randomout'}) {
1.579     albertel 4633: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4634:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4635:             return ''; 
                   4636:          }
1.247     www      4637:       }
                   4638:       if (&condval($statecond)) {
1.52      www      4639: 	 return '2';
                   4640:       } else {
                   4641:          return '';
                   4642:       }
                   4643:    }
1.30      www      4644: 
1.766     albertel 4645:     if ($thisallowed eq 'A') {
                   4646: 	return 'A';
1.814     raeburn  4647:     } elsif ($thisallowed eq 'B') {
                   4648:         return 'B';
1.766     albertel 4649:     }
1.52      www      4650:    return 'F';
1.232     www      4651: }
                   4652: 
1.710     albertel 4653: sub split_uri_for_cond {
                   4654:     my $uri=&deversion(&declutter(shift));
                   4655:     my @uriparts=split(/\//,$uri);
                   4656:     my $filename=pop(@uriparts);
                   4657:     my $pathname=join('/',@uriparts);
                   4658:     return ($pathname,$filename);
                   4659: }
1.232     www      4660: # --------------------------------------------------- Is a resource on the map?
                   4661: 
                   4662: sub is_on_map {
1.710     albertel 4663:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4664:     #Trying to find the conditional for the file
1.620     albertel 4665:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4666: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4667:     if ($match) {
1.289     bowersj2 4668: 	return (1,$1);
                   4669:     } else {
1.434     www      4670: 	return (0,0);
1.289     bowersj2 4671:     }
1.12      www      4672: }
                   4673: 
1.427     www      4674: # --------------------------------------------------------- Get symb from alias
                   4675: 
                   4676: sub get_symb_from_alias {
                   4677:     my $symb=shift;
                   4678:     my ($map,$resid,$url)=&decode_symb($symb);
                   4679: # Already is a symb
                   4680:     if ($url) { return $symb; }
                   4681: # Must be an alias
                   4682:     my $aliassymb='';
                   4683:     my %bighash;
1.620     albertel 4684:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4685:                             &GDBM_READER(),0640)) {
                   4686:         my $rid=$bighash{'mapalias_'.$symb};
                   4687: 	if ($rid) {
                   4688: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4689: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4690: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4691: 	}
                   4692:         untie %bighash;
                   4693:     }
                   4694:     return $aliassymb;
                   4695: }
                   4696: 
1.12      www      4697: # ----------------------------------------------------------------- Define Role
                   4698: 
                   4699: sub definerole {
                   4700:   if (allowed('mcr','/')) {
                   4701:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4702:     foreach my $role (split(':',$sysrole)) {
                   4703: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4704:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4705:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4706: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4707:                return "refused:s:$crole&$cqual"; 
                   4708:             }
                   4709:         }
1.191     harris41 4710:     }
1.800     albertel 4711:     foreach my $role (split(':',$domrole)) {
                   4712: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4713:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4714:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4715: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4716:                return "refused:d:$crole&$cqual"; 
                   4717:             }
                   4718:         }
1.191     harris41 4719:     }
1.800     albertel 4720:     foreach my $role (split(':',$courole)) {
                   4721: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4722:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4723:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4724: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4725:                return "refused:c:$crole&$cqual"; 
                   4726:             }
                   4727:         }
1.191     harris41 4728:     }
1.620     albertel 4729:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4730:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4731: 	        "rolesdef_$rolename=".
                   4732:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4733:     return reply($command,$env{'user.home'});
1.12      www      4734:   } else {
                   4735:     return 'refused';
                   4736:   }
1.105     harris41 4737: }
                   4738: 
                   4739: # ---------------- Make a metadata query against the network of library servers
                   4740: 
                   4741: sub metadata_query {
1.244     matthew  4742:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4743:     my %rhash;
1.845     albertel 4744:     my %libserv = &all_library();
1.244     matthew  4745:     my @server_list = (defined($server_array) ? @$server_array
                   4746:                                               : keys(%libserv) );
                   4747:     for my $server (@server_list) {
1.118     harris41 4748: 	unless ($custom or $customshow) {
                   4749: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4750: 	    $rhash{$server}=$reply;
                   4751: 	}
                   4752: 	else {
                   4753: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4754: 			     &escape($custom).':'.&escape($customshow),
                   4755: 			     $server);
                   4756: 	    $rhash{$server}=$reply;
                   4757: 	}
1.112     harris41 4758:     }
1.118     harris41 4759:     return \%rhash;
1.240     www      4760: }
                   4761: 
                   4762: # ----------------------------------------- Send log queries and wait for reply
                   4763: 
                   4764: sub log_query {
                   4765:     my ($uname,$udom,$query,%filters)=@_;
                   4766:     my $uhome=&homeserver($uname,$udom);
                   4767:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4768:     my $uhost=&hostname($uhome);
1.800     albertel 4769:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4770:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4771:                        $uhome);
1.479     albertel 4772:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4773:     return get_query_reply($queryid);
                   4774: }
                   4775: 
1.818     raeburn  4776: # -------------------------- Update MySQL table for portfolio file
                   4777: 
                   4778: sub update_portfolio_table {
1.821     raeburn  4779:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4780:     my $homeserver = &homeserver($uname,$udom);
                   4781:     my $queryid=
1.821     raeburn  4782:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4783:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4784:     my $reply = &get_query_reply($queryid);
                   4785:     return $reply;
                   4786: }
                   4787: 
1.899     raeburn  4788: # -------------------------- Update MySQL allusers table
                   4789: 
                   4790: sub update_allusers_table {
                   4791:     my ($uname,$udom,$names) = @_;
                   4792:     my $homeserver = &homeserver($uname,$udom);
                   4793:     my $queryid=
                   4794:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4795:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4796:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4797:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4798:                'generation='.&escape($names->{'generation'}).'%%'.
                   4799:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4800:                'id='.&escape($names->{'id'}),$homeserver);
                   4801:     my $reply = &get_query_reply($queryid);
                   4802:     return $reply;
                   4803: }
                   4804: 
1.508     raeburn  4805: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4806: 
                   4807: sub fetch_enrollment_query {
1.511     raeburn  4808:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4809:     my $homeserver;
1.547     raeburn  4810:     my $maxtries = 1;
1.508     raeburn  4811:     if ($context eq 'automated') {
                   4812:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4813:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4814:     } else {
                   4815:         $homeserver = &homeserver($cnum,$dom);
                   4816:     }
1.838     albertel 4817:     my $host=&hostname($homeserver);
1.506     raeburn  4818:     my $cmd = '';
1.800     albertel 4819:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4820:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4821:     }
                   4822:     $cmd =~ s/%%$//;
                   4823:     $cmd = &escape($cmd);
                   4824:     my $query = 'fetchenrollment';
1.620     albertel 4825:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4826:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4827:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4828:         return 'error: '.$queryid;
                   4829:     }
1.506     raeburn  4830:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4831:     my $tries = 1;
                   4832:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4833:         $reply = &get_query_reply($queryid);
                   4834:         $tries ++;
                   4835:     }
1.526     raeburn  4836:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4837:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4838:     } else {
1.901     albertel 4839:         my @responses = split(/:/,$reply);
1.515     raeburn  4840:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4841:             foreach my $line (@responses) {
                   4842:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4843:                 $$replyref{$key} = $value;
                   4844:             }
                   4845:         } else {
1.506     raeburn  4846:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4847:             foreach my $line (@responses) {
                   4848:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4849:                 $$replyref{$key} = $value;
                   4850:                 if ($value > 0) {
1.800     albertel 4851:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4852:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4853:                         my $destname = $pathname.'/'.$filename;
                   4854:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4855:                         if ($xml_classlist =~ /^error/) {
                   4856:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4857:                         } else {
1.506     raeburn  4858:                             if ( open(FILE,">$destname") ) {
                   4859:                                 print FILE &unescape($xml_classlist);
                   4860:                                 close(FILE);
1.526     raeburn  4861:                             } else {
                   4862:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4863:                             }
                   4864:                         }
                   4865:                     }
                   4866:                 }
                   4867:             }
                   4868:         }
                   4869:         return 'ok';
                   4870:     }
                   4871:     return 'error';
                   4872: }
                   4873: 
1.242     www      4874: sub get_query_reply {
                   4875:     my $queryid=shift;
1.240     www      4876:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4877:     my $reply='';
                   4878:     for (1..100) {
                   4879: 	sleep 2;
                   4880:         if (-e $replyfile.'.end') {
1.448     albertel 4881: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4882: 		$reply = join('',<$fh>);
                   4883: 		close($fh);
1.240     www      4884: 	   } else { return 'error: reply_file_error'; }
1.242     www      4885:            return &unescape($reply);
                   4886: 	}
1.240     www      4887:     }
1.242     www      4888:     return 'timeout:'.$queryid;
1.240     www      4889: }
                   4890: 
                   4891: sub courselog_query {
1.241     www      4892: #
                   4893: # possible filters:
                   4894: # url: url or symb
                   4895: # username
                   4896: # domain
                   4897: # action: view, submit, grade
                   4898: # start: timestamp
                   4899: # end: timestamp
                   4900: #
1.240     www      4901:     my (%filters)=@_;
1.620     albertel 4902:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4903:     if ($filters{'url'}) {
                   4904: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4905:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4906:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4907:     }
1.620     albertel 4908:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4909:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4910:     return &log_query($cname,$cdom,'courselog',%filters);
                   4911: }
                   4912: 
                   4913: sub userlog_query {
1.858     raeburn  4914: #
                   4915: # possible filters:
                   4916: # action: log check role
                   4917: # start: timestamp
                   4918: # end: timestamp
                   4919: #
1.240     www      4920:     my ($uname,$udom,%filters)=@_;
                   4921:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4922: }
                   4923: 
1.506     raeburn  4924: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4925: 
                   4926: sub auto_run {
1.508     raeburn  4927:     my ($cnum,$cdom) = @_;
1.876     raeburn  4928:     my $response = 0;
                   4929:     my $settings;
                   4930:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4931:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4932:         $settings = $domconfig{'autoenroll'};
                   4933:         if ($settings->{'run'} eq '1') {
                   4934:             $response = 1;
                   4935:         }
                   4936:     } else {
1.934     raeburn  4937:         my $homeserver;
                   4938:         if (&is_course($cdom,$cnum)) {
                   4939:             $homeserver = &homeserver($cnum,$cdom);
                   4940:         } else {
                   4941:             $homeserver = &domain($cdom,'primary');
                   4942:         }
                   4943:         if ($homeserver ne 'no_host') {
                   4944:             $response = &reply('autorun:'.$cdom,$homeserver);
                   4945:         }
1.876     raeburn  4946:     }
1.506     raeburn  4947:     return $response;
                   4948: }
1.776     albertel 4949: 
1.506     raeburn  4950: sub auto_get_sections {
1.508     raeburn  4951:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4952:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4953:     my @secs = ();
1.511     raeburn  4954:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4955:     unless ($response eq 'refused') {
1.901     albertel 4956:         @secs = split(/:/,$response);
1.506     raeburn  4957:     }
                   4958:     return @secs;
                   4959: }
1.776     albertel 4960: 
1.506     raeburn  4961: sub auto_new_course {
1.508     raeburn  4962:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4963:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4964:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4965:     return $response;
                   4966: }
1.776     albertel 4967: 
1.506     raeburn  4968: sub auto_validate_courseID {
1.508     raeburn  4969:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4970:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4971:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4972:     return $response;
                   4973: }
1.776     albertel 4974: 
1.506     raeburn  4975: sub auto_create_password {
1.873     raeburn  4976:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4977:     my ($homeserver,$response);
1.506     raeburn  4978:     my $create_passwd = 0;
                   4979:     my $authchk = '';
1.873     raeburn  4980:     if ($udom =~ /^$match_domain$/) {
                   4981:         $homeserver = &domain($udom,'primary');
                   4982:     }
                   4983:     if ($homeserver eq '') {
                   4984:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4985:             $homeserver = &homeserver($cnum,$cdom);
                   4986:         }
                   4987:     }
                   4988:     if ($homeserver eq '') {
                   4989:         $authchk = 'nodomain';
1.506     raeburn  4990:     } else {
1.873     raeburn  4991:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4992:         if ($response eq 'refused') {
                   4993:             $authchk = 'refused';
                   4994:         } else {
1.901     albertel 4995:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4996:         }
1.506     raeburn  4997:     }
                   4998:     return ($authparam,$create_passwd,$authchk);
                   4999: }
                   5000: 
1.706     raeburn  5001: sub auto_photo_permission {
                   5002:     my ($cnum,$cdom,$students) = @_;
                   5003:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5004:     my ($outcome,$perm_reqd,$conditions) = 
                   5005: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5006:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5007: 	return (undef,undef);
                   5008:     }
1.706     raeburn  5009:     return ($outcome,$perm_reqd,$conditions);
                   5010: }
                   5011: 
                   5012: sub auto_checkphotos {
                   5013:     my ($uname,$udom,$pid) = @_;
                   5014:     my $homeserver = &homeserver($uname,$udom);
                   5015:     my ($result,$resulttype);
                   5016:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5017: 				   &escape($uname).':'.&escape($pid),
                   5018: 				   $homeserver));
1.709     albertel 5019:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5020: 	return (undef,undef);
                   5021:     }
1.706     raeburn  5022:     if ($outcome) {
                   5023:         ($result,$resulttype) = split(/:/,$outcome);
                   5024:     } 
                   5025:     return ($result,$resulttype);
                   5026: }
                   5027: 
                   5028: sub auto_photochoice {
                   5029:     my ($cnum,$cdom) = @_;
                   5030:     my $homeserver = &homeserver($cnum,$cdom);
                   5031:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5032: 						       &escape($cdom),
                   5033: 						       $homeserver)));
1.709     albertel 5034:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5035: 	return (undef,undef);
                   5036:     }
1.706     raeburn  5037:     return ($update,$comment);
                   5038: }
                   5039: 
                   5040: sub auto_photoupdate {
                   5041:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5042:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5043:     my $host=&hostname($homeserver);
1.706     raeburn  5044:     my $cmd = '';
                   5045:     my $maxtries = 1;
1.800     albertel 5046:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5047:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5048:     }
                   5049:     $cmd =~ s/%%$//;
                   5050:     $cmd = &escape($cmd);
                   5051:     my $query = 'institutionalphotos';
                   5052:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5053:     unless ($queryid=~/^\Q$host\E\_/) {
                   5054:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5055:         return 'error: '.$queryid;
                   5056:     }
                   5057:     my $reply = &get_query_reply($queryid);
                   5058:     my $tries = 1;
                   5059:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5060:         $reply = &get_query_reply($queryid);
                   5061:         $tries ++;
                   5062:     }
                   5063:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5064:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5065:     } else {
                   5066:         my @responses = split(/:/,$reply);
                   5067:         my $outcome = shift(@responses); 
                   5068:         foreach my $item (@responses) {
                   5069:             my ($key,$value) = split(/=/,$item);
                   5070:             $$photo{$key} = $value;
                   5071:         }
                   5072:         return $outcome;
                   5073:     }
                   5074:     return 'error';
                   5075: }
                   5076: 
1.521     raeburn  5077: sub auto_instcode_format {
1.793     albertel 5078:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5079: 	$cat_order) = @_;
1.521     raeburn  5080:     my $courses = '';
1.772     raeburn  5081:     my @homeservers;
1.521     raeburn  5082:     if ($caller eq 'global') {
1.841     albertel 5083: 	my %servers = &get_servers($codedom,'library');
                   5084: 	foreach my $tryserver (keys(%servers)) {
                   5085: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5086: 		push(@homeservers,$tryserver);
                   5087: 	    }
1.584     raeburn  5088:         }
1.521     raeburn  5089:     } else {
1.772     raeburn  5090:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5091:     }
1.793     albertel 5092:     foreach my $code (keys(%{$instcodes})) {
                   5093:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5094:     }
                   5095:     chop($courses);
1.772     raeburn  5096:     my $ok_response = 0;
                   5097:     my $response;
                   5098:     while (@homeservers > 0 && $ok_response == 0) {
                   5099:         my $server = shift(@homeservers); 
                   5100:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5101:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5102:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5103: 		split(/:/,$response);
1.772     raeburn  5104:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5105:             push(@{$codetitles},&str2array($codetitles_str));
                   5106:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5107:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5108:             $ok_response = 1;
                   5109:         }
                   5110:     }
                   5111:     if ($ok_response) {
1.521     raeburn  5112:         return 'ok';
1.772     raeburn  5113:     } else {
                   5114:         return $response;
1.521     raeburn  5115:     }
                   5116: }
                   5117: 
1.792     raeburn  5118: sub auto_instcode_defaults {
                   5119:     my ($domain,$returnhash,$code_order) = @_;
                   5120:     my @homeservers;
1.841     albertel 5121: 
                   5122:     my %servers = &get_servers($domain,'library');
                   5123:     foreach my $tryserver (keys(%servers)) {
                   5124: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5125: 	    push(@homeservers,$tryserver);
                   5126: 	}
1.792     raeburn  5127:     }
1.841     albertel 5128: 
1.792     raeburn  5129:     my $response;
1.841     albertel 5130:     foreach my $server (@homeservers) {
1.792     raeburn  5131:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5132:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5133: 	
                   5134: 	foreach my $pair (split(/\&/,$response)) {
                   5135: 	    my ($name,$value)=split(/\=/,$pair);
                   5136: 	    if ($name eq 'code_order') {
                   5137: 		@{$code_order} = split(/\&/,&unescape($value));
                   5138: 	    } else {
                   5139: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5140: 	    }
                   5141: 	}
                   5142: 	return 'ok';
1.792     raeburn  5143:     }
1.841     albertel 5144: 
                   5145:     return $response;
1.792     raeburn  5146: } 
                   5147: 
1.777     albertel 5148: sub auto_validate_class_sec {
1.918     raeburn  5149:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5150:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5151:     my $ownerlist;
                   5152:     if (ref($owners) eq 'ARRAY') {
                   5153:         $ownerlist = join(',',@{$owners});
                   5154:     } else {
                   5155:         $ownerlist = $owners;
                   5156:     }
1.773     raeburn  5157:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5158:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5159:     return $response;
                   5160: }
                   5161: 
1.679     raeburn  5162: # ------------------------------------------------------- Course Group routines
                   5163: 
                   5164: sub get_coursegroups {
1.809     raeburn  5165:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5166:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5167: }
                   5168: 
1.679     raeburn  5169: sub modify_coursegroup {
                   5170:     my ($cdom,$cnum,$groupsettings) = @_;
                   5171:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5172: }
                   5173: 
1.809     raeburn  5174: sub toggle_coursegroup_status {
                   5175:     my ($cdom,$cnum,$group,$action) = @_;
                   5176:     my ($from_namespace,$to_namespace);
                   5177:     if ($action eq 'delete') {
                   5178:         $from_namespace = 'coursegroups';
                   5179:         $to_namespace = 'deleted_groups';
                   5180:     } else {
                   5181:         $from_namespace = 'deleted_groups';
                   5182:         $to_namespace = 'coursegroups';
                   5183:     }
                   5184:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5185:     if (my $tmp = &error(%curr_group)) {
                   5186:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5187:         return ('read error',$tmp);
                   5188:     } else {
                   5189:         my %savedsettings = %curr_group; 
1.809     raeburn  5190:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5191:         my $deloutcome;
                   5192:         if ($result eq 'ok') {
1.809     raeburn  5193:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5194:         } else {
                   5195:             return ('write error',$result);
                   5196:         }
                   5197:         if ($deloutcome eq 'ok') {
                   5198:             return 'ok';
                   5199:         } else {
                   5200:             return ('delete error',$deloutcome);
                   5201:         }
                   5202:     }
                   5203: }
                   5204: 
1.679     raeburn  5205: sub modify_group_roles {
                   5206:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5207:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5208:     my $role = 'gr/'.&escape($userprivs);
                   5209:     my ($uname,$udom) = split(/:/,$user);
                   5210:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5211:     if ($result eq 'ok') {
                   5212:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5213:     }
1.679     raeburn  5214:     return $result;
                   5215: }
                   5216: 
                   5217: sub modify_coursegroup_membership {
                   5218:     my ($cdom,$cnum,$membership) = @_;
                   5219:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5220:     return $result;
                   5221: }
                   5222: 
1.682     raeburn  5223: sub get_active_groups {
                   5224:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5225:     my $now = time;
                   5226:     my %groups = ();
                   5227:     foreach my $key (keys(%env)) {
1.811     albertel 5228:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5229:             my ($start,$end) = split(/\./,$env{$key});
                   5230:             if (($end!=0) && ($end<$now)) { next; }
                   5231:             if (($start!=0) && ($start>$now)) { next; }
                   5232:             if ($1 eq $cdom && $2 eq $cnum) {
                   5233:                 $groups{$3} = $env{$key} ;
                   5234:             }
                   5235:         }
                   5236:     }
                   5237:     return %groups;
                   5238: }
                   5239: 
1.683     raeburn  5240: sub get_group_membership {
                   5241:     my ($cdom,$cnum,$group) = @_;
                   5242:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5243: }
                   5244: 
                   5245: sub get_users_groups {
                   5246:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5247:     my @usersgroups;
1.683     raeburn  5248:     my $cachetime=1800;
                   5249: 
                   5250:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5251:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5252:     if (defined($cached)) {
1.734     albertel 5253:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5254:     } else {  
                   5255:         $grouplist = '';
1.816     raeburn  5256:         my $courseurl = &courseid_to_courseurl($courseid);
                   5257:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5258:         my $access_end = $env{'course.'.$courseid.
                   5259:                               '.default_enrollment_end_date'};
                   5260:         my $now = time;
                   5261:         foreach my $key (keys(%roleshash)) {
                   5262:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5263:                 my $group = $1;
                   5264:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5265:                     my $start = $2;
                   5266:                     my $end = $1;
                   5267:                     if ($start == -1) { next; } # deleted from group
                   5268:                     if (($start!=0) && ($start>$now)) { next; }
                   5269:                     if (($end!=0) && ($end<$now)) {
                   5270:                         if ($access_end && $access_end < $now) {
                   5271:                             if ($access_end - $end < 86400) {
                   5272:                                 push(@usersgroups,$group);
1.733     raeburn  5273:                             }
                   5274:                         }
1.817     raeburn  5275:                         next;
1.733     raeburn  5276:                     }
1.817     raeburn  5277:                     push(@usersgroups,$group);
1.683     raeburn  5278:                 }
                   5279:             }
                   5280:         }
1.817     raeburn  5281:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5282:         $grouplist = join(':',@usersgroups);
                   5283:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5284:     }
1.733     raeburn  5285:     return @usersgroups;
1.683     raeburn  5286: }
                   5287: 
                   5288: sub devalidate_getgroups_cache {
                   5289:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5290:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5291: 
1.683     raeburn  5292:     my $hashid="$udom:$uname:$courseid";
                   5293:     &devalidate_cache_new('getgroups',$hashid);
                   5294: }
                   5295: 
1.12      www      5296: # ------------------------------------------------------------------ Plain Text
                   5297: 
                   5298: sub plaintext {
1.742     raeburn  5299:     my ($short,$type,$cid) = @_;
1.758     albertel 5300:     if ($short =~ /^cr/) {
                   5301: 	return (split('/',$short))[-1];
                   5302:     }
1.742     raeburn  5303:     if (!defined($cid)) {
                   5304:         $cid = $env{'request.course.id'};
                   5305:     }
                   5306:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5307:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5308:                                           '.plaintext'});
                   5309:     }
                   5310:     my %rolenames = (
                   5311:                       Course => 'std',
                   5312:                       Group => 'alt1',
                   5313:                     );
                   5314:     if (defined($type) && 
                   5315:          defined($rolenames{$type}) && 
                   5316:          defined($prp{$short}{$rolenames{$type}})) {
                   5317:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5318:     } else {
                   5319:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5320:     }
1.12      www      5321: }
                   5322: 
                   5323: # ----------------------------------------------------------------- Assign Role
                   5324: 
                   5325: sub assignrole {
1.947     raeburn  5326:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
1.21      www      5327:     my $mrole;
                   5328:     if ($role =~ /^cr\//) {
1.393     www      5329:         my $cwosec=$url;
1.811     albertel 5330:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5331: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5332:            &logthis('Refused custom assignrole: '.
                   5333:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5334: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5335:            return 'refused'; 
                   5336:         }
1.21      www      5337:         $mrole='cr';
1.678     raeburn  5338:     } elsif ($role =~ /^gr\//) {
                   5339:         my $cwogrp=$url;
1.811     albertel 5340:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5341:         unless (&allowed('mdg',$cwogrp)) {
                   5342:             &logthis('Refused group assignrole: '.
                   5343:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5344:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5345:             return 'refused';
                   5346:         }
                   5347:         $mrole='gr';
1.21      www      5348:     } else {
1.82      www      5349:         my $cwosec=$url;
1.811     albertel 5350:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5351:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5352:             my $refused;
                   5353:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5354:                 if (!(&allowed('c'.$role,$url))) {
                   5355:                     $refused = 1;
                   5356:                 }
                   5357:             } else {
                   5358:                 $refused = 1;
                   5359:             }
1.947     raeburn  5360:             if ($refused) {
                   5361:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5362:                     $refused = '';
                   5363:                 } else {
                   5364:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5365:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5366: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5367:                     return 'refused';
                   5368:                 }
1.932     raeburn  5369:             }
1.104     www      5370:         }
1.21      www      5371:         $mrole=$role;
                   5372:     }
1.620     albertel 5373:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5374:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5375:     if ($end) { $command.='_'.$end; }
1.21      www      5376:     if ($start) {
                   5377: 	if ($end) { 
1.81      www      5378:            $command.='_'.$start; 
1.21      www      5379:         } else {
1.81      www      5380:            $command.='_0_'.$start;
1.21      www      5381:         }
                   5382:     }
1.739     raeburn  5383:     my $origstart = $start;
                   5384:     my $origend = $end;
1.357     www      5385: # actually delete
                   5386:     if ($deleteflag) {
1.373     www      5387: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5388: # modify command to delete the role
1.620     albertel 5389:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5390:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5391: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5392: # set start and finish to negative values for userrolelog
                   5393:            $start=-1;
                   5394:            $end=-1;
                   5395:         }
                   5396:     }
                   5397: # send command
1.349     www      5398:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5399: # log new user role if status is ok
1.349     www      5400:     if ($answer eq 'ok') {
1.663     raeburn  5401: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5402: # for course roles, perform group memberships changes triggered by role change.
                   5403:         unless ($role =~ /^gr/) {
                   5404:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5405:                                              $origstart);
                   5406:         }
1.349     www      5407:     }
                   5408:     return $answer;
1.169     harris41 5409: }
                   5410: 
                   5411: # -------------------------------------------------- Modify user authentication
1.197     www      5412: # Overrides without validation
                   5413: 
1.169     harris41 5414: sub modifyuserauth {
                   5415:     my ($udom,$uname,$umode,$upass)=@_;
                   5416:     my $uhome=&homeserver($uname,$udom);
1.197     www      5417:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5418:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5419:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5420:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5421:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5422: 		     &escape($upass),$uhome);
1.620     albertel 5423:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5424:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5425:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5426:     &log($udom,,$uname,$uhome,
1.620     albertel 5427:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5428:                                      $env{'user.name'}.', '.$umode.
1.197     www      5429:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5430:     unless ($reply eq 'ok') {
1.197     www      5431:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5432: 	return 'error: '.$reply;
                   5433:     }   
1.170     harris41 5434:     return 'ok';
1.80      www      5435: }
                   5436: 
1.81      www      5437: # --------------------------------------------------------------- Modify a user
1.80      www      5438: 
1.81      www      5439: sub modifyuser {
1.206     matthew  5440:     my ($udom,    $uname, $uid,
                   5441:         $umode,   $upass, $first,
                   5442:         $middle,  $last,  $gene,
1.387     www      5443:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5444:     $udom= &LONCAPA::clean_domain($udom);
                   5445:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5446:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5447:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5448: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5449:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5450:                                      ' desiredhome not specified'). 
1.620     albertel 5451:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5452:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5453:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5454: # ----------------------------------------------------------------- Create User
1.406     albertel 5455:     if (($uhome eq 'no_host') && 
                   5456: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5457:         my $unhome='';
1.844     albertel 5458:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5459:             $unhome = $desiredhome;
1.620     albertel 5460: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5461: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5462:         } else { # load balancing routine for determining $unhome
1.81      www      5463:             my $loadm=10000000;
1.841     albertel 5464: 	    my %servers = &get_servers($udom,'library');
                   5465: 	    foreach my $tryserver (keys(%servers)) {
                   5466: 		my $answer=reply('load',$tryserver);
                   5467: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5468: 		    $loadm=$answer;
                   5469: 		    $unhome=$tryserver;
                   5470: 		}
1.80      www      5471: 	    }
                   5472:         }
                   5473:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5474: 	    return 'error: unable to find a home server for '.$uname.
                   5475:                    ' in domain '.$udom;
1.80      www      5476:         }
                   5477:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5478:                          &escape($upass),$unhome);
                   5479: 	unless ($reply eq 'ok') {
                   5480:             return 'error: '.$reply;
                   5481:         }   
1.230     stredwic 5482:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5483:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5484: 	    return 'error: unable verify users home machine.';
1.80      www      5485:         }
1.209     matthew  5486:     }   # End of creation of new user
1.80      www      5487: # ---------------------------------------------------------------------- Add ID
                   5488:     if ($uid) {
                   5489:        $uid=~tr/A-Z/a-z/;
                   5490:        my %uidhash=&idrget($udom,$uname);
1.196     www      5491:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5492:          && (!$forceid)) {
1.80      www      5493: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5494: 	      return 'error: user id "'.$uid.'" does not match '.
                   5495:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5496:           }
                   5497:        } else {
                   5498: 	  &idput($udom,($uname => $uid));
                   5499:        }
                   5500:     }
                   5501: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5502:     my @tmp=&get('environment',
1.899     raeburn  5503: 		   ['firstname','middlename','lastname','generation','id',
                   5504:                     'permanentemail'],
1.134     albertel 5505: 		   $udom,$uname);
1.313     matthew  5506:     my %names;
                   5507:     if ($tmp[0] =~ m/^error:.*/) { 
                   5508:         %names=(); 
                   5509:     } else {
                   5510:         %names = @tmp;
                   5511:     }
1.388     www      5512: #
                   5513: # Make sure to not trash student environment if instructor does not bother
                   5514: # to supply name and email information
                   5515: #
                   5516:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5517:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5518:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5519:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5520:     if ($email) {
                   5521:        $email=~s/[^\w\@\.\-\,]//gs;
                   5522:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5523: 			   $names{'critnotification'} = $email;
                   5524: 			   $names{'permanentemail'} = $email; }
                   5525:     }
1.899     raeburn  5526:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5527:     my $reply = &put('environment', \%names, $udom,$uname);
                   5528:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5529:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5530:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5531:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5532:              $umode.', '.$first.', '.$middle.', '.
                   5533: 	     $last.', '.$gene.' by '.
1.620     albertel 5534:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5535:     return 'ok';
1.80      www      5536: }
                   5537: 
1.81      www      5538: # -------------------------------------------------------------- Modify student
1.80      www      5539: 
1.81      www      5540: sub modifystudent {
                   5541:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5542:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5543:     if (!$cid) {
1.620     albertel 5544: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5545: 	    return 'not_in_class';
                   5546: 	}
1.80      www      5547:     }
                   5548: # --------------------------------------------------------------- Make the user
1.81      www      5549:     my $reply=&modifyuser
1.209     matthew  5550: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5551:          $desiredhome,$email);
1.80      www      5552:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5553:     # This will cause &modify_student_enrollment to get the uid from the
                   5554:     # students environment
                   5555:     $uid = undef if (!$forceid);
1.455     albertel 5556:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5557: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5558:     return $reply;
                   5559: }
                   5560: 
                   5561: sub modify_student_enrollment {
1.947     raeburn  5562:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
1.455     albertel 5563:     my ($cdom,$cnum,$chome);
                   5564:     if (!$cid) {
1.620     albertel 5565: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5566: 	    return 'not_in_class';
                   5567: 	}
1.620     albertel 5568: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5569: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5570:     } else {
                   5571: 	($cdom,$cnum)=split(/_/,$cid);
                   5572:     }
1.620     albertel 5573:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5574:     if (!$chome) {
1.457     raeburn  5575: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5576:     }
1.455     albertel 5577:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5578:     # Make sure the user exists
1.81      www      5579:     my $uhome=&homeserver($uname,$udom);
                   5580:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5581: 	return 'error: no such user';
                   5582:     }
1.297     matthew  5583:     # Get student data if we were not given enough information
                   5584:     if (!defined($first)  || $first  eq '' || 
                   5585:         !defined($last)   || $last   eq '' || 
                   5586:         !defined($uid)    || $uid    eq '' || 
                   5587:         !defined($middle) || $middle eq '' || 
                   5588:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5589:         # They did not supply us with enough data to enroll the student, so
                   5590:         # we need to pick up more information.
1.297     matthew  5591:         my %tmp = &get('environment',
1.294     matthew  5592:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5593:                        ,$udom,$uname);
                   5594: 
1.800     albertel 5595:         #foreach my $key (keys(%tmp)) {
                   5596:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5597:         #}
1.294     matthew  5598:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5599:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5600:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5601:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5602:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5603:     }
1.556     albertel 5604:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5605:     my $reply=cput('classlist',
                   5606: 		   {"$uname:$udom" => 
1.515     raeburn  5607: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5608: 		   $cdom,$cnum);
1.81      www      5609:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5610: 	return 'error: '.$reply;
1.652     albertel 5611:     } else {
                   5612: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5613:     }
1.297     matthew  5614:     # Add student role to user
1.83      www      5615:     my $uurl='/'.$cid;
1.81      www      5616:     $uurl=~s/\_/\//g;
                   5617:     if ($usec) {
                   5618: 	$uurl.='/'.$usec;
                   5619:     }
1.947     raeburn  5620:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
1.21      www      5621: }
                   5622: 
1.556     albertel 5623: sub format_name {
                   5624:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5625:     my $name;
                   5626:     if ($first ne 'lastname') {
                   5627: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5628:     } else {
                   5629: 	if ($lastname=~/\S/) {
                   5630: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5631: 	    $name=~s/\s+,/,/;
                   5632: 	} else {
                   5633: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5634: 	}
                   5635:     }
                   5636:     $name=~s/^\s+//;
                   5637:     $name=~s/\s+$//;
                   5638:     $name=~s/\s+/ /g;
                   5639:     return $name;
                   5640: }
                   5641: 
1.84      www      5642: # ------------------------------------------------- Write to course preferences
                   5643: 
                   5644: sub writecoursepref {
                   5645:     my ($courseid,%prefs)=@_;
                   5646:     $courseid=~s/^\///;
                   5647:     $courseid=~s/\_/\//g;
                   5648:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5649:     my $chome=homeserver($cnum,$cdomain);
                   5650:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5651: 	return 'error: no such course';
                   5652:     }
                   5653:     my $cstring='';
1.800     albertel 5654:     foreach my $pref (keys(%prefs)) {
                   5655: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5656:     }
1.84      www      5657:     $cstring=~s/\&$//;
                   5658:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5659: }
                   5660: 
                   5661: # ---------------------------------------------------------- Make/modify course
                   5662: 
                   5663: sub createcourse {
1.741     raeburn  5664:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5665:         $course_owner,$crstype)=@_;
1.84      www      5666:     $url=&declutter($url);
                   5667:     my $cid='';
1.264     matthew  5668:     unless (&allowed('ccc',$udom)) {
1.84      www      5669:         return 'refused';
                   5670:     }
                   5671: # ------------------------------------------------------------------- Create ID
1.674     www      5672:    my $uname=int(1+rand(9)).
                   5673:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5674:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5675:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5676: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5677:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5678:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5679:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5680:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5681:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5682:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5683:            return 'error: unable to generate unique course-ID';
                   5684:        } 
                   5685:    }
1.264     matthew  5686: # ------------------------------------------------ Check supplied server name
1.620     albertel 5687:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5688:     if (! &is_library($course_server)) {
1.264     matthew  5689:         return 'error:bad server name '.$course_server;
                   5690:     }
1.84      www      5691: # ------------------------------------------------------------- Make the course
                   5692:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5693:                       $course_server);
1.84      www      5694:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5695:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5696:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5697: 	return 'error: no such course';
                   5698:     }
1.271     www      5699: # ----------------------------------------------------------------- Course made
1.516     raeburn  5700: # log existence
1.918     raeburn  5701:     my $newcourse = {
                   5702:                     $udom.'_'.$uname => {
1.921     raeburn  5703:                                      description => $description,
                   5704:                                      inst_code   => $inst_code,
                   5705:                                      owner       => $course_owner,
                   5706:                                      type        => $crstype,
1.918     raeburn  5707:                                                 },
                   5708:                     };
1.921     raeburn  5709:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5710: # set toplevel url
1.271     www      5711:     my $topurl=$url;
                   5712:     unless ($nonstandard) {
                   5713: # ------------------------------------------ For standard courses, make top url
                   5714:         my $mapurl=&clutter($url);
1.278     www      5715:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5716:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5717: <map>
                   5718: <resource id="1" type="start"></resource>
                   5719: <resource id="2" src="$mapurl"></resource>
                   5720: <resource id="3" type="finish"></resource>
                   5721: <link index="1" from="1" to="2"></link>
                   5722: <link index="2" from="2" to="3"></link>
                   5723: </map>
                   5724: ENDINITMAP
                   5725:         $topurl=&declutter(
1.638     albertel 5726:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5727:                           );
                   5728:     }
                   5729: # ----------------------------------------------------------- Write preferences
1.84      www      5730:     &writecoursepref($udom.'_'.$uname,
                   5731:                      ('description' => $description,
1.271     www      5732:                       'url'         => $topurl));
1.84      www      5733:     return '/'.$udom.'/'.$uname;
                   5734: }
                   5735: 
1.813     albertel 5736: sub is_course {
                   5737:     my ($cdom,$cnum) = @_;
                   5738:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5739: 				undef,'.');
1.813     albertel 5740:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5741:         return 1;
                   5742:     }
                   5743:     return 0;
                   5744: }
                   5745: 
1.21      www      5746: # ---------------------------------------------------------- Assign Custom Role
                   5747: 
                   5748: sub assigncustomrole {
1.357     www      5749:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5750:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5751:                        $end,$start,$deleteflag);
1.21      www      5752: }
                   5753: 
                   5754: # ----------------------------------------------------------------- Revoke Role
                   5755: 
                   5756: sub revokerole {
1.357     www      5757:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5758:     my $now=time;
1.357     www      5759:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5760: }
                   5761: 
                   5762: # ---------------------------------------------------------- Revoke Custom Role
                   5763: 
                   5764: sub revokecustomrole {
1.357     www      5765:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5766:     my $now=time;
1.357     www      5767:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5768:            $deleteflag);
1.17      www      5769: }
                   5770: 
1.533     banghart 5771: # ------------------------------------------------------------ Disk usage
1.535     albertel 5772: sub diskusage {
1.533     banghart 5773:     my ($udom,$uname,$directoryRoot)=@_;
                   5774:     $directoryRoot =~ s/\/$//;
1.535     albertel 5775:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5776:     return $listing;
1.512     banghart 5777: }
                   5778: 
1.566     banghart 5779: sub is_locked {
                   5780:     my ($file_name, $domain, $user) = @_;
                   5781:     my @check;
                   5782:     my $is_locked;
                   5783:     push @check, $file_name;
1.613     albertel 5784:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5785: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5786:     my ($tmp)=keys(%locked);
                   5787:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5788:     
1.566     banghart 5789:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5790:         $is_locked = 'false';
                   5791:         foreach my $entry (@{$locked{$file_name}}) {
                   5792:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5793:                $is_locked = 'true';
                   5794:                last;
1.745     raeburn  5795:            }
                   5796:        }
1.566     banghart 5797:     } else {
                   5798:         $is_locked = 'false';
                   5799:     }
                   5800: }
                   5801: 
1.759     albertel 5802: sub declutter_portfile {
                   5803:     my ($file) = @_;
1.833     albertel 5804:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5805:     return $file;
                   5806: }
                   5807: 
1.559     banghart 5808: # ------------------------------------------------------------- Mark as Read Only
                   5809: 
                   5810: sub mark_as_readonly {
                   5811:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5812:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5813:     my ($tmp)=keys(%current_permissions);
                   5814:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5815:     foreach my $file (@{$files}) {
1.759     albertel 5816: 	$file = &declutter_portfile($file);
1.561     banghart 5817:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5818:     }
1.613     albertel 5819:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5820:     return;
                   5821: }
                   5822: 
1.572     banghart 5823: # ------------------------------------------------------------Save Selected Files
                   5824: 
                   5825: sub save_selected_files {
                   5826:     my ($user, $path, @files) = @_;
                   5827:     my $filename = $user."savedfiles";
1.573     banghart 5828:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5829:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5830:     foreach my $file (@files) {
1.620     albertel 5831:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5832:     }
                   5833:     foreach my $file (@other_files) {
1.574     banghart 5834:         print (OUT $file."\n");
1.572     banghart 5835:     }
1.574     banghart 5836:     close (OUT);
1.572     banghart 5837:     return 'ok';
                   5838: }
                   5839: 
1.574     banghart 5840: sub clear_selected_files {
                   5841:     my ($user) = @_;
                   5842:     my $filename = $user."savedfiles";
                   5843:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5844:     print (OUT undef);
                   5845:     close (OUT);
                   5846:     return ("ok");    
                   5847: }
                   5848: 
1.572     banghart 5849: sub files_in_path {
                   5850:     my ($user, $path) = @_;
                   5851:     my $filename = $user."savedfiles";
                   5852:     my %return_files;
1.574     banghart 5853:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5854:     while (my $line_in = <IN>) {
1.574     banghart 5855:         chomp ($line_in);
                   5856:         my @paths_and_file = split (m!/!, $line_in);
                   5857:         my $file_part = pop (@paths_and_file);
                   5858:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5859:         $path_part.='/';
                   5860:         my $path_and_file = $path_part.$file_part;
                   5861:         if ($path_part eq $path) {
                   5862:             $return_files{$file_part}= 'selected';
                   5863:         }
                   5864:     }
1.574     banghart 5865:     close (IN);
                   5866:     return (\%return_files);
1.572     banghart 5867: }
                   5868: 
                   5869: # called in portfolio select mode, to show files selected NOT in current directory
                   5870: sub files_not_in_path {
                   5871:     my ($user, $path) = @_;
                   5872:     my $filename = $user."savedfiles";
                   5873:     my @return_files;
                   5874:     my $path_part;
1.800     albertel 5875:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5876:     while (my $line = <IN>) {
1.572     banghart 5877:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5878:         my @paths_and_file = split(m|/|, $line);
                   5879:         my $file_part = pop(@paths_and_file);
                   5880:         chomp($file_part);
                   5881:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5882:         $path_part .= '/';
                   5883:         my $path_and_file = $path_part.$file_part;
                   5884:         if ($path_part ne $path) {
1.800     albertel 5885:             push(@return_files, ($path_and_file));
1.572     banghart 5886:         }
                   5887:     }
1.800     albertel 5888:     close(OUT);
1.574     banghart 5889:     return (@return_files);
1.572     banghart 5890: }
                   5891: 
1.745     raeburn  5892: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5893: 
1.745     raeburn  5894: sub get_portfile_permissions {
                   5895:     my ($domain,$user) = @_;
1.613     albertel 5896:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5897:     my ($tmp)=keys(%current_permissions);
                   5898:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5899:     return \%current_permissions;
                   5900: }
                   5901: 
                   5902: #---------------------------------------------Get portfolio file access controls
                   5903: 
1.749     raeburn  5904: sub get_access_controls {
1.745     raeburn  5905:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5906:     my %access;
                   5907:     my $real_file = $file;
                   5908:     $file =~ s/\.meta$//;
1.745     raeburn  5909:     if (defined($file)) {
1.749     raeburn  5910:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5911:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5912:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5913:             }
                   5914:         }
1.745     raeburn  5915:     } else {
1.749     raeburn  5916:         foreach my $key (keys(%{$current_permissions})) {
                   5917:             if ($key =~ /\0accesscontrol$/) {
                   5918:                 if (defined($group)) {
                   5919:                     if ($key !~ m-^\Q$group\E/-) {
                   5920:                         next;
                   5921:                     }
                   5922:                 }
                   5923:                 my ($fullpath) = split(/\0/,$key);
                   5924:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5925:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5926:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5927:                     }
                   5928:                 }
                   5929:             }
                   5930:         }
                   5931:     }
                   5932:     return %access;
                   5933: }
                   5934: 
                   5935: sub modify_access_controls {
                   5936:     my ($file_name,$changes,$domain,$user)=@_;
                   5937:     my ($outcome,$deloutcome);
                   5938:     my %store_permissions;
                   5939:     my %new_values;
                   5940:     my %new_control;
                   5941:     my %translation;
                   5942:     my @deletions = ();
                   5943:     my $now = time;
                   5944:     if (exists($$changes{'activate'})) {
                   5945:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5946:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5947:             my $numnew = scalar(@newitems);
                   5948:             for (my $i=0; $i<$numnew; $i++) {
                   5949:                 my $newkey = $newitems[$i];
                   5950:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5951:                 if ($newkey =~ /^\d+:/) { 
                   5952:                     $newkey =~ s/^(\d+)/$newid/;
                   5953:                     $translation{$1} = $newid;
                   5954:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5955:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5956:                     $translation{$1} = $newid;
                   5957:                 }
1.749     raeburn  5958:                 $new_values{$file_name."\0".$newkey} = 
                   5959:                                           $$changes{'activate'}{$newitems[$i]};
                   5960:                 $new_control{$newkey} = $now;
                   5961:             }
                   5962:         }
                   5963:     }
                   5964:     my %todelete;
                   5965:     my %changed_items;
                   5966:     foreach my $action ('delete','update') {
                   5967:         if (exists($$changes{$action})) {
                   5968:             if (ref($$changes{$action}) eq 'HASH') {
                   5969:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5970:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5971:                     if ($action eq 'delete') { 
                   5972:                         $todelete{$itemnum} = 1;
                   5973:                     } else {
                   5974:                         $changed_items{$itemnum} = $key;
                   5975:                     }
                   5976:                 }
1.745     raeburn  5977:             }
                   5978:         }
1.749     raeburn  5979:     }
                   5980:     # get lock on access controls for file.
                   5981:     my $lockhash = {
                   5982:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5983:                                                        ':'.$env{'user.domain'},
                   5984:                    }; 
                   5985:     my $tries = 0;
                   5986:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5987:    
                   5988:     while (($gotlock ne 'ok') && $tries <3) {
                   5989:         $tries ++;
                   5990:         sleep 1;
                   5991:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5992:     }
                   5993:     if ($gotlock eq 'ok') {
                   5994:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5995:         my ($tmp)=keys(%curr_permissions);
                   5996:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5997:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5998:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5999:             if (ref($curr_controls) eq 'HASH') {
                   6000:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6001:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6002:                     if (defined($todelete{$itemnum})) {
                   6003:                         push(@deletions,$file_name."\0".$control_item);
                   6004:                     } else {
                   6005:                         if (defined($changed_items{$itemnum})) {
                   6006:                             $new_control{$changed_items{$itemnum}} = $now;
                   6007:                             push(@deletions,$file_name."\0".$control_item);
                   6008:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6009:                         } else {
                   6010:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6011:                         }
                   6012:                     }
1.745     raeburn  6013:                 }
                   6014:             }
                   6015:         }
1.749     raeburn  6016:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6017:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6018:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6019:         #  remove lock
                   6020:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6021:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6022:         my ($file,$group);
                   6023:         if (&is_course($domain,$user)) {
                   6024:             ($group,$file) = split(/\//,$file_name,2);
                   6025:         } else {
                   6026:             $file = $file_name;
                   6027:         }
                   6028:         my $sqlresult =
                   6029:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6030:                                     $group);
1.749     raeburn  6031:     } else {
                   6032:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6033:     }
1.749     raeburn  6034:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6035: }
                   6036: 
1.827     raeburn  6037: sub make_public_indefinitely {
                   6038:     my ($requrl) = @_;
                   6039:     my $now = time;
                   6040:     my $action = 'activate';
                   6041:     my $aclnum = 0;
                   6042:     if (&is_portfolio_url($requrl)) {
                   6043:         my (undef,$udom,$unum,$file_name,$group) =
                   6044:             &parse_portfolio_url($requrl);
                   6045:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6046:         my %access_controls = &get_access_controls($current_perms,
                   6047:                                                    $group,$file_name);
                   6048:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6049:             my ($num,$scope,$end,$start) = 
                   6050:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6051:             if ($scope eq 'public') {
                   6052:                 if ($start <= $now && $end == 0) {
                   6053:                     $action = 'none';
                   6054:                 } else {
                   6055:                     $action = 'update';
                   6056:                     $aclnum = $num;
                   6057:                 }
                   6058:                 last;
                   6059:             }
                   6060:         }
                   6061:         if ($action eq 'none') {
                   6062:              return 'ok';
                   6063:         } else {
                   6064:             my %changes;
                   6065:             my $newend = 0;
                   6066:             my $newstart = $now;
                   6067:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6068:             $changes{$action}{$newkey} = {
                   6069:                 type => 'public',
                   6070:                 time => {
                   6071:                     start => $newstart,
                   6072:                     end   => $newend,
                   6073:                 },
                   6074:             };
                   6075:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6076:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6077:             return $outcome;
                   6078:         }
                   6079:     } else {
                   6080:         return 'invalid';
                   6081:     }
                   6082: }
                   6083: 
1.745     raeburn  6084: #------------------------------------------------------Get Marked as Read Only
                   6085: 
                   6086: sub get_marked_as_readonly {
                   6087:     my ($domain,$user,$what,$group) = @_;
                   6088:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6089:     my @readonly_files;
1.629     banghart 6090:     my $cmp1=$what;
                   6091:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6092:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6093:         if (defined($group)) {
                   6094:             if ($file_name !~ m-^\Q$group\E/-) {
                   6095:                 next;
                   6096:             }
                   6097:         }
1.561     banghart 6098:         if (ref($value) eq "ARRAY"){
                   6099:             foreach my $stored_what (@{$value}) {
1.629     banghart 6100:                 my $cmp2=$stored_what;
1.759     albertel 6101:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6102:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6103:                 }
1.629     banghart 6104:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6105:                     push(@readonly_files, $file_name);
1.745     raeburn  6106:                     last;
1.563     banghart 6107:                 } elsif (!defined($what)) {
                   6108:                     push(@readonly_files, $file_name);
1.745     raeburn  6109:                     last;
1.561     banghart 6110:                 }
                   6111:             }
1.745     raeburn  6112:         }
1.561     banghart 6113:     }
                   6114:     return @readonly_files;
                   6115: }
1.577     banghart 6116: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6117: 
1.577     banghart 6118: sub get_marked_as_readonly_hash {
1.745     raeburn  6119:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6120:     my %readonly_files;
1.745     raeburn  6121:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6122:         if (defined($group)) {
                   6123:             if ($file_name !~ m-^\Q$group\E/-) {
                   6124:                 next;
                   6125:             }
                   6126:         }
1.577     banghart 6127:         if (ref($value) eq "ARRAY"){
                   6128:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6129:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6130:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6131:                         if ($lock_descriptor eq 'graded') {
                   6132:                             $readonly_files{$file_name} = 'graded';
                   6133:                         } elsif ($lock_descriptor eq 'handback') {
                   6134:                             $readonly_files{$file_name} = 'handback';
                   6135:                         } else {
                   6136:                             if (!exists($readonly_files{$file_name})) {
                   6137:                                 $readonly_files{$file_name} = 'locked';
                   6138:                             }
                   6139:                         }
1.745     raeburn  6140:                     }
1.750     banghart 6141:                 } 
1.577     banghart 6142:             }
                   6143:         } 
                   6144:     }
                   6145:     return %readonly_files;
                   6146: }
1.559     banghart 6147: # ------------------------------------------------------------ Unmark as Read Only
                   6148: 
                   6149: sub unmark_as_readonly {
1.629     banghart 6150:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6151:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6152:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6153:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6154:     my $symb_crs = $what;
                   6155:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6156:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6157:     my ($tmp)=keys(%current_permissions);
                   6158:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6159:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6160:     foreach my $file (@readonly_files) {
1.759     albertel 6161: 	my $clean_file = &declutter_portfile($file);
                   6162: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6163: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6164:         my @new_locks;
                   6165:         my @del_keys;
                   6166:         if (ref($current_locks) eq "ARRAY"){
                   6167:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6168:                 my $compare=$locker;
1.749     raeburn  6169:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6170:                     $compare=join('',@{$locker});
1.746     raeburn  6171:                     if ($compare ne $symb_crs) {
                   6172:                         push(@new_locks, $locker);
                   6173:                     }
1.563     banghart 6174:                 }
                   6175:             }
1.650     albertel 6176:             if (scalar(@new_locks) > 0) {
1.563     banghart 6177:                 $current_permissions{$file} = \@new_locks;
                   6178:             } else {
                   6179:                 push(@del_keys, $file);
1.613     albertel 6180:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6181:                 delete($current_permissions{$file});
1.563     banghart 6182:             }
                   6183:         }
1.561     banghart 6184:     }
1.613     albertel 6185:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6186:     return;
                   6187: }
1.512     banghart 6188: 
1.17      www      6189: # ------------------------------------------------------------ Directory lister
                   6190: 
                   6191: sub dirlist {
1.253     stredwic 6192:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   6193: 
1.18      www      6194:     $uri=~s/^\///;
                   6195:     $uri=~s/\/$//;
1.253     stredwic 6196:     my ($udom, $uname);
                   6197:     (undef,$udom,$uname)=split(/\//,$uri);
                   6198:     if(defined($userdomain)) {
                   6199:         $udom = $userdomain;
                   6200:     }
                   6201:     if(defined($username)) {
                   6202:         $uname = $username;
                   6203:     }
                   6204: 
                   6205:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6206:     if(defined($alternateDirectoryRoot)) {
                   6207:         $dirRoot = $alternateDirectoryRoot;
                   6208:         $dirRoot =~ s/\/$//;
1.751     banghart 6209:     }
1.253     stredwic 6210: 
                   6211:     if($udom) {
                   6212:         if($uname) {
1.800     albertel 6213:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6214: 				 &homeserver($uname,$udom));
1.605     matthew  6215:             my @listing_results;
                   6216:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6217:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6218: 				  &homeserver($uname,$udom));
1.605     matthew  6219:                 @listing_results = split(/:/,$listing);
                   6220:             } else {
                   6221:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6222:             }
                   6223:             return @listing_results;
1.253     stredwic 6224:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6225:             my %allusers;
1.841     albertel 6226: 	    my %servers = &get_servers($udom,'library');
                   6227: 	    foreach my $tryserver (keys(%servers)) {
                   6228: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6229: 				     $udom, $tryserver);
                   6230: 		my @listing_results;
                   6231: 		if ($listing eq 'unknown_cmd') {
                   6232: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6233: 				      $udom, $tryserver);
                   6234: 		    @listing_results = split(/:/,$listing);
                   6235: 		} else {
                   6236: 		    @listing_results =
                   6237: 			map { &unescape($_); } split(/:/,$listing);
                   6238: 		}
                   6239: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6240: 		    $listing_results[0] ne 'empty'       &&
                   6241: 		    $listing_results[0] ne 'con_lost') {
                   6242: 		    foreach my $line (@listing_results) {
                   6243: 			my ($entry) = split(/&/,$line,2);
                   6244: 			$allusers{$entry} = 1;
                   6245: 		    }
                   6246: 		}
1.253     stredwic 6247:             }
                   6248:             my $alluserstr='';
1.800     albertel 6249:             foreach my $user (sort(keys(%allusers))) {
                   6250:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6251:             }
                   6252:             $alluserstr=~s/:$//;
                   6253:             return split(/:/,$alluserstr);
                   6254:         } else {
1.800     albertel 6255:             return ('missing user name');
1.253     stredwic 6256:         }
                   6257:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6258:         my @all_domains = sort(&all_domains());
                   6259:          foreach my $domain (@all_domains) {
                   6260:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6261:          }
                   6262:          return @all_domains;
                   6263:      } else {
1.800     albertel 6264:         return ('missing domain');
1.275     stredwic 6265:     }
                   6266: }
                   6267: 
                   6268: # --------------------------------------------- GetFileTimestamp
                   6269: # This function utilizes dirlist and returns the date stamp for
                   6270: # when it was last modified.  It will also return an error of -1
                   6271: # if an error occurs
                   6272: 
1.410     matthew  6273: ##
                   6274: ## FIXME: This subroutine assumes its caller knows something about the
                   6275: ## directory structure of the home server for the student ($root).
                   6276: ## Not a good assumption to make.  Since this is for looking up files
                   6277: ## in user directories, the full path should be constructed by lond, not
                   6278: ## whatever machine we request data from.
                   6279: ##
1.275     stredwic 6280: sub GetFileTimestamp {
                   6281:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6282:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6283:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6284:     my $subdir=$studentName.'__';
                   6285:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6286:     my $proname="$studentDomain/$subdir/$studentName";
                   6287:     $proname .= '/'.$filename;
1.375     matthew  6288:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6289:                                               $studentName, $root);
1.275     stredwic 6290:     my @stats = split('&', $fileStat);
                   6291:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6292:         # @stats contains first the filename, then the stat output
                   6293:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6294:     } else {
                   6295:         return -1;
1.253     stredwic 6296:     }
1.26      www      6297: }
                   6298: 
1.712     albertel 6299: sub stat_file {
                   6300:     my ($uri) = @_;
1.787     albertel 6301:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6302: 
1.712     albertel 6303:     my ($udom,$uname,$file,$dir);
                   6304:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6305: 	($udom,$uname,$file) =
1.811     albertel 6306: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6307: 	$file = 'userfiles/'.$file;
1.740     www      6308: 	$dir = &propath($udom,$uname);
1.712     albertel 6309:     }
                   6310:     if ($uri =~ m-^/res/-) {
                   6311: 	($udom,$uname) = 
1.807     albertel 6312: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6313: 	$file = $uri;
                   6314:     }
                   6315: 
                   6316:     if (!$udom || !$uname || !$file) {
                   6317: 	# unable to handle the uri
                   6318: 	return ();
                   6319:     }
                   6320: 
                   6321:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6322:     my @stats = split('&', $result);
1.721     banghart 6323:     
1.712     albertel 6324:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6325: 	shift(@stats); #filename is first
                   6326: 	return @stats;
                   6327:     }
                   6328:     return ();
                   6329: }
                   6330: 
1.26      www      6331: # -------------------------------------------------------- Value of a Condition
                   6332: 
1.713     albertel 6333: # gets the value of a specific preevaluated condition
                   6334: #    stored in the string  $env{user.state.<cid>}
                   6335: # or looks up a condition reference in the bighash and if if hasn't
                   6336: # already been evaluated recurses into docondval to get the value of
                   6337: # the condition, then memoizing it to 
                   6338: #   $env{user.state.<cid>.<condition>}
1.40      www      6339: sub directcondval {
                   6340:     my $number=shift;
1.620     albertel 6341:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6342: 	&Apache::lonuserstate::evalstate();
                   6343:     }
1.713     albertel 6344:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6345: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6346:     } elsif ($number =~ /^_/) {
                   6347: 	my $sub_condition;
                   6348: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6349: 		&GDBM_READER(),0640)) {
                   6350: 	    $sub_condition=$bighash{'conditions'.$number};
                   6351: 	    untie(%bighash);
                   6352: 	}
                   6353: 	my $value = &docondval($sub_condition);
                   6354: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6355: 	return $value;
                   6356:     }
1.620     albertel 6357:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6358:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6359:     } else {
                   6360:        return 2;
                   6361:     }
                   6362: }
                   6363: 
1.713     albertel 6364: # get the collection of conditions for this resource
1.26      www      6365: sub condval {
                   6366:     my $condidx=shift;
1.54      www      6367:     my $allpathcond='';
1.713     albertel 6368:     foreach my $cond (split(/\|/,$condidx)) {
                   6369: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6370: 	    $allpathcond.=
                   6371: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6372: 	}
1.191     harris41 6373:     }
1.54      www      6374:     $allpathcond=~s/\|$//;
1.713     albertel 6375:     return &docondval($allpathcond);
                   6376: }
                   6377: 
                   6378: #evaluates an expression of conditions
                   6379: sub docondval {
                   6380:     my ($allpathcond) = @_;
                   6381:     my $result=0;
                   6382:     if ($env{'request.course.id'}
                   6383: 	&& defined($allpathcond)) {
                   6384: 	my $operand='|';
                   6385: 	my @stack;
                   6386: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6387: 	    if ($chunk eq '(') {
                   6388: 		push @stack,($operand,$result);
                   6389: 	    } elsif ($chunk eq ')') {
                   6390: 		my $before=pop @stack;
                   6391: 		if (pop @stack eq '&') {
                   6392: 		    $result=$result>$before?$before:$result;
                   6393: 		} else {
                   6394: 		    $result=$result>$before?$result:$before;
                   6395: 		}
                   6396: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6397: 		$operand=$chunk;
                   6398: 	    } else {
                   6399: 		my $new=directcondval($chunk);
                   6400: 		if ($operand eq '&') {
                   6401: 		    $result=$result>$new?$new:$result;
                   6402: 		} else {
                   6403: 		    $result=$result>$new?$result:$new;
                   6404: 		}
                   6405: 	    }
                   6406: 	}
1.26      www      6407:     }
                   6408:     return $result;
1.421     albertel 6409: }
                   6410: 
                   6411: # ---------------------------------------------------- Devalidate courseresdata
                   6412: 
                   6413: sub devalidatecourseresdata {
                   6414:     my ($coursenum,$coursedomain)=@_;
                   6415:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6416:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6417: }
                   6418: 
1.763     www      6419: 
1.200     www      6420: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6421: #
                   6422: #  Parameters:
                   6423: #      $coursenum    - Number of the course.
                   6424: #      $coursedomain - Domain at which the course was created.
                   6425: #  Returns:
                   6426: #     A hash of the course parameters along (I think) with timestamps
                   6427: #     and version info.
1.877     foxr     6428: 
1.624     albertel 6429: sub get_courseresdata {
                   6430:     my ($coursenum,$coursedomain)=@_;
1.200     www      6431:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6432:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6433:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6434:     my %dumpreply;
1.417     albertel 6435:     unless (defined($cached)) {
1.624     albertel 6436: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6437: 	$result=\%dumpreply;
1.251     albertel 6438: 	my ($tmp) = keys(%dumpreply);
                   6439: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6440: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6441: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6442: 	    return $tmp;
1.416     albertel 6443: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6444: 	    $result=undef;
1.599     albertel 6445: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6446: 	}
                   6447:     }
1.624     albertel 6448:     return $result;
                   6449: }
                   6450: 
1.633     albertel 6451: sub devalidateuserresdata {
                   6452:     my ($uname,$udom)=@_;
                   6453:     my $hashid="$udom:$uname";
                   6454:     &devalidate_cache_new('userres',$hashid);
                   6455: }
                   6456: 
1.624     albertel 6457: sub get_userresdata {
                   6458:     my ($uname,$udom)=@_;
                   6459:     #most student don\'t have any data set, check if there is some data
                   6460:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6461: 
                   6462:     my $hashid="$udom:$uname";
                   6463:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6464:     if (!defined($cached)) {
                   6465: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6466: 	$result=\%resourcedata;
                   6467: 	&do_cache_new('userres',$hashid,$result,600);
                   6468:     }
                   6469:     my ($tmp)=keys(%$result);
                   6470:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6471: 	return $result;
                   6472:     }
                   6473:     #error 2 occurs when the .db doesn't exist
                   6474:     if ($tmp!~/error: 2 /) {
1.672     albertel 6475: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6476: 		 " Trying to get resource data for ".
                   6477: 		 $uname." at ".$udom.": ".
                   6478: 		 $tmp."</font>");
                   6479:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6480: 	#&EXT_cache_set($udom,$uname);
                   6481: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6482: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6483:     }
                   6484:     return $tmp;
                   6485: }
1.879     foxr     6486: #----------------------------------------------- resdata - return resource data
                   6487: #  Purpose:
                   6488: #    Return resource data for either users or for a course.
                   6489: #  Parameters:
                   6490: #     $name      - Course/user name.
                   6491: #     $domain    - Name of the domain the user/course is registered on.
                   6492: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6493: #     @which     - Array of names of resources desired.
                   6494: #  Returns:
                   6495: #     The value of the first reasource in @which that is found in the
                   6496: #     resource hash.
                   6497: #  Exceptional Conditions:
                   6498: #     If the $type passed in is not valid (not the string 'course' or 
                   6499: #     'user', an undefined  reference is returned.
                   6500: #     If none of the resources are found, an undef is returned
1.624     albertel 6501: sub resdata {
                   6502:     my ($name,$domain,$type,@which)=@_;
                   6503:     my $result;
                   6504:     if ($type eq 'course') {
                   6505: 	$result=&get_courseresdata($name,$domain);
                   6506:     } elsif ($type eq 'user') {
                   6507: 	$result=&get_userresdata($name,$domain);
                   6508:     }
                   6509:     if (!ref($result)) { return $result; }    
1.251     albertel 6510:     foreach my $item (@which) {
1.927     albertel 6511: 	if (defined($result->{$item->[0]})) {
                   6512: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6513: 	}
1.250     albertel 6514:     }
1.291     albertel 6515:     return undef;
1.200     www      6516: }
                   6517: 
1.379     matthew  6518: #
                   6519: # EXT resource caching routines
                   6520: #
                   6521: 
                   6522: sub clear_EXT_cache_status {
1.383     albertel 6523:     &delenv('cache.EXT.');
1.379     matthew  6524: }
                   6525: 
                   6526: sub EXT_cache_status {
                   6527:     my ($target_domain,$target_user) = @_;
1.383     albertel 6528:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6529:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6530:         # We know already the user has no data
                   6531:         return 1;
                   6532:     } else {
                   6533:         return 0;
                   6534:     }
                   6535: }
                   6536: 
                   6537: sub EXT_cache_set {
                   6538:     my ($target_domain,$target_user) = @_;
1.383     albertel 6539:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6540:     #&appenv($cachename => time);
1.379     matthew  6541: }
                   6542: 
1.28      www      6543: # --------------------------------------------------------- Value of a Variable
1.58      www      6544: sub EXT {
1.715     albertel 6545: 
1.395     albertel 6546:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6547:     unless ($varname) { return ''; }
1.218     albertel 6548:     #get real user name/domain, courseid and symb
                   6549:     my $courseid;
1.359     albertel 6550:     my $publicuser;
1.427     www      6551:     if ($symbparm) {
                   6552: 	$symbparm=&get_symb_from_alias($symbparm);
                   6553:     }
1.218     albertel 6554:     if (!($uname && $udom)) {
1.790     albertel 6555:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6556:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6557:     } else {
1.620     albertel 6558: 	$courseid=$env{'request.course.id'};
1.218     albertel 6559:     }
1.48      www      6560:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6561:     my $rest;
1.320     albertel 6562:     if (defined($therest[0])) {
1.48      www      6563:        $rest=join('.',@therest);
                   6564:     } else {
                   6565:        $rest='';
                   6566:     }
1.320     albertel 6567: 
1.57      www      6568:     my $qualifierrest=$qualifier;
                   6569:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6570:     my $spacequalifierrest=$space;
                   6571:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6572:     if ($realm eq 'user') {
1.48      www      6573: # --------------------------------------------------------------- user.resource
                   6574: 	if ($space eq 'resource') {
1.651     albertel 6575: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6576: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6577: 		 &&
1.744     albertel 6578: 		 ($symbparm eq &symbread()) ) {	
                   6579: 		# if we are in the middle of processing the resource the
                   6580: 		# get the value we are planning on committing
                   6581:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6582:                     return $Apache::lonhomework::results{$qualifierrest};
                   6583:                 } else {
                   6584:                     return $Apache::lonhomework::history{$qualifierrest};
                   6585:                 }
1.335     albertel 6586: 	    } else {
1.359     albertel 6587: 		my %restored;
1.620     albertel 6588: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6589: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6590: 		} else {
                   6591: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6592: 		}
1.335     albertel 6593: 		return $restored{$qualifierrest};
                   6594: 	    }
1.48      www      6595: # ----------------------------------------------------------------- user.access
                   6596:         } elsif ($space eq 'access') {
1.218     albertel 6597: 	    # FIXME - not supporting calls for a specific user
1.48      www      6598:             return &allowed($qualifier,$rest);
                   6599: # ------------------------------------------ user.preferences, user.environment
                   6600:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6601: 	    if (($uname eq $env{'user.name'}) &&
                   6602: 		($udom eq $env{'user.domain'})) {
                   6603: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6604: 	    } else {
1.359     albertel 6605: 		my %returnhash;
                   6606: 		if (!$publicuser) {
                   6607: 		    %returnhash=&userenvironment($udom,$uname,
                   6608: 						 $qualifierrest);
                   6609: 		}
1.218     albertel 6610: 		return $returnhash{$qualifierrest};
                   6611: 	    }
1.48      www      6612: # ----------------------------------------------------------------- user.course
                   6613:         } elsif ($space eq 'course') {
1.218     albertel 6614: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6615:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6616: # ------------------------------------------------------------------- user.role
                   6617:         } elsif ($space eq 'role') {
1.218     albertel 6618: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6619:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6620:             if ($qualifier eq 'value') {
                   6621: 		return $role;
                   6622:             } elsif ($qualifier eq 'extent') {
                   6623:                 return $where;
                   6624:             }
                   6625: # ----------------------------------------------------------------- user.domain
                   6626:         } elsif ($space eq 'domain') {
1.218     albertel 6627:             return $udom;
1.48      www      6628: # ------------------------------------------------------------------- user.name
                   6629:         } elsif ($space eq 'name') {
1.218     albertel 6630:             return $uname;
1.48      www      6631: # ---------------------------------------------------- Any other user namespace
1.29      www      6632:         } else {
1.359     albertel 6633: 	    my %reply;
                   6634: 	    if (!$publicuser) {
                   6635: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6636: 	    }
                   6637: 	    return $reply{$qualifierrest};
1.48      www      6638:         }
1.236     www      6639:     } elsif ($realm eq 'query') {
                   6640: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6641:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6642: 						[$spacequalifierrest]);
1.620     albertel 6643: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6644:    } elsif ($realm eq 'request') {
1.48      www      6645: # ------------------------------------------------------------- request.browser
                   6646:         if ($space eq 'browser') {
1.430     www      6647: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6648: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6649: 		    return 1;
                   6650: 		} else {
                   6651: 		    return 0;
                   6652: 		}
                   6653: 	    } else {
1.620     albertel 6654: 		return $env{'browser.'.$qualifier};
1.430     www      6655: 	    }
1.57      www      6656: # ------------------------------------------------------------ request.filename
                   6657:         } else {
1.620     albertel 6658:             return $env{'request.'.$spacequalifierrest};
1.29      www      6659:         }
1.28      www      6660:     } elsif ($realm eq 'course') {
1.48      www      6661: # ---------------------------------------------------------- course.description
1.620     albertel 6662:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6663:     } elsif ($realm eq 'resource') {
1.165     www      6664: 
1.620     albertel 6665: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6666: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6667: 	}
1.693     albertel 6668: 
                   6669: 	if ($space eq 'title') {
                   6670: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6671: 	    return &gettitle($symbparm);
                   6672: 	}
                   6673: 	
                   6674: 	if ($space eq 'map') {
                   6675: 	    my ($map) = &decode_symb($symbparm);
                   6676: 	    return &symbread($map);
                   6677: 	}
1.905     albertel 6678: 	if ($space eq 'filename') {
                   6679: 	    if ($symbparm) {
                   6680: 		return &clutter((&decode_symb($symbparm))[2]);
                   6681: 	    }
                   6682: 	    return &hreflocation('',$env{'request.filename'});
                   6683: 	}
1.693     albertel 6684: 
                   6685: 	my ($section, $group, @groups);
1.593     albertel 6686: 	my ($courselevelm,$courselevel);
1.539     albertel 6687: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6688: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6689: 
1.218     albertel 6690: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6691: 
1.60      www      6692: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6693: 	    my $symbp=$symbparm;
1.735     albertel 6694: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6695: 
                   6696: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6697: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6698: 
1.620     albertel 6699: 	    if (($env{'user.name'} eq $uname) &&
                   6700: 		($env{'user.domain'} eq $udom)) {
                   6701: 		$section=$env{'request.course.sec'};
1.733     raeburn  6702:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6703:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6704: 	    } else {
1.539     albertel 6705: 		if (! defined($usection)) {
1.551     albertel 6706: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6707: 		} else {
                   6708: 		    $section = $usection;
                   6709: 		}
1.733     raeburn  6710:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6711: 	    }
                   6712: 
                   6713: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6714: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6715: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6716: 
1.593     albertel 6717: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6718: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6719: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6720: 
1.60      www      6721: # ----------------------------------------------------------- first, check user
1.624     albertel 6722: 
                   6723: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6724: 				       ([$courselevelr,'resource'],
                   6725: 					[$courselevelm,'map'     ],
                   6726: 					[$courselevel, 'course'  ]));
1.931     albertel 6727: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6728: 
1.594     albertel 6729: # ------------------------------------------------ second, check some of course
1.684     raeburn  6730:             my $coursereply;
1.691     raeburn  6731:             if (@groups > 0) {
                   6732:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6733:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6734:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6735:             }
1.96      www      6736: 
1.684     raeburn  6737: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6738: 				  $env{'course.'.$courseid.'.domain'},
                   6739: 				  'course',
                   6740: 				  ([$seclevelr,   'resource'],
                   6741: 				   [$seclevelm,   'map'     ],
                   6742: 				   [$seclevel,    'course'  ],
                   6743: 				   [$courselevelr,'resource']));
                   6744: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6745: 
1.60      www      6746: # ------------------------------------------------------ third, check map parms
1.218     albertel 6747: 	    my %parmhash=();
                   6748: 	    my $thisparm='';
                   6749: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6750: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6751: 		    &GDBM_READER(),0640)) {
1.218     albertel 6752: 		$thisparm=$parmhash{$symbparm};
                   6753: 		untie(%parmhash);
                   6754: 	    }
1.927     albertel 6755: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6756: 	}
1.594     albertel 6757: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6758: 
1.218     albertel 6759: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6760: 	my $filename;
                   6761: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6762: 	if ($symbparm) {
1.409     www      6763: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6764: 	} else {
1.620     albertel 6765: 	    $filename=$env{'request.filename'};
1.282     albertel 6766: 	}
                   6767: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6768: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6769: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6770: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6771: 
1.927     albertel 6772: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6773: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6774: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6775: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6776: 				     $env{'course.'.$courseid.'.domain'},
                   6777: 				     'course',
1.927     albertel 6778: 				     ([$courselevelm,'map'   ],
                   6779: 				      [$courselevel, 'course']));
                   6780: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6781: 	}
1.145     www      6782: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6783: 	unless ($space eq '0') {
1.336     albertel 6784: 	    my @parts=split(/_/,$space);
                   6785: 	    my $id=pop(@parts);
                   6786: 	    my $part=join('_',@parts);
                   6787: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6788: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6789: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6790: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6791: 	}
1.395     albertel 6792: 	if ($recurse) { return undef; }
                   6793: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6794: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6795: # ---------------------------------------------------- Any other user namespace
                   6796:     } elsif ($realm eq 'environment') {
                   6797: # ----------------------------------------------------------------- environment
1.620     albertel 6798: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6799: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6800: 	} else {
1.770     albertel 6801: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6802: 		return '';
                   6803: 	    }
1.219     albertel 6804: 	    my %returnhash=&userenvironment($udom,$uname,
                   6805: 					    $spacequalifierrest);
                   6806: 	    return $returnhash{$spacequalifierrest};
                   6807: 	}
1.28      www      6808:     } elsif ($realm eq 'system') {
1.48      www      6809: # ----------------------------------------------------------------- system.time
                   6810: 	if ($space eq 'time') {
                   6811: 	    return time;
                   6812:         }
1.696     albertel 6813:     } elsif ($realm eq 'server') {
                   6814: # ----------------------------------------------------------------- system.time
                   6815: 	if ($space eq 'name') {
                   6816: 	    return $ENV{'SERVER_NAME'};
                   6817:         }
1.28      www      6818:     }
1.48      www      6819:     return '';
1.61      www      6820: }
                   6821: 
1.927     albertel 6822: sub get_reply {
                   6823:     my ($reply_value) = @_;
1.940     raeburn  6824:     if (ref($reply_value) eq 'ARRAY') {
                   6825:         if (wantarray) {
                   6826: 	    return @$reply_value;
                   6827:         }
                   6828:         return $reply_value->[0];
                   6829:     } else {
                   6830:         return $reply_value;
1.927     albertel 6831:     }
                   6832: }
                   6833: 
1.691     raeburn  6834: sub check_group_parms {
                   6835:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6836:     my @groupitems = ();
                   6837:     my $resultitem;
1.927     albertel 6838:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6839:     foreach my $group (@{$groups}) {
                   6840:         foreach my $level (@levels) {
1.927     albertel 6841:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6842:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6843:         }
                   6844:     }
                   6845:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6846:                             $env{'course.'.$courseid.'.domain'},
                   6847:                                      'course',@groupitems);
                   6848:     return $coursereply;
                   6849: }
                   6850: 
                   6851: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6852:     my ($courseid,@groups) = @_;
                   6853:     @groups = sort(@groups);
1.691     raeburn  6854:     return @groups;
                   6855: }
                   6856: 
1.395     albertel 6857: sub packages_tab_default {
                   6858:     my ($uri,$varname)=@_;
                   6859:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6860: 
                   6861:     my (@extension,@specifics,$do_default);
                   6862:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6863: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6864: 	if ($pack_type eq 'default') {
                   6865: 	    $do_default=1;
                   6866: 	} elsif ($pack_type eq 'extension') {
                   6867: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6868: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6869: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6870: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6871: 	}
                   6872:     }
                   6873:     # first look for a package that matches the requested part id
                   6874:     foreach my $package (@specifics) {
                   6875: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6876: 	next if ($pack_part ne $part);
                   6877: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6878: 	    return $packagetab{"$pack_type&$name&default"};
                   6879: 	}
                   6880:     }
                   6881:     # look for any possible matching non extension_ package
                   6882:     foreach my $package (@specifics) {
                   6883: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6884: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6885: 	    return $packagetab{"$pack_type&$name&default"};
                   6886: 	}
1.585     albertel 6887: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6888: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6889: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6890: 	}
                   6891:     }
1.738     albertel 6892:     # look for any posible extension_ match
                   6893:     foreach my $package (@extension) {
                   6894: 	my ($package,$pack_type)=@{$package};
                   6895: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6896: 	    return $packagetab{"$pack_type&$name&default"};
                   6897: 	}
                   6898: 	if (defined($packagetab{$package."&$name&default"})) {
                   6899: 	    return $packagetab{$package."&$name&default"};
                   6900: 	}
                   6901:     }
                   6902:     # look for a global default setting
                   6903:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6904: 	return $packagetab{"default&$name&default"};
                   6905:     }
1.395     albertel 6906:     return undef;
                   6907: }
                   6908: 
1.334     albertel 6909: sub add_prefix_and_part {
                   6910:     my ($prefix,$part)=@_;
                   6911:     my $keyroot;
                   6912:     if (defined($prefix) && $prefix !~ /^__/) {
                   6913: 	# prefix that has a part already
                   6914: 	$keyroot=$prefix;
                   6915:     } elsif (defined($prefix)) {
                   6916: 	# prefix that is missing a part
                   6917: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6918:     } else {
                   6919: 	# no prefix at all
                   6920: 	if (defined($part)) { $keyroot='_'.$part; }
                   6921:     }
                   6922:     return $keyroot;
                   6923: }
                   6924: 
1.71      www      6925: # ---------------------------------------------------------------- Get metadata
                   6926: 
1.599     albertel 6927: my %metaentry;
1.71      www      6928: sub metadata {
1.176     www      6929:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6930:     $uri=&declutter($uri);
1.288     albertel 6931:     # if it is a non metadata possible uri return quickly
1.529     albertel 6932:     if (($uri eq '') || 
                   6933: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6934: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 6935:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   6936: 	return undef;
                   6937:     }
                   6938:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   6939: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 6940: 	return undef;
1.288     albertel 6941:     }
1.73      www      6942:     my $filename=$uri;
                   6943:     $uri=~s/\.meta$//;
1.172     www      6944: #
                   6945: # Is the metadata already cached?
1.177     www      6946: # Look at timestamp of caching
1.172     www      6947: # Everything is cached by the main uri, libraries are never directly cached
                   6948: #
1.428     albertel 6949:     if (!defined($liburi)) {
1.599     albertel 6950: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6951: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6952:     }
                   6953:     {
1.172     www      6954: #
                   6955: # Is this a recursive call for a library?
                   6956: #
1.599     albertel 6957: #	if (! exists($metacache{$uri})) {
                   6958: #	    $metacache{$uri}={};
                   6959: #	}
1.924     albertel 6960: 	my $cachetime = 60*60;
1.171     www      6961:         if ($liburi) {
                   6962: 	    $liburi=&declutter($liburi);
                   6963:             $filename=$liburi;
1.401     bowersj2 6964:         } else {
1.599     albertel 6965: 	    &devalidate_cache_new('meta',$uri);
                   6966: 	    undef(%metaentry);
1.401     bowersj2 6967: 	}
1.140     www      6968:         my %metathesekeys=();
1.73      www      6969:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6970: 	my $metastring;
1.924     albertel 6971: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 6972: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 6973: 	    $metastring = 
1.929     albertel 6974: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 6975: 					  ('grade_target' => 'meta'));
                   6976: 	    $cachetime = 1; # only want this cached in the child not long term
                   6977: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 6978: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6979: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6980: 	    $metastring=&getfile($file);
1.489     albertel 6981: 	}
1.208     albertel 6982:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6983:         my $token;
1.140     www      6984:         undef %metathesekeys;
1.71      www      6985:         while ($token=$parser->get_token) {
1.339     albertel 6986: 	    if ($token->[0] eq 'S') {
                   6987: 		if (defined($token->[2]->{'package'})) {
1.172     www      6988: #
                   6989: # This is a package - get package info
                   6990: #
1.339     albertel 6991: 		    my $package=$token->[2]->{'package'};
                   6992: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6993: 		    if (defined($token->[2]->{'id'})) { 
                   6994: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6995: 		    }
1.599     albertel 6996: 		    if ($metaentry{':packages'}) {
                   6997: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6998: 		    } else {
1.599     albertel 6999: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7000: 		    }
1.736     albertel 7001: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7002: 			my $part=$keyroot;
                   7003: 			$part=~s/^\_//;
1.736     albertel 7004: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7005: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7006: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7007: 			    # ignore package.tab specified default values
                   7008:                             # here &package_tab_default() will fetch those
                   7009: 			    if ($subp eq 'default') { next; }
1.736     albertel 7010: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7011: 			    my $unikey;
                   7012: 			    if ($pack =~ /_0$/) {
                   7013: 				$unikey='parameter_0_'.$name;
                   7014: 				$part=0;
                   7015: 			    } else {
                   7016: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7017: 			    }
1.339     albertel 7018: 			    if ($subp eq 'display') {
                   7019: 				$value.=' [Part: '.$part.']';
                   7020: 			    }
1.599     albertel 7021: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7022: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7023: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7024: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7025: 			    }
1.599     albertel 7026: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7027: 				$metaentry{':'.$unikey}=
                   7028: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7029: 			    }
1.339     albertel 7030: 			}
                   7031: 		    }
                   7032: 		} else {
1.172     www      7033: #
                   7034: # This is not a package - some other kind of start tag
1.339     albertel 7035: #
                   7036: 		    my $entry=$token->[1];
                   7037: 		    my $unikey;
                   7038: 		    if ($entry eq 'import') {
                   7039: 			$unikey='';
                   7040: 		    } else {
                   7041: 			$unikey=$entry;
                   7042: 		    }
                   7043: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7044: 
                   7045: 		    if (defined($token->[2]->{'id'})) { 
                   7046: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7047: 		    }
1.175     www      7048: 
1.339     albertel 7049: 		    if ($entry eq 'import') {
1.175     www      7050: #
                   7051: # Importing a library here
1.339     albertel 7052: #
                   7053: 			if ($depthcount<20) {
                   7054: 			    my $location=$parser->get_text('/import');
                   7055: 			    my $dir=$filename;
                   7056: 			    $dir=~s|[^/]*$||;
                   7057: 			    $location=&filelocation($dir,$location);
1.736     albertel 7058: 			    my $metadata = 
                   7059: 				&metadata($uri,'keys', $location,$unikey,
                   7060: 					  $depthcount+1);
                   7061: 			    foreach my $meta (split(',',$metadata)) {
                   7062: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7063: 				$metathesekeys{$meta}=1;
1.339     albertel 7064: 			    }
                   7065: 			}
                   7066: 		    } else { 
                   7067: 			
                   7068: 			if (defined($token->[2]->{'name'})) { 
                   7069: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7070: 			}
                   7071: 			$metathesekeys{$unikey}=1;
1.736     albertel 7072: 			foreach my $param (@{$token->[3]}) {
                   7073: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7074: 				$token->[2]->{$param};
1.339     albertel 7075: 			}
                   7076: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7077: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7078: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7079: 		 # only ws inside the tag, and not in default, so use default
                   7080: 		 # as value
1.599     albertel 7081: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7082: 			} elsif ( $internaltext =~ /\S/ ) {
                   7083: 		  # something interesting inside the tag
                   7084: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7085: 			} else {
1.908     albertel 7086: 		  # no interesting values, don't set a default
1.339     albertel 7087: 			}
1.172     www      7088: # end of not-a-package not-a-library import
1.339     albertel 7089: 		    }
1.172     www      7090: # end of not-a-package start tag
1.339     albertel 7091: 		}
1.172     www      7092: # the next is the end of "start tag"
1.339     albertel 7093: 	    }
                   7094: 	}
1.483     albertel 7095: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7096: 	$extension = lc($extension);
                   7097: 	if ($extension eq 'htm') { $extension='html'; }
                   7098: 
1.737     albertel 7099: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7100: 	    #no specific packages #how's our extension
                   7101: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7102: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7103: 					 \%metathesekeys);
                   7104: 	}
1.883     albertel 7105: 
                   7106: 	if (!exists($metaentry{':packages'})
                   7107: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7108: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7109: 		#no specific packages well let's get default then
                   7110: 		if ($key!~/^default&/) { next; }
1.488     albertel 7111: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7112: 					     \%metathesekeys);
                   7113: 	    }
                   7114: 	}
1.338     www      7115: # are there custom rights to evaluate
1.599     albertel 7116: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7117: 
1.338     www      7118:     #
                   7119:     # Importing a rights file here
1.339     albertel 7120:     #
                   7121: 	    unless ($depthcount) {
1.599     albertel 7122: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7123: 		my $dir=$filename;
                   7124: 		$dir=~s|[^/]*$||;
                   7125: 		$location=&filelocation($dir,$location);
1.736     albertel 7126: 		my $rights_metadata =
                   7127: 		    &metadata($uri,'keys',$location,'_rights',
                   7128: 			      $depthcount+1);
                   7129: 		foreach my $rights (split(',',$rights_metadata)) {
                   7130: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7131: 		    $metathesekeys{$rights}=1;
1.339     albertel 7132: 		}
                   7133: 	    }
                   7134: 	}
1.737     albertel 7135: 	# uniqifiy package listing
                   7136: 	my %seen;
                   7137: 	my @uniq_packages =
                   7138: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7139: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7140: 
                   7141: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7142: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7143: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7144: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7145: # this is the end of "was not already recently cached
1.71      www      7146:     }
1.599     albertel 7147:     return $metaentry{':'.$what};
1.261     albertel 7148: }
                   7149: 
1.488     albertel 7150: sub metadata_create_package_def {
1.483     albertel 7151:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7152:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7153:     if ($subp eq 'default') { next; }
                   7154:     
1.599     albertel 7155:     if (defined($metaentry{':packages'})) {
                   7156: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7157:     } else {
1.599     albertel 7158: 	$metaentry{':packages'}=$package;
1.483     albertel 7159:     }
                   7160:     my $value=$packagetab{$key};
                   7161:     my $unikey;
                   7162:     $unikey='parameter_0_'.$name;
1.599     albertel 7163:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7164:     $$metathesekeys{$unikey}=1;
1.599     albertel 7165:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7166: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7167:     }
1.599     albertel 7168:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7169: 	$metaentry{':'.$unikey}=
                   7170: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7171:     }
                   7172: }
                   7173: 
1.261     albertel 7174: sub metadata_generate_part0 {
                   7175:     my ($metadata,$metacache,$uri) = @_;
                   7176:     my %allnames;
1.737     albertel 7177:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7178: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7179: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7180: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7181: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7182: 	    $allnames{$name}=$part;
                   7183: 	  }
                   7184: 	}
                   7185:     }
                   7186:     foreach my $name (keys(%allnames)) {
                   7187:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7188:       my $key=":parameter_0_$name";
1.261     albertel 7189:       $$metacache{"$key.part"}='0';
                   7190:       $$metacache{"$key.name"}=$name;
1.428     albertel 7191:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7192: 					   $allnames{$name}.'_'.$name.
                   7193: 					   '.type'};
1.428     albertel 7194:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7195: 			     '.display'};
1.644     www      7196:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7197:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7198:       $$metacache{"$key.display"}=$olddis;
                   7199:     }
1.71      www      7200: }
                   7201: 
1.764     albertel 7202: # ------------------------------------------------------ Devalidate title cache
                   7203: 
                   7204: sub devalidate_title_cache {
                   7205:     my ($url)=@_;
                   7206:     if (!$env{'request.course.id'}) { return; }
                   7207:     my $symb=&symbread($url);
                   7208:     if (!$symb) { return; }
                   7209:     my $key=$env{'request.course.id'}."\0".$symb;
                   7210:     &devalidate_cache_new('title',$key);
                   7211: }
                   7212: 
1.301     www      7213: # ------------------------------------------------- Get the title of a resource
                   7214: 
                   7215: sub gettitle {
                   7216:     my $urlsymb=shift;
                   7217:     my $symb=&symbread($urlsymb);
1.534     albertel 7218:     if ($symb) {
1.620     albertel 7219: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7220: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7221: 	if (defined($cached)) { 
                   7222: 	    return $result;
                   7223: 	}
1.534     albertel 7224: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7225: 	my $title='';
1.907     albertel 7226: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7227: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7228: 	} else {
                   7229: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7230: 		    &GDBM_READER(),0640)) {
                   7231: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7232: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7233: 		untie(%bighash);
                   7234: 	    }
1.534     albertel 7235: 	}
                   7236: 	$title=~s/\&colon\;/\:/gs;
                   7237: 	if ($title) {
1.599     albertel 7238: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7239: 	}
                   7240: 	$urlsymb=$url;
                   7241:     }
                   7242:     my $title=&metadata($urlsymb,'title');
                   7243:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7244:     return $title;
1.301     www      7245: }
1.613     albertel 7246: 
1.614     albertel 7247: sub get_slot {
                   7248:     my ($which,$cnum,$cdom)=@_;
                   7249:     if (!$cnum || !$cdom) {
1.790     albertel 7250: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7251: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7252: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7253:     }
1.703     albertel 7254:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7255:     my %slotinfo;
                   7256:     if (exists($remembered{$key})) {
                   7257: 	$slotinfo{$which} = $remembered{$key};
                   7258:     } else {
                   7259: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7260: 	&Apache::lonhomework::showhash(%slotinfo);
                   7261: 	my ($tmp)=keys(%slotinfo);
                   7262: 	if ($tmp=~/^error:/) { return (); }
                   7263: 	$remembered{$key} = $slotinfo{$which};
                   7264:     }
1.616     albertel 7265:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7266: 	return %{$slotinfo{$which}};
                   7267:     }
                   7268:     return $slotinfo{$which};
1.614     albertel 7269: }
1.31      www      7270: # ------------------------------------------------- Update symbolic store links
                   7271: 
                   7272: sub symblist {
                   7273:     my ($mapname,%newhash)=@_;
1.438     www      7274:     $mapname=&deversion(&declutter($mapname));
1.31      www      7275:     my %hash;
1.620     albertel 7276:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7277:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7278:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7279: 	    foreach my $url (keys %newhash) {
                   7280: 		next if ($url eq 'last_known'
                   7281: 			 && $env{'form.no_update_last_known'});
                   7282: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7283: 						    $newhash{$url}->[1],
                   7284: 						    $newhash{$url}->[0]);
1.191     harris41 7285:             }
1.31      www      7286:             if (untie(%hash)) {
                   7287: 		return 'ok';
                   7288:             }
                   7289:         }
                   7290:     }
                   7291:     return 'error';
1.212     www      7292: }
                   7293: 
                   7294: # --------------------------------------------------------------- Verify a symb
                   7295: 
                   7296: sub symbverify {
1.510     www      7297:     my ($symb,$thisurl)=@_;
                   7298:     my $thisfn=$thisurl;
1.439     www      7299:     $thisfn=&declutter($thisfn);
1.215     www      7300: # direct jump to resource in page or to a sequence - will construct own symbs
                   7301:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7302: # check URL part
1.409     www      7303:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7304: 
1.431     www      7305:     unless ($url eq $thisfn) { return 0; }
1.213     www      7306: 
1.216     www      7307:     $symb=&symbclean($symb);
1.510     www      7308:     $thisurl=&deversion($thisurl);
1.439     www      7309:     $thisfn=&deversion($thisfn);
1.213     www      7310: 
                   7311:     my %bighash;
                   7312:     my $okay=0;
1.431     www      7313: 
1.620     albertel 7314:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7315:                             &GDBM_READER(),0640)) {
1.510     www      7316:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7317:         unless ($ids) { 
1.510     www      7318:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7319:         }
                   7320:         if ($ids) {
                   7321: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7322: 	    foreach my $id (split(/\,/,$ids)) {
                   7323: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7324:                if (
                   7325:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7326:    eq $symb) { 
1.620     albertel 7327: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7328: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7329: 		       $okay=1; 
                   7330: 		   }
                   7331: 	       }
1.216     www      7332: 	   }
                   7333:         }
1.213     www      7334: 	untie(%bighash);
                   7335:     }
                   7336:     return $okay;
1.31      www      7337: }
                   7338: 
1.210     www      7339: # --------------------------------------------------------------- Clean-up symb
                   7340: 
                   7341: sub symbclean {
                   7342:     my $symb=shift;
1.568     albertel 7343:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7344: # remove version from map
                   7345:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7346: 
1.210     www      7347: # remove version from URL
                   7348:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7349: 
1.507     www      7350: # remove wrapper
                   7351: 
1.510     www      7352:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7353:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7354:     return $symb;
1.409     www      7355: }
                   7356: 
                   7357: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7358: 
                   7359: sub encode_symb {
                   7360:     my ($map,$resid,$url)=@_;
                   7361:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7362: }
1.409     www      7363: 
                   7364: sub decode_symb {
1.568     albertel 7365:     my $symb=shift;
                   7366:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7367:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7368:     return (&fixversion($map),$resid,&fixversion($url));
                   7369: }
                   7370: 
                   7371: sub fixversion {
                   7372:     my $fn=shift;
1.609     banghart 7373:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7374:     my %bighash;
                   7375:     my $uri=&clutter($fn);
1.620     albertel 7376:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7377: # is this cached?
1.599     albertel 7378:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7379:     if (defined($cached)) { return $result; }
                   7380: # unfortunately not cached, or expired
1.620     albertel 7381:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7382: 	    &GDBM_READER(),0640)) {
                   7383:  	if ($bighash{'version_'.$uri}) {
                   7384:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7385:  	    unless (($version eq 'mostrecent') || 
                   7386: 		    ($version==&getversion($uri))) {
1.440     www      7387:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7388:  	    }
                   7389:  	}
                   7390:  	untie %bighash;
1.413     www      7391:     }
1.599     albertel 7392:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7393: }
                   7394: 
                   7395: sub deversion {
                   7396:     my $url=shift;
                   7397:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7398:     return $url;
1.210     www      7399: }
                   7400: 
1.31      www      7401: # ------------------------------------------------------ Return symb list entry
                   7402: 
                   7403: sub symbread {
1.249     www      7404:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7405:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7406:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7407: # no filename provided? try from environment
1.44      www      7408:     unless ($thisfn) {
1.620     albertel 7409:         if ($env{'request.symb'}) {
                   7410: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7411: 	}
1.620     albertel 7412: 	$thisfn=$env{'request.filename'};
1.44      www      7413:     }
1.569     albertel 7414:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7415: # is that filename actually a symb? Verify, clean, and return
                   7416:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7417: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7418: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7419: 	}
1.242     www      7420:     }
1.44      www      7421:     $thisfn=declutter($thisfn);
1.31      www      7422:     my %hash;
1.37      www      7423:     my %bighash;
                   7424:     my $syval='';
1.620     albertel 7425:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7426:         my $targetfn = $thisfn;
1.609     banghart 7427:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7428:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7429:         }
1.687     albertel 7430: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7431: 	    $targetfn=$1;
                   7432: 	}
1.620     albertel 7433:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7434:                       &GDBM_READER(),0640)) {
1.481     raeburn  7435: 	    $syval=$hash{$targetfn};
1.37      www      7436:             untie(%hash);
                   7437:         }
                   7438: # ---------------------------------------------------------- There was an entry
                   7439:         if ($syval) {
1.601     albertel 7440: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7441: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7442: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7443: 		    #return $env{$cache_str}='';
1.601     albertel 7444: 		#}    
                   7445: 		#$syval.=$1;
                   7446: 	    #}
1.37      www      7447:         } else {
                   7448: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7449:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7450:                             &GDBM_READER(),0640)) {
1.37      www      7451: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7452:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7453:               unless ($ids) { 
                   7454:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7455:               }
                   7456:               unless ($ids) {
                   7457: # alias?
                   7458: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7459:               }
1.37      www      7460:               if ($ids) {
                   7461: # ------------------------------------------------------------------- Has ID(s)
                   7462:                  my @possibilities=split(/\,/,$ids);
1.39      www      7463:                  if ($#possibilities==0) {
                   7464: # ----------------------------------------------- There is only one possibility
1.37      www      7465: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7466: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7467: 						    $resid,$thisfn);
1.249     www      7468:                  } elsif (!$donotrecurse) {
1.39      www      7469: # ------------------------------------------ There is more than one possibility
                   7470:                      my $realpossible=0;
1.800     albertel 7471:                      foreach my $id (@possibilities) {
                   7472: 			 my $file=$bighash{'src_'.$id};
1.39      www      7473:                          if (&allowed('bre',$file)) {
1.800     albertel 7474:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7475:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7476: 				$realpossible++;
1.626     albertel 7477:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7478: 						    $resid,$thisfn);
1.39      www      7479:                             }
                   7480: 			 }
1.191     harris41 7481:                      }
1.39      www      7482: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7483:                  } else {
                   7484:                      $syval='';
1.37      www      7485:                  }
                   7486: 	      }
                   7487:               untie(%bighash)
1.481     raeburn  7488:            }
1.31      www      7489:         }
1.62      www      7490:         if ($syval) {
1.620     albertel 7491: 	    return $env{$cache_str}=$syval;
1.62      www      7492:         }
1.31      www      7493:     }
1.44      www      7494:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7495:     return $env{$cache_str}='';
1.31      www      7496: }
                   7497: 
                   7498: # ---------------------------------------------------------- Return random seed
                   7499: 
1.32      www      7500: sub numval {
                   7501:     my $txt=shift;
                   7502:     $txt=~tr/A-J/0-9/;
                   7503:     $txt=~tr/a-j/0-9/;
                   7504:     $txt=~tr/K-T/0-9/;
                   7505:     $txt=~tr/k-t/0-9/;
                   7506:     $txt=~tr/U-Z/0-5/;
                   7507:     $txt=~tr/u-z/0-5/;
                   7508:     $txt=~s/\D//g;
1.564     albertel 7509:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7510:     return int($txt);
1.368     albertel 7511: }
                   7512: 
1.484     albertel 7513: sub numval2 {
                   7514:     my $txt=shift;
                   7515:     $txt=~tr/A-J/0-9/;
                   7516:     $txt=~tr/a-j/0-9/;
                   7517:     $txt=~tr/K-T/0-9/;
                   7518:     $txt=~tr/k-t/0-9/;
                   7519:     $txt=~tr/U-Z/0-5/;
                   7520:     $txt=~tr/u-z/0-5/;
                   7521:     $txt=~s/\D//g;
                   7522:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7523:     my $total;
                   7524:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7525:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7526:     return int($total);
                   7527: }
                   7528: 
1.575     albertel 7529: sub numval3 {
                   7530:     use integer;
                   7531:     my $txt=shift;
                   7532:     $txt=~tr/A-J/0-9/;
                   7533:     $txt=~tr/a-j/0-9/;
                   7534:     $txt=~tr/K-T/0-9/;
                   7535:     $txt=~tr/k-t/0-9/;
                   7536:     $txt=~tr/U-Z/0-5/;
                   7537:     $txt=~tr/u-z/0-5/;
                   7538:     $txt=~s/\D//g;
                   7539:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7540:     my $total;
                   7541:     foreach my $val (@txts) { $total+=$val; }
                   7542:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7543:     return $total;
                   7544: }
                   7545: 
1.675     albertel 7546: sub digest {
                   7547:     my ($data)=@_;
                   7548:     my $digest=&Digest::MD5::md5($data);
                   7549:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7550:     my ($e,$f);
                   7551:     {
                   7552:         use integer;
                   7553:         $e=($a+$b);
                   7554:         $f=($c+$d);
                   7555:         if ($_64bit) {
                   7556:             $e=(($e<<32)>>32);
                   7557:             $f=(($f<<32)>>32);
                   7558:         }
                   7559:     }
                   7560:     if (wantarray) {
                   7561: 	return ($e,$f);
                   7562:     } else {
                   7563: 	my $g;
                   7564: 	{
                   7565: 	    use integer;
                   7566: 	    $g=($e+$f);
                   7567: 	    if ($_64bit) {
                   7568: 		$g=(($g<<32)>>32);
                   7569: 	    }
                   7570: 	}
                   7571: 	return $g;
                   7572:     }
                   7573: }
                   7574: 
1.368     albertel 7575: sub latest_rnd_algorithm_id {
1.675     albertel 7576:     return '64bit5';
1.366     albertel 7577: }
1.32      www      7578: 
1.503     albertel 7579: sub get_rand_alg {
                   7580:     my ($courseid)=@_;
1.790     albertel 7581:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7582:     if ($courseid) {
1.620     albertel 7583: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7584:     }
                   7585:     return &latest_rnd_algorithm_id();
                   7586: }
                   7587: 
1.562     albertel 7588: sub validCODE {
                   7589:     my ($CODE)=@_;
                   7590:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7591:     return 0;
                   7592: }
                   7593: 
1.491     albertel 7594: sub getCODE {
1.620     albertel 7595:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7596:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7597: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7598: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7599: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7600:     }
                   7601:     return undef;
                   7602: }
                   7603: 
1.31      www      7604: sub rndseed {
1.155     albertel 7605:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7606:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7607:     if (!defined($symb)) {
1.366     albertel 7608: 	unless ($symb=$wsymb) { return time; }
                   7609:     }
                   7610:     if (!$courseid) { $courseid=$wcourseid; }
                   7611:     if (!$domain) { $domain=$wdomain; }
                   7612:     if (!$username) { $username=$wusername }
1.503     albertel 7613:     my $which=&get_rand_alg();
1.803     albertel 7614: 
1.491     albertel 7615:     if (defined(&getCODE())) {
1.675     albertel 7616: 	if ($which eq '64bit5') {
                   7617: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7618: 	} elsif ($which eq '64bit4') {
1.575     albertel 7619: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7620: 	} else {
                   7621: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7622: 	}
1.675     albertel 7623:     } elsif ($which eq '64bit5') {
                   7624: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7625:     } elsif ($which eq '64bit4') {
                   7626: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7627:     } elsif ($which eq '64bit3') {
                   7628: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7629:     } elsif ($which eq '64bit2') {
                   7630: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7631:     } elsif ($which eq '64bit') {
                   7632: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7633:     }
                   7634:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7635: }
                   7636: 
                   7637: sub rndseed_32bit {
                   7638:     my ($symb,$courseid,$domain,$username)=@_;
                   7639:     {
                   7640: 	use integer;
                   7641: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7642: 	my $symbseed=numval($symb) << 22;
                   7643: 	my $namechck=unpack("%32C*",$username) << 17;
                   7644: 	my $nameseed=numval($username) << 12;
                   7645: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7646: 	my $courseseed=unpack("%32C*",$courseid);
                   7647: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7648: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7649: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7650: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7651: 	return $num;
                   7652:     }
                   7653: }
                   7654: 
                   7655: sub rndseed_64bit {
                   7656:     my ($symb,$courseid,$domain,$username)=@_;
                   7657:     {
                   7658: 	use integer;
                   7659: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7660: 	my $symbseed=numval($symb) << 10;
                   7661: 	my $namechck=unpack("%32S*",$username);
                   7662: 	
                   7663: 	my $nameseed=numval($username) << 21;
                   7664: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7665: 	my $courseseed=unpack("%32S*",$courseid);
                   7666: 	
                   7667: 	my $num1=$symbchck+$symbseed+$namechck;
                   7668: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7669: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7670: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7671: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7672: 	return "$num1,$num2";
1.155     albertel 7673:     }
1.366     albertel 7674: }
                   7675: 
1.443     albertel 7676: sub rndseed_64bit2 {
                   7677:     my ($symb,$courseid,$domain,$username)=@_;
                   7678:     {
                   7679: 	use integer;
                   7680: 	# strings need to be an even # of cahracters long, it it is odd the
                   7681:         # last characters gets thrown away
                   7682: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7683: 	my $symbseed=numval($symb) << 10;
                   7684: 	my $namechck=unpack("%32S*",$username.' ');
                   7685: 	
                   7686: 	my $nameseed=numval($username) << 21;
1.501     albertel 7687: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7688: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7689: 	
                   7690: 	my $num1=$symbchck+$symbseed+$namechck;
                   7691: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7692: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7693: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7694: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7695: 	return "$num1,$num2";
                   7696:     }
                   7697: }
                   7698: 
                   7699: sub rndseed_64bit3 {
                   7700:     my ($symb,$courseid,$domain,$username)=@_;
                   7701:     {
                   7702: 	use integer;
                   7703: 	# strings need to be an even # of cahracters long, it it is odd the
                   7704:         # last characters gets thrown away
                   7705: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7706: 	my $symbseed=numval2($symb) << 10;
                   7707: 	my $namechck=unpack("%32S*",$username.' ');
                   7708: 	
                   7709: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7710: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7711: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7712: 	
                   7713: 	my $num1=$symbchck+$symbseed+$namechck;
                   7714: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7715: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7716: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7717: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7718: 	
1.503     albertel 7719: 	return "$num1:$num2";
1.443     albertel 7720:     }
                   7721: }
                   7722: 
1.575     albertel 7723: sub rndseed_64bit4 {
                   7724:     my ($symb,$courseid,$domain,$username)=@_;
                   7725:     {
                   7726: 	use integer;
                   7727: 	# strings need to be an even # of cahracters long, it it is odd the
                   7728:         # last characters gets thrown away
                   7729: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7730: 	my $symbseed=numval3($symb) << 10;
                   7731: 	my $namechck=unpack("%32S*",$username.' ');
                   7732: 	
                   7733: 	my $nameseed=numval3($username) << 21;
                   7734: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7735: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7736: 	
                   7737: 	my $num1=$symbchck+$symbseed+$namechck;
                   7738: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7739: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7740: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7741: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7742: 	
                   7743: 	return "$num1:$num2";
                   7744:     }
                   7745: }
                   7746: 
1.675     albertel 7747: sub rndseed_64bit5 {
                   7748:     my ($symb,$courseid,$domain,$username)=@_;
                   7749:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7750:     return "$num1:$num2";
                   7751: }
                   7752: 
1.366     albertel 7753: sub rndseed_CODE_64bit {
                   7754:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7755:     {
1.366     albertel 7756: 	use integer;
1.443     albertel 7757: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7758: 	my $symbseed=numval2($symb);
1.491     albertel 7759: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7760: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7761: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7762: 	my $num1=$symbseed+$CODEchck;
                   7763: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7764: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7765: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7766: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7767: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7768: 	return "$num1:$num2";
1.366     albertel 7769:     }
                   7770: }
                   7771: 
1.575     albertel 7772: sub rndseed_CODE_64bit4 {
                   7773:     my ($symb,$courseid,$domain,$username)=@_;
                   7774:     {
                   7775: 	use integer;
                   7776: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7777: 	my $symbseed=numval3($symb);
                   7778: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7779: 	my $CODEseed=numval3(&getCODE());
                   7780: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7781: 	my $num1=$symbseed+$CODEchck;
                   7782: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7783: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7784: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7785: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7786: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7787: 	return "$num1:$num2";
                   7788:     }
                   7789: }
                   7790: 
1.675     albertel 7791: sub rndseed_CODE_64bit5 {
                   7792:     my ($symb,$courseid,$domain,$username)=@_;
                   7793:     my $code = &getCODE();
                   7794:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7795:     return "$num1:$num2";
                   7796: }
                   7797: 
1.366     albertel 7798: sub setup_random_from_rndseed {
                   7799:     my ($rndseed)=@_;
1.503     albertel 7800:     if ($rndseed =~/([,:])/) {
                   7801: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7802: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7803:     } else {
                   7804: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7805:     }
1.36      albertel 7806: }
                   7807: 
1.474     albertel 7808: sub latest_receipt_algorithm_id {
1.835     albertel 7809:     return 'receipt3';
1.474     albertel 7810: }
                   7811: 
1.480     www      7812: sub recunique {
                   7813:     my $fucourseid=shift;
                   7814:     my $unique;
1.835     albertel 7815:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7816: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7817: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7818:     } else {
                   7819: 	$unique=$perlvar{'lonReceipt'};
                   7820:     }
                   7821:     return unpack("%32C*",$unique);
                   7822: }
                   7823: 
                   7824: sub recprefix {
                   7825:     my $fucourseid=shift;
                   7826:     my $prefix;
1.835     albertel 7827:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7828: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7829: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7830:     } else {
                   7831: 	$prefix=$perlvar{'lonHostID'};
                   7832:     }
                   7833:     return unpack("%32C*",$prefix);
                   7834: }
                   7835: 
1.76      www      7836: sub ireceipt {
1.474     albertel 7837:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7838: 
                   7839:     my $return =&recprefix($fucourseid).'-';
                   7840: 
                   7841:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7842: 	$env{'request.state'} eq 'construct') {
                   7843: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7844: 	return $return;
                   7845:     }
                   7846: 
1.76      www      7847:     my $cuname=unpack("%32C*",$funame);
                   7848:     my $cudom=unpack("%32C*",$fudom);
                   7849:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7850:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7851:     my $cunique=&recunique($fucourseid);
1.474     albertel 7852:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7853:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7854: 
1.790     albertel 7855: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7856: 			       
                   7857: 	$return.= ($cunique%$cuname+
                   7858: 		   $cunique%$cudom+
                   7859: 		   $cusymb%$cuname+
                   7860: 		   $cusymb%$cudom+
                   7861: 		   $cucourseid%$cuname+
                   7862: 		   $cucourseid%$cudom+
                   7863: 		   $cpart%$cuname+
                   7864: 		   $cpart%$cudom);
                   7865:     } else {
                   7866: 	$return.= ($cunique%$cuname+
                   7867: 		   $cunique%$cudom+
                   7868: 		   $cusymb%$cuname+
                   7869: 		   $cusymb%$cudom+
                   7870: 		   $cucourseid%$cuname+
                   7871: 		   $cucourseid%$cudom);
                   7872:     }
                   7873:     return $return;
1.76      www      7874: }
                   7875: 
                   7876: sub receipt {
1.474     albertel 7877:     my ($part)=@_;
1.790     albertel 7878:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7879:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7880: }
1.260     ng       7881: 
1.790     albertel 7882: sub whichuser {
                   7883:     my ($passedsymb)=@_;
                   7884:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7885:     if (defined($env{'form.grade_symb'})) {
                   7886: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7887: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7888: 	if (!$allowed &&
                   7889: 	    exists($env{'request.course.sec'}) &&
                   7890: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7891: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7892: 			      '/'.$env{'request.course.sec'});
                   7893: 	}
                   7894: 	if ($allowed) {
                   7895: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7896: 	    $courseid=$tmp_courseid;
                   7897: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7898: 	    ($name)=&get_env_multiple('form.grade_username');
                   7899: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7900: 	}
                   7901:     }
                   7902:     if (!$passedsymb) {
                   7903: 	$symb=&symbread();
                   7904:     } else {
                   7905: 	$symb=$passedsymb;
                   7906:     }
                   7907:     $courseid=$env{'request.course.id'};
                   7908:     $domain=$env{'user.domain'};
                   7909:     $name=$env{'user.name'};
                   7910:     if ($name eq 'public' && $domain eq 'public') {
                   7911: 	if (!defined($env{'form.username'})) {
                   7912: 	    $env{'form.username'}.=time.rand(10000000);
                   7913: 	}
                   7914: 	$name.=$env{'form.username'};
                   7915:     }
                   7916:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7917: 
                   7918: }
                   7919: 
1.36      albertel 7920: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7921: # returns either the contents of the file or 
                   7922: # -1 if the file doesn't exist
1.481     raeburn  7923: #
                   7924: # if the target is a file that was uploaded via DOCS, 
                   7925: # a check will be made to see if a current copy exists on the local server,
                   7926: # if it does this will be served, otherwise a copy will be retrieved from
                   7927: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7928: # the local server.   
1.472     albertel 7929: 
1.36      albertel 7930: sub getfile {
1.538     albertel 7931:     my ($file) = @_;
1.609     banghart 7932:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7933:     &repcopy($file);
                   7934:     return &readfile($file);
                   7935: }
                   7936: 
                   7937: sub repcopy_userfile {
                   7938:     my ($file)=@_;
1.609     banghart 7939:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7940:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7941:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7942: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7943:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7944:     if (-e "$file") {
1.828     www      7945: # we already have a local copy, check it out
1.538     albertel 7946: 	my @fileinfo = stat($file);
1.828     www      7947: 	my $rtncode;
                   7948: 	my $info;
1.538     albertel 7949: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7950: 	if ($lwpresp ne 'ok') {
1.828     www      7951: # there is no such file anymore, even though we had a local copy
1.482     albertel 7952: 	    if ($rtncode eq '404') {
1.538     albertel 7953: 		unlink($file);
1.482     albertel 7954: 	    }
                   7955: 	    return -1;
                   7956: 	}
                   7957: 	if ($info < $fileinfo[9]) {
1.828     www      7958: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7959: 	    return 'ok';
1.828     www      7960: 	} else {
                   7961: # the file is outdated, get rid of it
                   7962: 	    unlink($file);
1.482     albertel 7963: 	}
1.828     www      7964:     }
                   7965: # one way or the other, at this point, we don't have the file
                   7966: # construct the correct path for the file
                   7967:     my @parts = ($cdom,$cnum); 
                   7968:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7969: 	push @parts, split(/\//,$1);
                   7970:     }
                   7971:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7972:     foreach my $part (@parts) {
                   7973: 	$path .= '/'.$part;
                   7974: 	if (!-e $path) {
                   7975: 	    mkdir($path,0770);
1.482     albertel 7976: 	}
                   7977:     }
1.828     www      7978: # now the path exists for sure
                   7979: # get a user agent
                   7980:     my $ua=new LWP::UserAgent;
                   7981:     my $transferfile=$file.'.in.transfer';
                   7982: # FIXME: this should flock
                   7983:     if (-e $transferfile) { return 'ok'; }
                   7984:     my $request;
                   7985:     $uri=~s/^\///;
1.838     albertel 7986:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7987:     my $response=$ua->request($request,$transferfile);
                   7988: # did it work?
                   7989:     if ($response->is_error()) {
                   7990: 	unlink($transferfile);
                   7991: 	&logthis("Userfile repcopy failed for $uri");
                   7992: 	return -1;
                   7993:     }
                   7994: # worked, rename the transfer file
                   7995:     rename($transferfile,$file);
1.607     raeburn  7996:     return 'ok';
1.481     raeburn  7997: }
                   7998: 
1.517     albertel 7999: sub tokenwrapper {
                   8000:     my $uri=shift;
1.552     albertel 8001:     $uri=~s|^http\://([^/]+)||;
                   8002:     $uri=~s|^/||;
1.620     albertel 8003:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8004:     my $token=$1;
1.552     albertel 8005:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8006:     if ($udom && $uname && $file) {
                   8007: 	$file=~s|(\?\.*)*$||;
1.620     albertel 8008:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 8009:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8010:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8011:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8012:     } else {
                   8013:         return '/adm/notfound.html';
                   8014:     }
                   8015: }
                   8016: 
1.828     www      8017: # call with reqtype HEAD: get last modification time
                   8018: # call with reqtype GET: get the file contents
                   8019: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8020: #
1.481     raeburn  8021: sub getuploaded {
                   8022:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8023:     $uri=~s/^\///;
1.838     albertel 8024:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8025:     my $ua=new LWP::UserAgent;
                   8026:     my $request=new HTTP::Request($reqtype,$uri);
                   8027:     my $response=$ua->request($request);
                   8028:     $$rtncode = $response->code;
1.482     albertel 8029:     if (! $response->is_success()) {
                   8030: 	return 'failed';
                   8031:     }      
                   8032:     if ($reqtype eq 'HEAD') {
1.486     www      8033: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8034:     } elsif ($reqtype eq 'GET') {
                   8035: 	$$info = $response->content;
1.472     albertel 8036:     }
1.482     albertel 8037:     return 'ok';
1.36      albertel 8038: }
                   8039: 
1.481     raeburn  8040: sub readfile {
                   8041:     my $file = shift;
                   8042:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8043:     my $fh;
                   8044:     open($fh,"<$file");
                   8045:     my $a='';
1.800     albertel 8046:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8047:     return $a;
                   8048: }
                   8049: 
1.36      albertel 8050: sub filelocation {
1.590     banghart 8051:     my ($dir,$file) = @_;
                   8052:     my $location;
                   8053:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8054: 
                   8055:     if ($file =~ m-^/adm/-) {
                   8056: 	$file=~s-^/adm/wrapper/-/-;
                   8057: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8058:     }
1.882     albertel 8059: 
1.590     banghart 8060:     if ($file=~m:^/~:) { # is a contruction space reference
                   8061:         $location = $file;
                   8062:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8063:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8064: 	# is a correct contruction space reference
                   8065:         $location = $file;
1.609     banghart 8066:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8067:         my ($udom,$uname,$filename)=
1.811     albertel 8068:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8069:         my $home=&homeserver($uname,$udom);
                   8070:         my $is_me=0;
                   8071:         my @ids=&current_machine_ids();
                   8072:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8073:         if ($is_me) {
1.740     www      8074:   	    $location=&propath($udom,$uname).
1.590     banghart 8075:   	      '/userfiles/'.$filename;
                   8076:         } else {
                   8077:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8078:   	      $udom.'/'.$uname.'/'.$filename;
                   8079:         }
1.882     albertel 8080:     } elsif ($file =~ m-^/adm/-) {
                   8081: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8082:     } else {
                   8083:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8084:         $file=~s:^/res/:/:;
                   8085:         if ( !( $file =~ m:^/:) ) {
                   8086:             $location = $dir. '/'.$file;
                   8087:         } else {
                   8088:             $location = '/home/httpd/html/res'.$file;
                   8089:         }
1.59      albertel 8090:     }
1.590     banghart 8091:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8092:     while ($location=~m{/\.\./}) {
                   8093: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8094: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8095: 	} else {
                   8096: 	    $location=~ s{/\.\./}{/}g;
                   8097: 	}
                   8098:     } #remove dir/..
1.590     banghart 8099:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8100:     return $location;
1.46      www      8101: }
1.36      albertel 8102: 
1.46      www      8103: sub hreflocation {
                   8104:     my ($dir,$file)=@_;
1.460     albertel 8105:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8106: 	$file=filelocation($dir,$file);
1.700     albertel 8107:     } elsif ($file=~m-^/adm/-) {
                   8108: 	$file=~s-^/adm/wrapper/-/-;
                   8109: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8110:     }
                   8111:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8112: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8113:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8114: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8115:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8116: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8117: 	    -/uploaded/$1/$2/-x;
1.46      www      8118:     }
1.913     albertel 8119:     if ($file=~ m{^/userfiles/}) {
                   8120: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8121:     }
1.462     albertel 8122:     return $file;
1.465     albertel 8123: }
                   8124: 
                   8125: sub current_machine_domains {
1.853     albertel 8126:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8127: }
                   8128: 
                   8129: sub machine_domains {
                   8130:     my ($hostname) = @_;
1.465     albertel 8131:     my @domains;
1.838     albertel 8132:     my %hostname = &all_hostnames();
1.465     albertel 8133:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8134: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8135: 	if ($hostname eq $name) {
1.844     albertel 8136: 	    push(@domains,&host_domain($id));
1.465     albertel 8137: 	}
                   8138:     }
                   8139:     return @domains;
                   8140: }
                   8141: 
                   8142: sub current_machine_ids {
1.853     albertel 8143:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8144: }
                   8145: 
                   8146: sub machine_ids {
                   8147:     my ($hostname) = @_;
                   8148:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8149:     my @ids;
1.888     albertel 8150:     my %name_to_host = &all_names();
1.889     albertel 8151:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8152: 	return @{ $name_to_host{$hostname} };
                   8153:     }
                   8154:     return;
1.31      www      8155: }
                   8156: 
1.824     raeburn  8157: sub additional_machine_domains {
                   8158:     my @domains;
                   8159:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8160:     while( my $line = <$fh>) {
                   8161:         $line =~ s/\s//g;
                   8162:         push(@domains,$line);
                   8163:     }
                   8164:     return @domains;
                   8165: }
                   8166: 
                   8167: sub default_login_domain {
                   8168:     my $domain = $perlvar{'lonDefDomain'};
                   8169:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8170:     foreach my $posdom (&current_machine_domains(),
                   8171:                         &additional_machine_domains()) {
                   8172:         if (lc($posdom) eq lc($testdomain)) {
                   8173:             $domain=$posdom;
                   8174:             last;
                   8175:         }
                   8176:     }
                   8177:     return $domain;
                   8178: }
                   8179: 
1.31      www      8180: # ------------------------------------------------------------- Declutters URLs
                   8181: 
                   8182: sub declutter {
                   8183:     my $thisfn=shift;
1.569     albertel 8184:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8185:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8186:     $thisfn=~s/^\///;
1.697     albertel 8187:     $thisfn=~s|^adm/wrapper/||;
                   8188:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8189:     $thisfn=~s/^res\///;
1.235     www      8190:     $thisfn=~s/\?.+$//;
1.268     www      8191:     return $thisfn;
                   8192: }
                   8193: 
                   8194: # ------------------------------------------------------------- Clutter up URLs
                   8195: 
                   8196: sub clutter {
                   8197:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8198:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8199: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8200:        $thisfn='/res'.$thisfn; 
                   8201:     }
1.694     albertel 8202:     if ($thisfn !~m|/adm|) {
1.695     albertel 8203: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8204: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8205: 	} else {
                   8206: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8207: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8208: 	    if ($embstyle eq 'ssi'
                   8209: 		|| ($embstyle eq 'hdn')
                   8210: 		|| ($embstyle eq 'rat')
                   8211: 		|| ($embstyle eq 'prv')
                   8212: 		|| ($embstyle eq 'ign')) {
                   8213: 		#do nothing with these
                   8214: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8215: 		|| ($embstyle eq 'emb')
                   8216: 		|| ($embstyle eq 'wrp')) {
                   8217: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8218: 	    } elsif ($embstyle eq 'unk'
                   8219: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8220: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8221: 	    } else {
1.718     www      8222: #		&logthis("Got a blank emb style");
1.695     albertel 8223: 	    }
1.694     albertel 8224: 	}
                   8225:     }
1.31      www      8226:     return $thisfn;
1.12      www      8227: }
                   8228: 
1.787     albertel 8229: sub clutter_with_no_wrapper {
                   8230:     my $uri = &clutter(shift);
                   8231:     if ($uri =~ m-^/adm/-) {
                   8232: 	$uri =~ s-^/adm/wrapper/-/-;
                   8233: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8234:     }
                   8235:     return $uri;
                   8236: }
                   8237: 
1.557     albertel 8238: sub freeze_escape {
                   8239:     my ($value)=@_;
                   8240:     if (ref($value)) {
                   8241: 	$value=&nfreeze($value);
                   8242: 	return '__FROZEN__'.&escape($value);
                   8243:     }
                   8244:     return &escape($value);
                   8245: }
                   8246: 
1.11      www      8247: 
1.557     albertel 8248: sub thaw_unescape {
                   8249:     my ($value)=@_;
                   8250:     if ($value =~ /^__FROZEN__/) {
                   8251: 	substr($value,0,10,undef);
                   8252: 	$value=&unescape($value);
                   8253: 	return &thaw($value);
                   8254:     }
                   8255:     return &unescape($value);
                   8256: }
                   8257: 
1.436     albertel 8258: sub correct_line_ends {
                   8259:     my ($result)=@_;
                   8260:     $$result =~s/\r\n/\n/mg;
                   8261:     $$result =~s/\r/\n/mg;
1.415     albertel 8262: }
1.1       albertel 8263: # ================================================================ Main Program
                   8264: 
1.184     www      8265: sub goodbye {
1.204     albertel 8266:    &logthis("Starting Shut down");
1.443     albertel 8267: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8268:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8269: #converted
1.599     albertel 8270: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8271:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8272: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8273: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8274: #1.1 only
1.870     albertel 8275: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8276: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8277: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8278: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8279:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8280:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8281:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8282:    &flushcourselogs();
                   8283:    &logthis("Shutting down");
                   8284: }
                   8285: 
1.852     albertel 8286: sub get_dns {
1.869     albertel 8287:     my ($url,$func,$ignore_cache) = @_;
                   8288:     if (!$ignore_cache) {
                   8289: 	my ($content,$cached)=
                   8290: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8291: 	if ($cached) {
                   8292: 	    &$func($content);
                   8293: 	    return;
                   8294: 	}
                   8295:     }
                   8296: 
                   8297:     my %alldns;
1.852     albertel 8298:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8299:     foreach my $dns (<$config>) {
                   8300: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8301: 	$alldns{$1} = 1;
                   8302:     }
                   8303:     while (%alldns) {
                   8304: 	my ($dns) = keys(%alldns);
                   8305: 	delete($alldns{$dns});
1.852     albertel 8306: 	my $ua=new LWP::UserAgent;
                   8307: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8308: 	my $response=$ua->request($request);
                   8309: 	next if ($response->is_error());
                   8310: 	my @content = split("\n",$response->content);
1.869     albertel 8311: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8312: 	&$func(\@content);
1.869     albertel 8313: 	return;
1.852     albertel 8314:     }
                   8315:     close($config);
1.871     albertel 8316:     my $which = (split('/',$url))[3];
                   8317:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8318:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8319:     my @content = <$config>;
                   8320:     &$func(\@content);
                   8321:     return;
1.852     albertel 8322: }
1.327     albertel 8323: # ------------------------------------------------------------ Read domain file
                   8324: {
1.852     albertel 8325:     my $loaded;
1.846     albertel 8326:     my %domain;
                   8327: 
1.852     albertel 8328:     sub parse_domain_tab {
                   8329: 	my ($lines) = @_;
                   8330: 	foreach my $line (@$lines) {
                   8331: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8332: 
1.846     albertel 8333: 	    chomp($line);
1.852     albertel 8334: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8335: 	    my %this_domain;
                   8336: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8337: 			       'lang_def', 'city', 'longi', 'lati',
                   8338: 			       'primary') {
                   8339: 		$this_domain{$field} = shift(@elements);
                   8340: 	    }
                   8341: 	    $domain{$name} = \%this_domain;
1.852     albertel 8342: 	}
                   8343:     }
1.864     albertel 8344: 
                   8345:     sub reset_domain_info {
                   8346: 	undef($loaded);
                   8347: 	undef(%domain);
                   8348:     }
                   8349: 
1.852     albertel 8350:     sub load_domain_tab {
1.869     albertel 8351: 	my ($ignore_cache) = @_;
                   8352: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8353: 	my $fh;
                   8354: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8355: 	    my @lines = <$fh>;
                   8356: 	    &parse_domain_tab(\@lines);
1.448     albertel 8357: 	}
1.852     albertel 8358: 	close($fh);
                   8359: 	$loaded = 1;
1.327     albertel 8360:     }
1.846     albertel 8361: 
                   8362:     sub domain {
1.852     albertel 8363: 	&load_domain_tab() if (!$loaded);
                   8364: 
1.846     albertel 8365: 	my ($name,$what) = @_;
                   8366: 	return if ( !exists($domain{$name}) );
                   8367: 
                   8368: 	if (!$what) {
                   8369: 	    return $domain{$name}{'description'};
                   8370: 	}
                   8371: 	return $domain{$name}{$what};
                   8372:     }
1.327     albertel 8373: }
                   8374: 
                   8375: 
1.1       albertel 8376: # ------------------------------------------------------------- Read hosts file
                   8377: {
1.838     albertel 8378:     my %hostname;
1.844     albertel 8379:     my %hostdom;
1.845     albertel 8380:     my %libserv;
1.852     albertel 8381:     my $loaded;
1.888     albertel 8382:     my %name_to_host;
1.852     albertel 8383: 
                   8384:     sub parse_hosts_tab {
                   8385: 	my ($file) = @_;
                   8386: 	foreach my $configline (@$file) {
                   8387: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8388: 	    next if ($configline =~ /^\^/);
                   8389: 	    chomp($configline);
                   8390: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8391: 	    $name=~s/\s//g;
                   8392: 	    if ($id && $domain && $role && $name) {
                   8393: 		$hostname{$id}=$name;
1.888     albertel 8394: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8395: 		$hostdom{$id}=$domain;
                   8396: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8397: 	    }
                   8398: 	}
                   8399:     }
1.864     albertel 8400:     
                   8401:     sub reset_hosts_info {
1.897     albertel 8402: 	&purge_remembered();
1.864     albertel 8403: 	&reset_domain_info();
                   8404: 	&reset_hosts_ip_info();
1.892     albertel 8405: 	undef(%name_to_host);
1.864     albertel 8406: 	undef(%hostname);
                   8407: 	undef(%hostdom);
                   8408: 	undef(%libserv);
                   8409: 	undef($loaded);
                   8410:     }
1.1       albertel 8411: 
1.852     albertel 8412:     sub load_hosts_tab {
1.869     albertel 8413: 	my ($ignore_cache) = @_;
                   8414: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8415: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8416: 	my @config = <$config>;
                   8417: 	&parse_hosts_tab(\@config);
                   8418: 	close($config);
                   8419: 	$loaded=1;
1.1       albertel 8420:     }
1.852     albertel 8421: 
1.838     albertel 8422:     sub hostname {
1.852     albertel 8423: 	&load_hosts_tab() if (!$loaded);
                   8424: 
1.838     albertel 8425: 	my ($lonid) = @_;
                   8426: 	return $hostname{$lonid};
                   8427:     }
1.845     albertel 8428: 
1.838     albertel 8429:     sub all_hostnames {
1.852     albertel 8430: 	&load_hosts_tab() if (!$loaded);
                   8431: 
1.838     albertel 8432: 	return %hostname;
                   8433:     }
1.845     albertel 8434: 
1.888     albertel 8435:     sub all_names {
                   8436: 	&load_hosts_tab() if (!$loaded);
                   8437: 
                   8438: 	return %name_to_host;
                   8439:     }
                   8440: 
1.845     albertel 8441:     sub is_library {
1.852     albertel 8442: 	&load_hosts_tab() if (!$loaded);
                   8443: 
1.845     albertel 8444: 	return exists($libserv{$_[0]});
                   8445:     }
                   8446: 
                   8447:     sub all_library {
1.852     albertel 8448: 	&load_hosts_tab() if (!$loaded);
                   8449: 
1.845     albertel 8450: 	return %libserv;
                   8451:     }
                   8452: 
1.841     albertel 8453:     sub get_servers {
1.852     albertel 8454: 	&load_hosts_tab() if (!$loaded);
                   8455: 
1.841     albertel 8456: 	my ($domain,$type) = @_;
                   8457: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8458: 	                                          : %hostname;
                   8459: 	my %result;
1.842     albertel 8460: 	if (ref($domain) eq 'ARRAY') {
                   8461: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8462: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8463: 		    $result{$host} = $hostname;
                   8464: 		}
                   8465: 	    }
                   8466: 	} else {
                   8467: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8468: 		if ($hostdom{$host} eq $domain) {
                   8469: 		    $result{$host} = $hostname;
                   8470: 		}
1.841     albertel 8471: 	    }
                   8472: 	}
                   8473: 	return %result;
                   8474:     }
1.845     albertel 8475: 
1.844     albertel 8476:     sub host_domain {
1.852     albertel 8477: 	&load_hosts_tab() if (!$loaded);
                   8478: 
1.844     albertel 8479: 	my ($lonid) = @_;
                   8480: 	return $hostdom{$lonid};
                   8481:     }
                   8482: 
1.841     albertel 8483:     sub all_domains {
1.852     albertel 8484: 	&load_hosts_tab() if (!$loaded);
                   8485: 
1.841     albertel 8486: 	my %seen;
                   8487: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8488: 	return @uniq;
                   8489:     }
1.1       albertel 8490: }
                   8491: 
1.847     albertel 8492: { 
                   8493:     my %iphost;
1.856     albertel 8494:     my %name_to_ip;
                   8495:     my %lonid_to_ip;
1.869     albertel 8496: 
1.847     albertel 8497:     sub get_hosts_from_ip {
                   8498: 	my ($ip) = @_;
                   8499: 	my %iphosts = &get_iphost();
                   8500: 	if (ref($iphosts{$ip})) {
                   8501: 	    return @{$iphosts{$ip}};
                   8502: 	}
                   8503: 	return;
1.839     albertel 8504:     }
1.864     albertel 8505:     
                   8506:     sub reset_hosts_ip_info {
                   8507: 	undef(%iphost);
                   8508: 	undef(%name_to_ip);
                   8509: 	undef(%lonid_to_ip);
                   8510:     }
1.856     albertel 8511: 
                   8512:     sub get_host_ip {
                   8513: 	my ($lonid) = @_;
                   8514: 	if (exists($lonid_to_ip{$lonid})) {
                   8515: 	    return $lonid_to_ip{$lonid};
                   8516: 	}
                   8517: 	my $name=&hostname($lonid);
                   8518:    	my $ip = gethostbyname($name);
                   8519: 	return if (!$ip || length($ip) ne 4);
                   8520: 	$ip=inet_ntoa($ip);
                   8521: 	$name_to_ip{$name}   = $ip;
                   8522: 	$lonid_to_ip{$lonid} = $ip;
                   8523: 	return $ip;
                   8524:     }
1.847     albertel 8525:     
                   8526:     sub get_iphost {
1.869     albertel 8527: 	my ($ignore_cache) = @_;
1.894     albertel 8528: 
1.869     albertel 8529: 	if (!$ignore_cache) {
                   8530: 	    if (%iphost) {
                   8531: 		return %iphost;
                   8532: 	    }
                   8533: 	    my ($ip_info,$cached)=
                   8534: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8535: 	    if ($cached) {
                   8536: 		%iphost      = %{$ip_info->[0]};
                   8537: 		%name_to_ip  = %{$ip_info->[1]};
                   8538: 		%lonid_to_ip = %{$ip_info->[2]};
                   8539: 		return %iphost;
                   8540: 	    }
                   8541: 	}
1.894     albertel 8542: 
                   8543: 	# get yesterday's info for fallback
                   8544: 	my %old_name_to_ip;
                   8545: 	my ($ip_info,$cached)=
                   8546: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8547: 	if ($cached) {
                   8548: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8549: 	}
                   8550: 
1.888     albertel 8551: 	my %name_to_host = &all_names();
                   8552: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8553: 	    my $ip;
                   8554: 	    if (!exists($name_to_ip{$name})) {
                   8555: 		$ip = gethostbyname($name);
                   8556: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8557: 		    if (defined($old_name_to_ip{$name})) {
                   8558: 			$ip = $old_name_to_ip{$name};
                   8559: 			&logthis("Can't find $name defaulting to old $ip");
                   8560: 		    } else {
                   8561: 			&logthis("Name $name no IP found");
                   8562: 			next;
                   8563: 		    }
                   8564: 		} else {
                   8565: 		    $ip=inet_ntoa($ip);
1.847     albertel 8566: 		}
                   8567: 		$name_to_ip{$name} = $ip;
                   8568: 	    } else {
                   8569: 		$ip = $name_to_ip{$name};
1.653     albertel 8570: 	    }
1.888     albertel 8571: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8572: 		$lonid_to_ip{$id} = $ip;
                   8573: 	    }
                   8574: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8575: 	}
1.869     albertel 8576: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8577: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8578: 				      48*60*60);
1.869     albertel 8579: 
1.847     albertel 8580: 	return %iphost;
1.598     albertel 8581:     }
                   8582: }
                   8583: 
1.862     albertel 8584: BEGIN {
                   8585: 
                   8586: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8587:     unless ($readit) {
                   8588: {
                   8589:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8590:     %perlvar = (%perlvar,%{$configvars});
                   8591: }
                   8592: 
                   8593: 
1.1       albertel 8594: # ------------------------------------------------------ Read spare server file
                   8595: {
1.448     albertel 8596:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8597: 
                   8598:     while (my $configline=<$config>) {
                   8599:        chomp($configline);
1.284     matthew  8600:        if ($configline) {
1.784     albertel 8601: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8602: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8603: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8604:        }
                   8605:     }
1.448     albertel 8606:     close($config);
1.1       albertel 8607: }
1.11      www      8608: # ------------------------------------------------------------ Read permissions
                   8609: {
1.448     albertel 8610:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8611: 
                   8612:     while (my $configline=<$config>) {
1.448     albertel 8613: 	chomp($configline);
                   8614: 	if ($configline) {
                   8615: 	    my ($role,$perm)=split(/ /,$configline);
                   8616: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8617: 	}
1.11      www      8618:     }
1.448     albertel 8619:     close($config);
1.11      www      8620: }
                   8621: 
                   8622: # -------------------------------------------- Read plain texts for permissions
                   8623: {
1.448     albertel 8624:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8625: 
                   8626:     while (my $configline=<$config>) {
1.448     albertel 8627: 	chomp($configline);
                   8628: 	if ($configline) {
1.742     raeburn  8629: 	    my ($short,@plain)=split(/:/,$configline);
                   8630:             %{$prp{$short}} = ();
                   8631: 	    if (@plain > 0) {
                   8632:                 $prp{$short}{'std'} = $plain[0];
                   8633:                 for (my $i=1; $i<@plain; $i++) {
                   8634:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8635:                 }
                   8636:             }
1.448     albertel 8637: 	}
1.135     www      8638:     }
1.448     albertel 8639:     close($config);
1.135     www      8640: }
                   8641: 
                   8642: # ---------------------------------------------------------- Read package table
                   8643: {
1.448     albertel 8644:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8645: 
                   8646:     while (my $configline=<$config>) {
1.483     albertel 8647: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8648: 	chomp($configline);
                   8649: 	my ($short,$plain)=split(/:/,$configline);
                   8650: 	my ($pack,$name)=split(/\&/,$short);
                   8651: 	if ($plain ne '') {
                   8652: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8653: 	    $packagetab{$short}=$plain; 
                   8654: 	}
1.11      www      8655:     }
1.448     albertel 8656:     close($config);
1.329     matthew  8657: }
                   8658: 
                   8659: # ------------- set up temporary directory
                   8660: {
                   8661:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8662: 
1.11      www      8663: }
                   8664: 
1.794     albertel 8665: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8666: 				'compress_threshold'=> 20_000,
                   8667:  			        });
1.185     www      8668: 
1.281     www      8669: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8670: $dumpcount=0;
1.22      www      8671: 
1.163     harris41 8672: &logtouch();
1.672     albertel 8673: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8674: $readit=1;
1.564     albertel 8675:     {
                   8676: 	use integer;
                   8677: 	my $test=(2**32)+1;
1.568     albertel 8678: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8679: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8680:     }
1.195     www      8681: }
1.1       albertel 8682: }
1.179     www      8683: 
1.1       albertel 8684: 1;
1.191     harris41 8685: __END__
                   8686: 
1.243     albertel 8687: =pod
                   8688: 
1.191     harris41 8689: =head1 NAME
                   8690: 
1.243     albertel 8691: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8692: 
                   8693: =head1 SYNOPSIS
                   8694: 
1.243     albertel 8695: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8696: 
                   8697:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8698: 
1.243     albertel 8699: Common parameters:
                   8700: 
                   8701: =over 4
                   8702: 
                   8703: =item *
                   8704: 
                   8705: $uname : an internal username (if $cname expecting a course Id specifically)
                   8706: 
                   8707: =item *
                   8708: 
                   8709: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8710: 
                   8711: =item *
                   8712: 
                   8713: $symb : a resource instance identifier
                   8714: 
                   8715: =item *
                   8716: 
                   8717: $namespace : the name of a .db file that contains the data needed or
                   8718: being set.
                   8719: 
                   8720: =back
                   8721: 
1.394     bowersj2 8722: =head1 OVERVIEW
1.191     harris41 8723: 
1.394     bowersj2 8724: lonnet provides subroutines which interact with the
                   8725: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8726: about classes, users, and resources.
1.243     albertel 8727: 
                   8728: For many of these objects you can also use this to store data about
                   8729: them or modify them in various ways.
1.191     harris41 8730: 
1.394     bowersj2 8731: =head2 Symbs
1.191     harris41 8732: 
1.394     bowersj2 8733: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8734: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8735: map, the resource number of the resource in the map, and the URL of
                   8736: the resource itself. The latter is somewhat redundant, but might help
                   8737: if maps change.
                   8738: 
                   8739: An example is
                   8740: 
                   8741:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8742: 
                   8743: The respective map entry is
                   8744: 
                   8745:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8746:   title="Problem 2">
                   8747:  </resource>
                   8748: 
                   8749: Symbs are used by the random number generator, as well as to store and
                   8750: restore data specific to a certain instance of for example a problem.
                   8751: 
                   8752: =head2 Storing And Retrieving Data
                   8753: 
                   8754: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8755: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8756: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8757: is is the non-critical message twin of cstore. These functions are for
                   8758: handlers to store a perl hash to a user's permanent data space in an
                   8759: easy manner, and to retrieve it again on another call. It is expected
                   8760: that a handler would use this once at the beginning to retrieve data,
                   8761: and then again once at the end to send only the new data back.
                   8762: 
                   8763: The data is stored in the user's data directory on the user's
                   8764: homeserver under the ID of the course.
                   8765: 
                   8766: The hash that is returned by restore will have all of the previous
                   8767: value for all of the elements of the hash.
                   8768: 
                   8769: Example:
                   8770: 
                   8771:  #creating a hash
                   8772:  my %hash;
                   8773:  $hash{'foo'}='bar';
                   8774: 
                   8775:  #storing it
                   8776:  &Apache::lonnet::cstore(\%hash);
                   8777: 
                   8778:  #changing a value
                   8779:  $hash{'foo'}='notbar';
                   8780: 
                   8781:  #adding a new value
                   8782:  $hash{'bar'}='foo';
                   8783:  &Apache::lonnet::cstore(\%hash);
                   8784: 
                   8785:  #retrieving the hash
                   8786:  my %history=&Apache::lonnet::restore();
                   8787: 
                   8788:  #print the hash
                   8789:  foreach my $key (sort(keys(%history))) {
                   8790:    print("\%history{$key} = $history{$key}");
                   8791:  }
                   8792: 
                   8793: Will print out:
1.191     harris41 8794: 
1.394     bowersj2 8795:  %history{1:foo} = bar
                   8796:  %history{1:keys} = foo:timestamp
                   8797:  %history{1:timestamp} = 990455579
                   8798:  %history{2:bar} = foo
                   8799:  %history{2:foo} = notbar
                   8800:  %history{2:keys} = foo:bar:timestamp
                   8801:  %history{2:timestamp} = 990455580
                   8802:  %history{bar} = foo
                   8803:  %history{foo} = notbar
                   8804:  %history{timestamp} = 990455580
                   8805:  %history{version} = 2
                   8806: 
                   8807: Note that the special hash entries C<keys>, C<version> and
                   8808: C<timestamp> were added to the hash. C<version> will be equal to the
                   8809: total number of versions of the data that have been stored. The
                   8810: C<timestamp> attribute will be the UNIX time the hash was
                   8811: stored. C<keys> is available in every historical section to list which
                   8812: keys were added or changed at a specific historical revision of a
                   8813: hash.
                   8814: 
                   8815: B<Warning>: do not store the hash that restore returns directly. This
                   8816: will cause a mess since it will restore the historical keys as if the
                   8817: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8818: 
1.394     bowersj2 8819: Calling convention:
1.191     harris41 8820: 
1.394     bowersj2 8821:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8822:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8823: 
1.394     bowersj2 8824: For more detailed information, see lonnet specific documentation.
1.191     harris41 8825: 
1.394     bowersj2 8826: =head1 RETURN MESSAGES
1.191     harris41 8827: 
1.394     bowersj2 8828: =over 4
1.191     harris41 8829: 
1.394     bowersj2 8830: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8831: 
1.394     bowersj2 8832: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8833: when the connection is brought back up
1.191     harris41 8834: 
1.394     bowersj2 8835: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8836: for later delivery
1.191     harris41 8837: 
1.394     bowersj2 8838: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8839: 
1.394     bowersj2 8840: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8841: that was requested
1.191     harris41 8842: 
1.243     albertel 8843: =back
1.191     harris41 8844: 
1.243     albertel 8845: =head1 PUBLIC SUBROUTINES
1.191     harris41 8846: 
1.243     albertel 8847: =head2 Session Environment Functions
1.191     harris41 8848: 
1.243     albertel 8849: =over 4
1.191     harris41 8850: 
1.394     bowersj2 8851: =item * 
                   8852: X<appenv()>
                   8853: B<appenv(%hash)>: the value of %hash is written to
                   8854: the user envirnoment file, and will be restored for each access this
1.620     albertel 8855: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8856: process
1.191     harris41 8857: 
                   8858: =item *
1.394     bowersj2 8859: X<delenv()>
                   8860: B<delenv($regexp)>: removes all items from the session
                   8861: environment file that matches the regular expression in $regexp. The
1.620     albertel 8862: values are also delted from the current processes %env.
1.191     harris41 8863: 
1.795     albertel 8864: =item * get_env_multiple($name) 
                   8865: 
                   8866: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8867: values may be defined and end up as an array ref.
                   8868: 
                   8869: returns an array of values
                   8870: 
1.243     albertel 8871: =back
                   8872: 
                   8873: =head2 User Information
1.191     harris41 8874: 
1.243     albertel 8875: =over 4
1.191     harris41 8876: 
                   8877: =item *
1.394     bowersj2 8878: X<queryauthenticate()>
                   8879: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8880: authentication scheme
                   8881: 
                   8882: =item *
1.394     bowersj2 8883: X<authenticate()>
                   8884: B<authenticate($uname,$upass,$udom)>: try to
                   8885: authenticate user from domain's lib servers (first use the current
                   8886: one). C<$upass> should be the users password.
1.191     harris41 8887: 
                   8888: =item *
1.394     bowersj2 8889: X<homeserver()>
                   8890: B<homeserver($uname,$udom)>: find the server which has
                   8891: the user's directory and files (there must be only one), this caches
                   8892: the answer, and also caches if there is a borken connection.
1.191     harris41 8893: 
                   8894: =item *
1.394     bowersj2 8895: X<idget()>
                   8896: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8897: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8898: username, and only 1 username per ID in a specific domain) (returns
                   8899: hash: id=>name,id=>name)
1.191     harris41 8900: 
                   8901: =item *
1.394     bowersj2 8902: X<idrget()>
                   8903: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8904: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8905: 
                   8906: =item *
1.394     bowersj2 8907: X<idput()>
                   8908: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8909: 
                   8910: =item *
1.394     bowersj2 8911: X<rolesinit()>
                   8912: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8913: 
                   8914: =item *
1.551     albertel 8915: X<getsection()>
                   8916: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8917: course $cname, return section name/number or '' for "not in course"
                   8918: and '-1' for "no section"
                   8919: 
                   8920: =item *
1.394     bowersj2 8921: X<userenvironment()>
                   8922: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8923: passed in @what from the requested user's environment, returns a hash
                   8924: 
1.858     raeburn  8925: =item * 
                   8926: X<userlog_query()>
1.859     albertel 8927: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8928: activity.log file. %filters defines filters applied when parsing the
                   8929: log file. These can be start or end timestamps, or the type of action
                   8930: - log to look for Login or Logout events, check for Checkin or
                   8931: Checkout, role for role selection. The response is in the form
                   8932: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8933: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8934: 
1.243     albertel 8935: =back
                   8936: 
                   8937: =head2 User Roles
                   8938: 
                   8939: =over 4
                   8940: 
                   8941: =item *
                   8942: 
1.810     raeburn  8943: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8944:  F: full access
                   8945:  U,I,K: authentication modes (cxx only)
                   8946:  '': forbidden
                   8947:  1: user needs to choose course
                   8948:  2: browse allowed
1.766     albertel 8949:  A: passphrase authentication needed
1.243     albertel 8950: 
                   8951: =item *
                   8952: 
                   8953: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8954: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8955: and course level
                   8956: 
                   8957: =item *
                   8958: 
                   8959: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8960: explanation of a user role term
                   8961: 
1.832     raeburn  8962: =item *
                   8963: 
1.935     raeburn  8964: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  8965: All arguments are optional. Returns a hash of a roles, either for
                   8966: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8967: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  8968: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   8969: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   8970: For each key, value is set to colon-separated start and end times for
                   8971: the role.  If no username and domain are specified, will default to
1.934     raeburn  8972: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  8973: of role statuses (active, future or previous), roles 
                   8974: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8975: to restrict the list of roles reported. If no array ref is 
                   8976: provided for types, will default to return only active roles.
1.834     albertel 8977: 
1.243     albertel 8978: =back
                   8979: 
                   8980: =head2 User Modification
                   8981: 
                   8982: =over 4
                   8983: 
                   8984: =item *
                   8985: 
                   8986: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8987: user for the level given by URL.  Optional start and end dates (leave empty
                   8988: string or zero for "no date")
1.191     harris41 8989: 
                   8990: =item *
                   8991: 
1.243     albertel 8992: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8993: change a users, password, possible return values are: ok,
                   8994: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8995: refused
1.191     harris41 8996: 
                   8997: =item *
                   8998: 
1.243     albertel 8999: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9000: 
                   9001: =item *
                   9002: 
1.243     albertel 9003: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   9004: modify user
1.191     harris41 9005: 
                   9006: =item *
                   9007: 
1.286     matthew  9008: modifystudent
                   9009: 
                   9010: modify a students enrollment and identification information.
                   9011: The course id is resolved based on the current users environment.  
                   9012: This means the envoking user must be a course coordinator or otherwise
                   9013: associated with a course.
                   9014: 
1.297     matthew  9015: This call is essentially a wrapper for lonnet::modifyuser and
                   9016: lonnet::modify_student_enrollment
1.286     matthew  9017: 
                   9018: Inputs: 
                   9019: 
                   9020: =over 4
                   9021: 
                   9022: =item B<$udom> Students loncapa domain
                   9023: 
                   9024: =item B<$uname> Students loncapa login name
                   9025: 
                   9026: =item B<$uid> Students id/student number
                   9027: 
                   9028: =item B<$umode> Students authentication mode
                   9029: 
                   9030: =item B<$upass> Students password
                   9031: 
                   9032: =item B<$first> Students first name
                   9033: 
                   9034: =item B<$middle> Students middle name
                   9035: 
                   9036: =item B<$last> Students last name
                   9037: 
                   9038: =item B<$gene> Students generation
                   9039: 
                   9040: =item B<$usec> Students section in course
                   9041: 
                   9042: =item B<$end> Unix time of the roles expiration
                   9043: 
                   9044: =item B<$start> Unix time of the roles start date
                   9045: 
                   9046: =item B<$forceid> If defined, allow $uid to be changed
                   9047: 
                   9048: =item B<$desiredhome> server to use as home server for student
                   9049: 
                   9050: =back
1.297     matthew  9051: 
                   9052: =item *
                   9053: 
                   9054: modify_student_enrollment
                   9055: 
                   9056: Change a students enrollment status in a class.  The environment variable
                   9057: 'role.request.course' must be defined for this function to proceed.
                   9058: 
                   9059: Inputs:
                   9060: 
                   9061: =over 4
                   9062: 
                   9063: =item $udom, students domain
                   9064: 
                   9065: =item $uname, students name
                   9066: 
                   9067: =item $uid, students user id
                   9068: 
                   9069: =item $first, students first name
                   9070: 
                   9071: =item $middle
                   9072: 
                   9073: =item $last
                   9074: 
                   9075: =item $gene
                   9076: 
                   9077: =item $usec
                   9078: 
                   9079: =item $end
                   9080: 
                   9081: =item $start
                   9082: 
                   9083: =back
                   9084: 
1.191     harris41 9085: 
                   9086: =item *
                   9087: 
1.243     albertel 9088: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9089: custom role; give a custom role to a user for the level given by URL.  Specify
                   9090: name and domain of role author, and role name
1.191     harris41 9091: 
                   9092: =item *
                   9093: 
1.243     albertel 9094: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9095: 
                   9096: =item *
                   9097: 
1.243     albertel 9098: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9099: 
                   9100: =back
                   9101: 
                   9102: =head2 Course Infomation
                   9103: 
                   9104: =over 4
1.191     harris41 9105: 
                   9106: =item *
                   9107: 
1.631     albertel 9108: coursedescription($courseid) : returns a hash of information about the
                   9109: specified course id, including all environment settings for the
                   9110: course, the description of the course will be in the hash under the
                   9111: key 'description'
1.191     harris41 9112: 
                   9113: =item *
                   9114: 
1.624     albertel 9115: resdata($name,$domain,$type,@which) : request for current parameter
                   9116: setting for a specific $type, where $type is either 'course' or 'user',
                   9117: @what should be a list of parameters to ask about. This routine caches
                   9118: answers for 5 minutes.
1.243     albertel 9119: 
1.877     foxr     9120: =item *
                   9121: 
                   9122: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9123: data base, returning a hash that is keyed by the resource name and has
                   9124: values that are the resource value.  I believe that the timestamps and
                   9125: versions are also returned.
                   9126: 
                   9127: 
1.243     albertel 9128: =back
                   9129: 
                   9130: =head2 Course Modification
                   9131: 
                   9132: =over 4
1.191     harris41 9133: 
                   9134: =item *
                   9135: 
1.243     albertel 9136: writecoursepref($courseid,%prefs) : write preferences (environment
                   9137: database) for a course
1.191     harris41 9138: 
                   9139: =item *
                   9140: 
1.243     albertel 9141: createcourse($udom,$description,$url) : make/modify course
                   9142: 
                   9143: =back
                   9144: 
                   9145: =head2 Resource Subroutines
                   9146: 
                   9147: =over 4
1.191     harris41 9148: 
                   9149: =item *
                   9150: 
1.243     albertel 9151: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9152: 
                   9153: =item *
                   9154: 
1.243     albertel 9155: repcopy($filename) : subscribes to the requested file, and attempts to
                   9156: replicate from the owning library server, Might return
1.607     raeburn  9157: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9158: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9159: resource. Expects the local filesystem pathname
                   9160: (/home/httpd/html/res/....)
                   9161: 
                   9162: =back
                   9163: 
                   9164: =head2 Resource Information
                   9165: 
                   9166: =over 4
1.191     harris41 9167: 
                   9168: =item *
                   9169: 
1.243     albertel 9170: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9171: a vairety of different possible values, $varname should be a request
                   9172: string, and the other parameters can be used to specify who and what
                   9173: one is asking about.
                   9174: 
                   9175: Possible values for $varname are environment.lastname (or other item
                   9176: from the envirnment hash), user.name (or someother aspect about the
                   9177: user), resource.0.maxtries (or some other part and parameter of a
                   9178: resource)
1.204     albertel 9179: 
                   9180: =item *
                   9181: 
1.243     albertel 9182: directcondval($number) : get current value of a condition; reads from a state
                   9183: string
1.204     albertel 9184: 
                   9185: =item *
                   9186: 
1.243     albertel 9187: condval($condidx) : value of condition index based on state
1.204     albertel 9188: 
                   9189: =item *
                   9190: 
1.243     albertel 9191: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9192: resource's metadata, $what should be either a specific key, or either
                   9193: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9194: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9195: 
                   9196: this function automatically caches all requests
1.191     harris41 9197: 
                   9198: =item *
                   9199: 
1.243     albertel 9200: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9201: network of library servers; returns file handle of where SQL and regex results
                   9202: will be stored for query
1.191     harris41 9203: 
                   9204: =item *
                   9205: 
1.243     albertel 9206: symbread($filename) : return symbolic list entry (filename argument optional);
                   9207: returns the data handle
1.191     harris41 9208: 
                   9209: =item *
                   9210: 
1.243     albertel 9211: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9212: a possible symb for the URL in $thisfn, and if is an encryypted
                   9213: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9214: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9215: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9216: 
1.191     harris41 9217: 
                   9218: =item *
                   9219: 
1.243     albertel 9220: symbclean($symb) : removes versions numbers from a symb, returns the
                   9221: cleaned symb
1.191     harris41 9222: 
                   9223: =item *
                   9224: 
1.243     albertel 9225: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9226: course map, user must be in a course for it to work.
1.191     harris41 9227: 
                   9228: =item *
                   9229: 
1.243     albertel 9230: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9231: 
                   9232: =item *
                   9233: 
1.243     albertel 9234: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9235: a random seed, all arguments are optional, if they aren't sent it uses the
                   9236: environment to derive them. Note: if symb isn't sent and it can't get one
                   9237: from &symbread it will use the current time as its return value
1.191     harris41 9238: 
                   9239: =item *
                   9240: 
1.243     albertel 9241: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9242: unfakeable, receipt
1.191     harris41 9243: 
                   9244: =item *
                   9245: 
1.620     albertel 9246: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9247: 
                   9248: =item *
                   9249: 
1.243     albertel 9250: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9251: 
                   9252: =item *
                   9253: 
1.243     albertel 9254: 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 9255: 
                   9256: =item *
                   9257: 
1.243     albertel 9258: 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 9259: 
                   9260: =item *
                   9261: 
1.243     albertel 9262: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9263: 
                   9264: =item *
                   9265: 
1.243     albertel 9266: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9267: forcing spreadsheet to reevaluate the resource scores next time.
                   9268: 
                   9269: =back
                   9270: 
                   9271: =head2 Storing/Retreiving Data
                   9272: 
                   9273: =over 4
1.191     harris41 9274: 
                   9275: =item *
                   9276: 
1.243     albertel 9277: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9278: for this url; hashref needs to be given and should be a \%hashname; the
                   9279: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9280: be derived from the env
1.191     harris41 9281: 
                   9282: =item *
                   9283: 
1.243     albertel 9284: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9285: uses critical subroutine
1.191     harris41 9286: 
                   9287: =item *
                   9288: 
1.243     albertel 9289: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9290: all args are optional
1.191     harris41 9291: 
                   9292: =item *
                   9293: 
1.717     albertel 9294: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9295: dumps the complete (or key matching regexp) namespace into a hash
                   9296: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9297: normally &store()ed into
                   9298: 
                   9299: $range should be either an integer '100' (give me the first 100
                   9300:                                            matching records)
                   9301:               or be  two integers sperated by a - with no spaces
                   9302:                  '30-50' (give me the 30th through the 50th matching
                   9303:                           records)
                   9304: 
                   9305: 
                   9306: =item *
                   9307: 
                   9308: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9309: replaces a &store() version of data with a replacement set of data
                   9310: for a particular resource in a namespace passed in the $storehash hash 
                   9311: reference
                   9312: 
                   9313: =item *
                   9314: 
1.243     albertel 9315: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9316: works very similar to store/cstore, but all data is stored in a
                   9317: temporary location and can be reset using tmpreset, $storehash should
                   9318: be a hash reference, returns nothing on success
1.191     harris41 9319: 
                   9320: =item *
                   9321: 
1.243     albertel 9322: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9323: similar to restore, but all data is stored in a temporary location and
                   9324: can be reset using tmpreset. Returns a hash of values on success,
                   9325: error string otherwise.
1.191     harris41 9326: 
                   9327: =item *
                   9328: 
1.243     albertel 9329: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9330: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9331: 
                   9332: =item *
                   9333: 
1.243     albertel 9334: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9335: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9336: 
                   9337: =item *
                   9338: 
1.243     albertel 9339: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9340: namesp ($udom and $uname are optional)
1.191     harris41 9341: 
                   9342: =item *
                   9343: 
1.702     albertel 9344: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9345: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9346: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9347: 
1.702     albertel 9348: $range should be either an integer '100' (give me the first 100
                   9349:                                            matching records)
                   9350:               or be  two integers sperated by a - with no spaces
                   9351:                  '30-50' (give me the 30th through the 50th matching
                   9352:                           records)
1.449     matthew  9353: =item *
                   9354: 
                   9355: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9356: $store can be a scalar, an array reference, or if the amount to be 
                   9357: incremented is > 1, a hash reference.
                   9358: 
                   9359: ($udom and $uname are optional)
1.191     harris41 9360: 
                   9361: =item *
                   9362: 
1.243     albertel 9363: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9364: ($udom and $uname are optional)
1.191     harris41 9365: 
                   9366: =item *
                   9367: 
1.243     albertel 9368: cput($namespace,$storehash,$udom,$uname) : critical put
                   9369: ($udom and $uname are optional)
1.191     harris41 9370: 
                   9371: =item *
                   9372: 
1.748     albertel 9373: newput($namespace,$storehash,$udom,$uname) :
                   9374: 
                   9375: Attempts to store the items in the $storehash, but only if they don't
                   9376: currently exist, if this succeeds you can be certain that you have 
                   9377: successfully created a new key value pair in the $namespace db.
                   9378: 
                   9379: 
                   9380: Args:
                   9381:  $namespace: name of database to store values to
                   9382:  $storehash: hashref to store to the db
                   9383:  $udom: (optional) domain of user containing the db
                   9384:  $uname: (optional) name of user caontaining the db
                   9385: 
                   9386: Returns:
                   9387:  'ok' -> succeeded in storing all keys of $storehash
                   9388:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9389:                         least <key> already existed in the db (other
                   9390:                         requested keys may also already exist)
                   9391:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9392:  'con_lost' -> unable to contact request server
                   9393:  'refused' -> action was not allowed by remote machine
                   9394: 
                   9395: 
                   9396: =item *
                   9397: 
1.243     albertel 9398: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9399: reference filled in from namesp (encrypts the return communication)
                   9400: ($udom and $uname are optional)
1.191     harris41 9401: 
                   9402: =item *
                   9403: 
1.243     albertel 9404: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9405: critical subroutine
                   9406: 
1.806     raeburn  9407: =item *
                   9408: 
1.860     raeburn  9409: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9410: array reference filled in from namespace found in domain level on either
                   9411: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9412: 
                   9413: =item *
                   9414: 
1.860     raeburn  9415: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9416: domain level either on specified domain server ($uhome) or primary domain 
                   9417: server ($udom and $uhome are optional)
1.806     raeburn  9418: 
1.943     raeburn  9419: =item * 
                   9420: 
                   9421: get_domain_defaults($target_domain) : returns hash with defaults for
                   9422: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9423: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9424: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9425: Values are retrieved from cache (if current), or from domain's configuration.db
                   9426: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9427: or lonTabs/domain.tab. 
                   9428: 
                   9429: %domdefaults = &get_auth_defaults($target_domain);
                   9430: 
1.243     albertel 9431: =back
                   9432: 
                   9433: =head2 Network Status Functions
                   9434: 
                   9435: =over 4
1.191     harris41 9436: 
                   9437: =item *
                   9438: 
                   9439: dirlist($uri) : return directory list based on URI
                   9440: 
                   9441: =item *
                   9442: 
1.243     albertel 9443: spareserver() : find server with least workload from spare.tab
                   9444: 
                   9445: =back
                   9446: 
                   9447: =head2 Apache Request
                   9448: 
                   9449: =over 4
1.191     harris41 9450: 
                   9451: =item *
                   9452: 
1.243     albertel 9453: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9454: localhost, posts hash
                   9455: 
                   9456: =back
                   9457: 
                   9458: =head2 Data to String to Data
                   9459: 
                   9460: =over 4
1.191     harris41 9461: 
                   9462: =item *
                   9463: 
1.243     albertel 9464: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9465: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9466: 
                   9467: =item *
                   9468: 
1.243     albertel 9469: hashref2str($hashref) : convert a hashref into a string complete with
                   9470: escaping and '=' and '&' separators, supports elements that are
                   9471: arrayrefs and hashrefs
1.191     harris41 9472: 
                   9473: =item *
                   9474: 
1.243     albertel 9475: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9476: with escaping and '&' separators, supports elements that are arrayrefs
                   9477: and hashrefs
1.191     harris41 9478: 
                   9479: =item *
                   9480: 
1.243     albertel 9481: str2hash($string) : convert string to hash using unescaping and
                   9482: splitting on '=' and '&', supports elements that are arrayrefs and
                   9483: hashrefs
1.191     harris41 9484: 
                   9485: =item *
                   9486: 
1.243     albertel 9487: str2array($string) : convert string to hash using unescaping and
                   9488: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9489: 
                   9490: =back
                   9491: 
                   9492: =head2 Logging Routines
                   9493: 
                   9494: =over 4
                   9495: 
                   9496: These routines allow one to make log messages in the lonnet.log and
                   9497: lonnet.perm logfiles.
1.191     harris41 9498: 
                   9499: =item *
                   9500: 
1.243     albertel 9501: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9502: 
                   9503: =item *
                   9504: 
1.243     albertel 9505: logthis() : append message to the normal lonnet.log file, it gets
                   9506: preiodically rolled over and deleted.
1.191     harris41 9507: 
                   9508: =item *
                   9509: 
1.243     albertel 9510: logperm() : append a permanent message to lonnet.perm.log, this log
                   9511: file never gets deleted by any automated portion of the system, only
                   9512: messages of critical importance should go in here.
                   9513: 
                   9514: =back
                   9515: 
                   9516: =head2 General File Helper Routines
                   9517: 
                   9518: =over 4
1.191     harris41 9519: 
                   9520: =item *
                   9521: 
1.481     raeburn  9522: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9523: (a) files in /uploaded
                   9524:   (i) If a local copy of the file exists - 
                   9525:       compares modification date of local copy with last-modified date for 
                   9526:       definitive version stored on home server for course. If local copy is 
                   9527:       stale, requests a new version from the home server and stores it. 
                   9528:       If the original has been removed from the home server, then local copy 
                   9529:       is unlinked.
                   9530:   (ii) If local copy does not exist -
                   9531:       requests the file from the home server and stores it. 
                   9532:   
                   9533:   If $caller is 'uploadrep':  
                   9534:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9535:     for request for files originally uploaded via DOCS. 
                   9536:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9537:   
                   9538:   Otherwise:
                   9539:      This indicates a call from the content generation phase of the request.
                   9540:      -  returns the entire contents of the file or -1.
                   9541:      
                   9542: (b) files in /res
                   9543:    - returns the entire contents of a file or -1; 
                   9544:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9545: 
1.712     albertel 9546: 
                   9547: =item *
                   9548: 
                   9549: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9550:                   reference
                   9551: 
                   9552: returns either a stat() list of data about the file or an empty list
                   9553: if the file doesn't exist or couldn't find out about it (connection
                   9554: problems or user unknown)
                   9555: 
1.191     harris41 9556: =item *
                   9557: 
1.243     albertel 9558: filelocation($dir,$file) : returns file system location of a file
                   9559: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9560: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9561: and a file of ../bob will become /a/bob)
1.191     harris41 9562: 
                   9563: =item *
                   9564: 
                   9565: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9566: filelocation except for hrefs
                   9567: 
                   9568: =item *
                   9569: 
                   9570: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9571: 
1.243     albertel 9572: =back
                   9573: 
1.608     albertel 9574: =head2 Usererfile file routines (/uploaded*)
                   9575: 
                   9576: =over 4
                   9577: 
                   9578: =item *
                   9579: 
                   9580: userfileupload(): main rotine for putting a file in a user or course's
                   9581:                   filespace, arguments are,
                   9582: 
1.620     albertel 9583:  formname - required - this is the name of the element in $env where the
1.608     albertel 9584:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9585:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9586:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9587:  coursedoc - if true, store the file in the course of the active role
                   9588:              of the current user
                   9589:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9590:          if undefined, it will be placed in "unknown"
                   9591: 
                   9592:  (This routine calls clean_filename() to remove any dangerous
                   9593:  characters from the filename, and then calls finuserfileupload() to
                   9594:  complete the transaction)
                   9595: 
                   9596:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9597:  and /adm/notfound.html if unsuccessful
                   9598: 
                   9599: =item *
                   9600: 
                   9601: clean_filename(): routine for cleaing a filename up for storage in
                   9602:                  userfile space, argument is:
                   9603: 
                   9604:  filename - proposed filename
                   9605: 
                   9606: returns: the new clean filename
                   9607: 
                   9608: =item *
                   9609: 
                   9610: finishuserfileupload(): routine that creaes and sends the file to
                   9611: userspace, probably shouldn't be called directly
                   9612: 
                   9613:   docuname: username or courseid of destination for the file
                   9614:   docudom: domain of user/course of destination for the file
                   9615:   formname: same as for userfileupload()
                   9616:   fname: filename (inculding subdirectories) for the file
                   9617: 
                   9618:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9619:  and /adm/notfound.html if unsuccessful
                   9620: 
                   9621: =item *
                   9622: 
                   9623: renameuserfile(): renames an existing userfile to a new name
                   9624: 
                   9625:   Args:
                   9626:    docuname: username or courseid of destination for the file
                   9627:    docudom: domain of user/course of destination for the file
                   9628:    old: current file name (including any subdirs under userfiles)
                   9629:    new: desired file name (including any subdirs under userfiles)
                   9630: 
                   9631: =item *
                   9632: 
                   9633: mkdiruserfile(): creates a directory is a userfiles dir
                   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:    dir: dir to create (including any subdirs under userfiles)
                   9639: 
                   9640: =item *
                   9641: 
                   9642: removeuserfile(): removes a file that exists in userfiles
                   9643: 
                   9644:   Args:
                   9645:    docuname: username or courseid of destination for the file
                   9646:    docudom: domain of user/course of destination for the file
                   9647:    fname: filname to delete (including any subdirs under userfiles)
                   9648: 
                   9649: =item *
                   9650: 
                   9651: removeuploadedurl(): convience function for removeuserfile()
                   9652: 
                   9653:   Args:
                   9654:    url:  a full /uploaded/... url to delete
                   9655: 
1.747     albertel 9656: =item * 
                   9657: 
                   9658: get_portfile_permissions():
                   9659:   Args:
                   9660:     domain: domain of user or course contain the portfolio files
                   9661:     user: name of user or num of course contain the portfolio files
                   9662:   Returns:
                   9663:     hashref of a dump of the proper file_permissions.db
                   9664:    
                   9665: 
                   9666: =item * 
                   9667: 
                   9668: get_access_controls():
                   9669: 
                   9670: Args:
                   9671:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9672:   group: (optional) the group you want the files associated with
                   9673:   file: (optional) the file you want access info on
                   9674: 
                   9675: Returns:
1.749     raeburn  9676:     a hash (keys are file names) of hashes containing
                   9677:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9678:         values are XML containing access control settings (see below) 
1.747     albertel 9679: 
                   9680: Internal notes:
                   9681: 
1.749     raeburn  9682:  access controls are stored in file_permissions.db as key=value pairs.
                   9683:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9684:         where scope -> public,guest,course,group,domains or users.
                   9685:               end -> UNIX time for end of access (0 -> no end date)
                   9686:               start -> UNIX time for start of access
                   9687: 
                   9688:     value -> XML description of access control
                   9689:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9690:             <start></start>
                   9691:             <end></end>
                   9692: 
                   9693:             <password></password>  for scope type = guest
                   9694: 
                   9695:             <domain></domain>     for scope type = course or group
                   9696:             <number></number>
                   9697:             <roles id="">
                   9698:              <role></role>
                   9699:              <access></access>
                   9700:              <section></section>
                   9701:              <group></group>
                   9702:             </roles>
                   9703: 
                   9704:             <dom></dom>         for scope type = domains
                   9705: 
                   9706:             <users>             for scope type = users
                   9707:              <user>
                   9708:               <uname></uname>
                   9709:               <udom></udom>
                   9710:              </user>
                   9711:             </users>
                   9712:            </scope> 
                   9713:               
                   9714:  Access data is also aggregated for each file in an additional key=value pair:
                   9715:  key -> path to file/file_name\0accesscontrol 
                   9716:  value -> reference to hash
                   9717:           hash contains key = value pairs
                   9718:           where key = uniqueID:scope_end_start
                   9719:                 value = UNIX time record was last updated
                   9720: 
                   9721:           Used to improve speed of look-ups of access controls for each file.  
                   9722:  
                   9723:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9724: 
                   9725: modify_access_controls():
                   9726: 
                   9727: Modifies access controls for a portfolio file
                   9728: Args
                   9729: 1. file name
                   9730: 2. reference to hash of required changes,
                   9731: 3. domain
                   9732: 4. username
                   9733:   where domain,username are the domain of the portfolio owner 
                   9734:   (either a user or a course) 
                   9735: 
                   9736: Returns:
                   9737: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9738: 2. result of deletions ('ok' or 'error', with error message).
                   9739: 3. reference to hash of any new or updated access controls.
                   9740: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9741:    key = integer (inbound ID)
                   9742:    value = uniqueID  
1.747     albertel 9743: 
1.608     albertel 9744: =back
                   9745: 
1.243     albertel 9746: =head2 HTTP Helper Routines
                   9747: 
                   9748: =over 4
                   9749: 
1.191     harris41 9750: =item *
                   9751: 
                   9752: escape() : unpack non-word characters into CGI-compatible hex codes
                   9753: 
                   9754: =item *
                   9755: 
                   9756: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9757: 
1.243     albertel 9758: =back
                   9759: 
                   9760: =head1 PRIVATE SUBROUTINES
                   9761: 
                   9762: =head2 Underlying communication routines (Shouldn't call)
                   9763: 
                   9764: =over 4
                   9765: 
                   9766: =item *
                   9767: 
                   9768: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9769: 
                   9770: =item *
                   9771: 
                   9772: reply() : uses subreply to send a message to remote machine, logs all failures
                   9773: 
                   9774: =item *
                   9775: 
                   9776: critical() : passes a critical message to another server; if cannot
                   9777: get through then place message in connection buffer directory and
                   9778: returns con_delayed, if incapable of saving message, returns
                   9779: con_failed
                   9780: 
                   9781: =item *
                   9782: 
                   9783: reconlonc() : tries to reconnect lonc client processes.
                   9784: 
                   9785: =back
                   9786: 
                   9787: =head2 Resource Access Logging
                   9788: 
                   9789: =over 4
                   9790: 
                   9791: =item *
                   9792: 
                   9793: flushcourselogs() : flush (save) buffer logs and access logs
                   9794: 
                   9795: =item *
                   9796: 
                   9797: courselog($what) : save message for course in hash
                   9798: 
                   9799: =item *
                   9800: 
                   9801: courseacclog($what) : save message for course using &courselog().  Perform
                   9802: special processing for specific resource types (problems, exams, quizzes, etc).
                   9803: 
1.191     harris41 9804: =item *
                   9805: 
                   9806: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9807: as a PerlChildExitHandler
1.243     albertel 9808: 
                   9809: =back
                   9810: 
                   9811: =head2 Other
                   9812: 
                   9813: =over 4
                   9814: 
                   9815: =item *
                   9816: 
                   9817: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9818: 
                   9819: =back
                   9820: 
                   9821: =cut
1.877     foxr     9822: 

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