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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.891   ! albertel    4: # $Id: lonnet.pm,v 1.890 2007/06/13 03:00:59 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.891   ! albertel  217:     my ($lonid) = @_;
        !           218:     my $hostname = &hostname($lonid);
        !           219:     if ($lonid) {
        !           220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
        !           221: 	if ($hostname && -e $peerfile) {
        !           222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
        !           223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
        !           224: 					     Type    => SOCK_STREAM,
        !           225: 					     Timeout => 10);
        !           226: 	    if ($client) {
        !           227: 		print $client ("reset_retries\n");
        !           228: 		my $answer=<$client>;
        !           229: 		#reset just this one.
        !           230: 	    }
        !           231: 	}
        !           232: 	return;
        !           233:     }
        !           234: 
1.836     www       235:     &logthis("Trying to reconnect lonc");
1.1       albertel  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  237:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  238: 	my $loncpid=<$fh>;
                    239:         chomp($loncpid);
                    240:         if (kill 0 => $loncpid) {
                    241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    242:             kill USR1 => $loncpid;
                    243:             sleep 1;
1.836     www       244:          } else {
1.12      www       245: 	    &logthis(
1.672     albertel  246:                "<font color=\"blue\">WARNING:".
1.12      www       247:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  248:         }
                    249:     } else {
1.836     www       250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  251:     }
                    252: }
                    253: 
                    254: # ------------------------------------------------------ Critical communication
1.12      www       255: 
1.1       albertel  256: sub critical {
                    257:     my ($cmd,$server)=@_;
1.838     albertel  258:     unless (&hostname($server)) {
1.672     albertel  259:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       260:                " Critical message to unknown server ($server)</font>");
                    261:         return 'no_such_host';
                    262:     }
1.1       albertel  263:     my $answer=reply($cmd,$server);
                    264:     if ($answer eq 'con_lost') {
                    265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  266: 	my $answer=reply($cmd,$server);
1.1       albertel  267:         if ($answer eq 'con_lost') {
                    268:             my $now=time;
                    269:             my $middlename=$cmd;
1.5       www       270:             $middlename=substr($middlename,0,16);
1.1       albertel  271:             $middlename=~s/\W//g;
                    272:             my $dfilename=
1.305     www       273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    274:             $dumpcount++;
1.1       albertel  275:             {
1.448     albertel  276: 		my $dfh;
                    277: 		if (open($dfh,">$dfilename")) {
                    278: 		    print $dfh "$cmd\n"; 
                    279: 		    close($dfh);
                    280: 		}
1.1       albertel  281:             }
                    282:             sleep 2;
                    283:             my $wcmd='';
                    284:             {
1.448     albertel  285: 		my $dfh;
                    286: 		if (open($dfh,"<$dfilename")) {
                    287: 		    $wcmd=<$dfh>; 
                    288: 		    close($dfh);
                    289: 		}
1.1       albertel  290:             }
                    291:             chomp($wcmd);
1.7       www       292:             if ($wcmd eq $cmd) {
1.672     albertel  293: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       294:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  295:                 &logperm("D:$server:$cmd");
                    296: 	        return 'con_delayed';
                    297:             } else {
1.672     albertel  298:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       299:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  300:                 &logperm("F:$server:$cmd");
                    301:                 return 'con_failed';
                    302:             }
                    303:         }
                    304:     }
                    305:     return $answer;
1.405     albertel  306: }
                    307: 
1.755     albertel  308: # ------------------------------------------- check if return value is an error
                    309: 
                    310: sub error {
                    311:     my ($result) = @_;
1.756     albertel  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  313: 	if ($2 == 2) { return undef; }
                    314: 	return $1;
                    315:     }
                    316:     return undef;
                    317: }
                    318: 
1.783     albertel  319: sub convert_and_load_session_env {
                    320:     my ($lonidsdir,$handle)=@_;
                    321:     my @profile;
                    322:     {
                    323: 	open(my $idf,"$lonidsdir/$handle.id");
                    324: 	flock($idf,LOCK_SH);
                    325: 	@profile=<$idf>;
                    326: 	close($idf);
                    327:     }
                    328:     my %temp_env;
                    329:     foreach my $line (@profile) {
1.786     albertel  330: 	if ($line !~ m/=/) {
                    331: 	    return 0;
                    332: 	}
1.783     albertel  333: 	chomp($line);
                    334: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    335: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    336:     }
                    337:     unlink("$lonidsdir/$handle.id");
                    338:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    339: 	    0640)) {
                    340: 	%disk_env = %temp_env;
                    341: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    342: 	untie(%disk_env);
                    343:     }
1.786     albertel  344:     return 1;
1.783     albertel  345: }
                    346: 
1.374     www       347: # ------------------------------------------- Transfer profile into environment
1.780     albertel  348: my $env_loaded;
                    349: sub transfer_profile_to_env {
1.788     albertel  350:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    351:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       352: 
1.720     albertel  353:     if (!defined($lonidsdir)) {
                    354: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    355:     }
                    356:     if (!defined($handle)) {
                    357:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    358:     }
                    359: 
1.786     albertel  360:     my $convert;
                    361:     {
                    362:     	open(my $idf,"$lonidsdir/$handle.id");
                    363: 	flock($idf,LOCK_SH);
                    364: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    365: 		&GDBM_READER(),0640)) {
                    366: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    367: 	    untie(%disk_env);
                    368: 	} else {
                    369: 	    $convert = 1;
                    370: 	}
                    371:     }
                    372:     if ($convert) {
                    373: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    374: 	    &logthis("Failed to load session, or convert session.");
                    375: 	}
1.374     www       376:     }
1.783     albertel  377: 
1.786     albertel  378:     my %remove;
1.783     albertel  379:     while ( my $envname = each(%env) ) {
1.433     matthew   380:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    381:             if ($time < time-300) {
1.783     albertel  382:                 $remove{$key}++;
1.433     matthew   383:             }
                    384:         }
                    385:     }
1.783     albertel  386: 
1.619     albertel  387:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  388:     $env_loaded=1;
1.783     albertel  389:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   390:         &delenv($expired_key);
1.374     www       391:     }
1.1       albertel  392: }
                    393: 
1.830     albertel  394: sub timed_flock {
                    395:     my ($file,$lock_type) = @_;
                    396:     my $failed=0;
                    397:     eval {
                    398: 	local $SIG{__DIE__}='DEFAULT';
                    399: 	local $SIG{ALRM}=sub {
                    400: 	    $failed=1;
                    401: 	    die("failed lock");
                    402: 	};
                    403: 	alarm(13);
                    404: 	flock($file,$lock_type);
                    405: 	alarm(0);
                    406:     };
                    407:     if ($failed) {
                    408: 	return undef;
                    409:     } else {
                    410: 	return 1;
                    411:     }
                    412: }
                    413: 
1.5       www       414: # ---------------------------------------------------------- Append Environment
                    415: 
                    416: sub appenv {
1.6       www       417:     my %newenv=@_;
1.692     albertel  418:     foreach my $key (keys(%newenv)) {
                    419: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  420:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  421:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       422:                 .'</font>');
1.692     albertel  423: 	    delete($newenv{$key});
1.35      www       424:         } else {
1.692     albertel  425:             $env{$key}=$newenv{$key};
1.35      www       426:         }
1.191     harris41  427:     }
1.830     albertel  428:     open(my $env_file,$env{'user.environment'});
                    429:     if (&timed_flock($env_file,LOCK_EX)
                    430: 	&&
                    431: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    432: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  433: 	while (my ($key,$value) = each(%newenv)) {
                    434: 	    $disk_env{$key} = $value;
1.448     albertel  435: 	}
1.783     albertel  436: 	untie(%disk_env);
1.56      www       437:     }
                    438:     return 'ok';
                    439: }
                    440: # ----------------------------------------------------- Delete from Environment
                    441: 
                    442: sub delenv {
                    443:     my $delthis=shift;
                    444:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  445:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       446:                 "Attempt to delete from environment ".$delthis);
                    447:         return 'error';
                    448:     }
1.830     albertel  449:     open(my $env_file,$env{'user.environment'});
                    450:     if (&timed_flock($env_file,LOCK_EX)
                    451: 	&&
                    452: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    453: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  454: 	foreach my $key (keys(%disk_env)) {
                    455: 	    if ($key=~/^$delthis/) { 
1.619     albertel  456:                 delete($env{$key});
1.783     albertel  457:                 delete($disk_env{$key});
1.473     matthew   458:             }
1.448     albertel  459: 	}
1.783     albertel  460: 	untie(%disk_env);
1.5       www       461:     }
                    462:     return 'ok';
1.369     albertel  463: }
                    464: 
1.790     albertel  465: sub get_env_multiple {
                    466:     my ($name) = @_;
                    467:     my @values;
                    468:     if (defined($env{$name})) {
                    469:         # exists is it an array
                    470:         if (ref($env{$name})) {
                    471:             @values=@{ $env{$name} };
                    472:         } else {
                    473:             $values[0]=$env{$name};
                    474:         }
                    475:     }
                    476:     return(@values);
                    477: }
                    478: 
1.369     albertel  479: # ------------------------------------------ Find out current server userload
                    480: # there is a copy in lond
                    481: sub userload {
                    482:     my $numusers=0;
                    483:     {
                    484: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    485: 	my $filename;
                    486: 	my $curtime=time;
                    487: 	while ($filename=readdir(LONIDS)) {
                    488: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  489: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  490: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  491: 	}
                    492: 	closedir(LONIDS);
                    493:     }
                    494:     my $userloadpercent=0;
                    495:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    496:     if ($maxuserload) {
1.371     albertel  497: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  498:     }
1.372     albertel  499:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  500:     return $userloadpercent;
1.283     www       501: }
                    502: 
                    503: # ------------------------------------------ Fight off request when overloaded
                    504: 
                    505: sub overloaderror {
                    506:     my ($r,$checkserver)=@_;
                    507:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    508:     my $loadavg;
                    509:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  510:        open(my $loadfile,'/proc/loadavg');
1.283     www       511:        $loadavg=<$loadfile>;
                    512:        $loadavg =~ s/\s.*//g;
1.285     matthew   513:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  514:        close($loadfile);
1.283     www       515:     } else {
                    516:        $loadavg=&reply('load',$checkserver);
                    517:     }
1.285     matthew   518:     my $overload=$loadavg-100;
1.283     www       519:     if ($overload>0) {
1.285     matthew   520: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       521:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       522:         return 413;
1.283     www       523:     }    
                    524:     return '';
1.5       www       525: }
1.1       albertel  526: 
                    527: # ------------------------------ Find server with least workload from spare.tab
1.11      www       528: 
1.1       albertel  529: sub spareserver {
1.670     albertel  530:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  531:     my $spare_server;
1.370     albertel  532:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  533:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    534:                                                      :  $userloadpercent;
                    535:     
                    536:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    537: 	($spare_server, $lowest_load) =
                    538: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    539:     }
                    540: 
                    541:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    542: 
                    543:     if (!$found_server) {
                    544: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    545: 	    ($spare_server, $lowest_load) =
                    546: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    547: 	}
                    548:     }
                    549: 
                    550:     if (!$want_server_name) {
1.838     albertel  551: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  552:     }
                    553:     return $spare_server;
                    554: }
                    555: 
                    556: sub compare_server_load {
                    557:     my ($try_server, $spare_server, $lowest_load) = @_;
                    558: 
                    559:     my $loadans     = &reply('load',    $try_server);
                    560:     my $userloadans = &reply('userload',$try_server);
                    561: 
                    562:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    563: 	next; #didn't get a number from the server
                    564:     }
                    565: 
                    566:     my $load;
                    567:     if ($loadans =~ /\d/) {
                    568: 	if ($userloadans =~ /\d/) {
                    569: 	    #both are numbers, pick the bigger one
                    570: 	    $load = ($loadans > $userloadans) ? $loadans 
                    571: 		                              : $userloadans;
1.411     albertel  572: 	} else {
1.784     albertel  573: 	    $load = $loadans;
1.411     albertel  574: 	}
1.784     albertel  575:     } else {
                    576: 	$load = $userloadans;
                    577:     }
                    578: 
                    579:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    580: 	$spare_server = $try_server;
                    581: 	$lowest_load  = $load;
1.370     albertel  582:     }
1.784     albertel  583:     return ($spare_server,$lowest_load);
1.202     matthew   584: }
                    585: # --------------------------------------------- Try to change a user's password
                    586: 
                    587: sub changepass {
1.799     raeburn   588:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   589:     $currentpass = &escape($currentpass);
                    590:     $newpass     = &escape($newpass);
1.799     raeburn   591:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   592: 		       $server);
                    593:     if (! $answer) {
                    594: 	&logthis("No reply on password change request to $server ".
                    595: 		 "by $uname in domain $udom.");
                    596:     } elsif ($answer =~ "^ok") {
                    597:         &logthis("$uname in $udom successfully changed their password ".
                    598: 		 "on $server.");
                    599:     } elsif ($answer =~ "^pwchange_failure") {
                    600: 	&logthis("$uname in $udom was unable to change their password ".
                    601: 		 "on $server.  The action was blocked by either lcpasswd ".
                    602: 		 "or pwchange");
                    603:     } elsif ($answer =~ "^non_authorized") {
                    604:         &logthis("$uname in $udom did not get their password correct when ".
                    605: 		 "attempting to change it on $server.");
                    606:     } elsif ($answer =~ "^auth_mode_error") {
                    607:         &logthis("$uname in $udom attempted to change their password despite ".
                    608: 		 "not being locally or internally authenticated on $server.");
                    609:     } elsif ($answer =~ "^unknown_user") {
                    610:         &logthis("$uname in $udom attempted to change their password ".
                    611: 		 "on $server but were unable to because $server is not ".
                    612: 		 "their home server.");
                    613:     } elsif ($answer =~ "^refused") {
                    614: 	&logthis("$server refused to change $uname in $udom password because ".
                    615: 		 "it was sent an unencrypted request to change the password.");
                    616:     }
                    617:     return $answer;
1.1       albertel  618: }
                    619: 
1.169     harris41  620: # ----------------------- Try to determine user's current authentication scheme
                    621: 
                    622: sub queryauthenticate {
                    623:     my ($uname,$udom)=@_;
1.456     albertel  624:     my $uhome=&homeserver($uname,$udom);
                    625:     if (!$uhome) {
                    626: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    627: 	return 'no_host';
                    628:     }
                    629:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    630:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    631: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  632:     }
1.456     albertel  633:     return $answer;
1.169     harris41  634: }
                    635: 
1.1       albertel  636: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       637: 
1.1       albertel  638: sub authenticate {
                    639:     my ($uname,$upass,$udom)=@_;
1.807     albertel  640:     $upass=&escape($upass);
                    641:     $uname= &LONCAPA::clean_username($uname);
1.836     www       642:     my $uhome=&homeserver($uname,$udom,1);
                    643:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    644: # Maybe the machine was offline and only re-appeared again recently?
                    645:         &reconlonc();
                    646: # One more
                    647: 	my $uhome=&homeserver($uname,$udom,1);
                    648: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    649: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    650: 	}
1.471     albertel  651: 	return 'no_host';
1.1       albertel  652:     }
1.471     albertel  653:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    654:     if ($answer eq 'authorized') {
                    655: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    656: 	return $uhome; 
                    657:     }
                    658:     if ($answer eq 'non_authorized') {
                    659: 	&logthis("User $uname at $udom rejected by $uhome");
                    660: 	return 'no_host'; 
1.9       www       661:     }
1.471     albertel  662:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  663:     return 'no_host';
                    664: }
                    665: 
                    666: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       667: 
1.599     albertel  668: my %homecache;
1.1       albertel  669: sub homeserver {
1.230     stredwic  670:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  671:     my $index="$uname:$udom";
1.426     albertel  672: 
1.599     albertel  673:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  674: 
                    675:     my %servers = &get_servers($udom,'library');
                    676:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  677:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  678: 		 exists($badServerCache{$tryserver}));
1.841     albertel  679: 
                    680: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    681: 	if ($answer eq 'found') {
                    682: 	    delete($badServerCache{$tryserver}); 
                    683: 	    return $homecache{$index}=$tryserver;
                    684: 	} elsif ($answer eq 'no_host') {
                    685: 	    $badServerCache{$tryserver}=1;
                    686: 	}
1.1       albertel  687:     }    
                    688:     return 'no_host';
1.70      www       689: }
                    690: 
                    691: # ------------------------------------- Find the usernames behind a list of IDs
                    692: 
                    693: sub idget {
                    694:     my ($udom,@ids)=@_;
                    695:     my %returnhash=();
                    696:     
1.841     albertel  697:     my %servers = &get_servers($udom,'library');
                    698:     foreach my $tryserver (keys(%servers)) {
                    699: 	my $idlist=join('&',@ids);
                    700: 	$idlist=~tr/A-Z/a-z/; 
                    701: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    702: 	my @answer=();
                    703: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    704: 	    @answer=split(/\&/,$reply);
                    705: 	}                    ;
                    706: 	my $i;
                    707: 	for ($i=0;$i<=$#ids;$i++) {
                    708: 	    if ($answer[$i]) {
                    709: 		$returnhash{$ids[$i]}=$answer[$i];
                    710: 	    } 
                    711: 	}
                    712:     } 
1.70      www       713:     return %returnhash;
                    714: }
                    715: 
                    716: # ------------------------------------- Find the IDs behind a list of usernames
                    717: 
                    718: sub idrget {
                    719:     my ($udom,@unames)=@_;
                    720:     my %returnhash=();
1.800     albertel  721:     foreach my $uname (@unames) {
                    722:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  723:     }
1.70      www       724:     return %returnhash;
                    725: }
                    726: 
                    727: # ------------------------------- Store away a list of names and associated IDs
                    728: 
                    729: sub idput {
                    730:     my ($udom,%ids)=@_;
                    731:     my %servers=();
1.800     albertel  732:     foreach my $uname (keys(%ids)) {
                    733: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    734:         my $uhom=&homeserver($uname,$udom);
1.70      www       735:         if ($uhom ne 'no_host') {
1.800     albertel  736:             my $id=&escape($ids{$uname});
1.70      www       737:             $id=~tr/A-Z/a-z/;
1.800     albertel  738:             my $esc_unam=&escape($uname);
1.70      www       739: 	    if ($servers{$uhom}) {
1.800     albertel  740: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       741:             } else {
1.800     albertel  742:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       743:             }
                    744:         }
1.191     harris41  745:     }
1.800     albertel  746:     foreach my $server (keys(%servers)) {
                    747:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  748:     }
1.344     www       749: }
                    750: 
1.806     raeburn   751: # ------------------------------------------- get items from domain db files   
                    752: 
                    753: sub get_dom {
1.860     raeburn   754:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   755:     my $items='';
                    756:     foreach my $item (@$storearr) {
                    757:         $items.=&escape($item).'&';
                    758:     }
                    759:     $items=~s/\&$//;
1.860     raeburn   760:     if (!$udom) {
                    761:         $udom=$env{'user.domain'};
                    762:         if (defined(&domain($udom,'primary'))) {
                    763:             $uhome=&domain($udom,'primary');
                    764:         } else {
1.874     albertel  765:             undef($uhome);
1.860     raeburn   766:         }
                    767:     } else {
                    768:         if (!$uhome) {
                    769:             if (defined(&domain($udom,'primary'))) {
                    770:                 $uhome=&domain($udom,'primary');
                    771:             }
                    772:         }
                    773:     }
                    774:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   775:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   776:         my %returnhash;
1.875     albertel  777:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   778:             return %returnhash;
                    779:         }
1.806     raeburn   780:         my @pairs=split(/\&/,$rep);
                    781:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    782:             return @pairs;
                    783:         }
                    784:         my $i=0;
                    785:         foreach my $item (@$storearr) {
                    786:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    787:             $i++;
                    788:         }
                    789:         return %returnhash;
                    790:     } else {
1.880     banghart  791:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   792:     }
                    793: }
                    794: 
                    795: # -------------------------------------------- put items in domain db files 
                    796: 
                    797: sub put_dom {
1.860     raeburn   798:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    799:     if (!$udom) {
                    800:         $udom=$env{'user.domain'};
                    801:         if (defined(&domain($udom,'primary'))) {
                    802:             $uhome=&domain($udom,'primary');
                    803:         } else {
1.874     albertel  804:             undef($uhome);
1.860     raeburn   805:         }
                    806:     } else {
                    807:         if (!$uhome) {
                    808:             if (defined(&domain($udom,'primary'))) {
                    809:                 $uhome=&domain($udom,'primary');
                    810:             }
                    811:         }
                    812:     } 
                    813:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   814:         my $items='';
                    815:         foreach my $item (keys(%$storehash)) {
                    816:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    817:         }
                    818:         $items=~s/\&$//;
                    819:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    820:     } else {
1.860     raeburn   821:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   822:     }
                    823: }
                    824: 
1.837     raeburn   825: sub retrieve_inst_usertypes {
                    826:     my ($udom) = @_;
                    827:     my (%returnhash,@order);
1.846     albertel  828:     if (defined(&domain($udom,'primary'))) {
                    829:         my $uhome=&domain($udom,'primary');
1.837     raeburn   830:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    831:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    832:         my @pairs=split(/\&/,$hashitems);
                    833:         foreach my $item (@pairs) {
                    834:             my ($key,$value)=split(/=/,$item,2);
                    835:             $key = &unescape($key);
                    836:             next if ($key =~ /^error: 2 /);
                    837:             $returnhash{$key}=&thaw_unescape($value);
                    838:         }
                    839:         my @esc_order = split(/\&/,$orderitems);
                    840:         foreach my $item (@esc_order) {
                    841:             push(@order,&unescape($item));
                    842:         }
                    843:     } else {
                    844:         &logthis("get_dom failed - no primary domain server for $udom");
                    845:     }
                    846:     return (\%returnhash,\@order);
                    847: }
                    848: 
1.868     raeburn   849: sub is_domainimage {
                    850:     my ($url) = @_;
                    851:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    852:         if (&domain($1) ne '') {
                    853:             return '1';
                    854:         }
                    855:     }
                    856:     return;
                    857: }
                    858: 
1.344     www       859: # --------------------------------------------------- Assign a key to a student
                    860: 
                    861: sub assign_access_key {
1.364     www       862: #
                    863: # a valid key looks like uname:udom#comments
                    864: # comments are being appended
                    865: #
1.498     www       866:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    867:     $kdom=
1.620     albertel  868:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       869:     $knum=
1.620     albertel  870:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       871:     $cdom=
1.620     albertel  872:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       873:     $cnum=
1.620     albertel  874:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    875:     $udom=$env{'user.name'} unless (defined($udom));
                    876:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       877:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       878:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  879:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       880:                                                   # assigned to this person
                    881:                                                   # - this should not happen,
1.345     www       882:                                                   # unless something went wrong
                    883:                                                   # the first time around
                    884: # ready to assign
1.364     www       885:         $logentry=$1.'; '.$logentry;
1.496     www       886:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       887:                                                  $kdom,$knum) eq 'ok') {
1.345     www       888: # key now belongs to user
1.346     www       889: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       890:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    891:                 &appenv('environment.'.$envkey => $ckey);
                    892:                 return 'ok';
                    893:             } else {
                    894:                 return 
                    895:   'error: Count not permanently assign key, will need to be re-entered later.';
                    896: 	    }
                    897:         } else {
                    898:             return 'error: Could not assign key, try again later.';
                    899:         }
1.364     www       900:     } elsif (!$existing{$ckey}) {
1.345     www       901: # the key does not exist
                    902: 	return 'error: The key does not exist';
                    903:     } else {
                    904: # the key is somebody else's
                    905: 	return 'error: The key is already in use';
                    906:     }
1.344     www       907: }
                    908: 
1.364     www       909: # ------------------------------------------ put an additional comment on a key
                    910: 
                    911: sub comment_access_key {
                    912: #
                    913: # a valid key looks like uname:udom#comments
                    914: # comments are being appended
                    915: #
                    916:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    917:     $cdom=
1.620     albertel  918:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       919:     $cnum=
1.620     albertel  920:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       921:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    922:     if ($existing{$ckey}) {
                    923:         $existing{$ckey}.='; '.$logentry;
                    924: # ready to assign
1.367     www       925:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       926:                                                  $cdom,$cnum) eq 'ok') {
                    927: 	    return 'ok';
                    928:         } else {
                    929: 	    return 'error: Count not store comment.';
                    930:         }
                    931:     } else {
                    932: # the key does not exist
                    933: 	return 'error: The key does not exist';
                    934:     }
                    935: }
                    936: 
1.344     www       937: # ------------------------------------------------------ Generate a set of keys
                    938: 
                    939: sub generate_access_keys {
1.364     www       940:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       941:     $cdom=
1.620     albertel  942:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       943:     $cnum=
1.620     albertel  944:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       945:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       946:     unless (($cdom) && ($cnum)) { return 0; }
                    947:     if ($number>10000) { return 0; }
                    948:     sleep(2); # make sure don't get same seed twice
                    949:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    950:     my $total=0;
                    951:     for (my $i=1;$i<=$number;$i++) {
                    952:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    953:                   sprintf("%lx",int(100000*rand)).'-'.
                    954:                   sprintf("%lx",int(100000*rand));
                    955:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    956:        $newkey=~s/0/h/g; # and also 0 and O
                    957:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    958:        if ($existing{$newkey}) {
                    959:            $i--;
                    960:        } else {
1.364     www       961: 	  if (&put('accesskeys',
                    962:               { $newkey => '# generated '.localtime().
1.620     albertel  963:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       964:                            '; '.$logentry },
                    965: 		   $cdom,$cnum) eq 'ok') {
1.344     www       966:               $total++;
                    967: 	  }
                    968:        }
                    969:     }
1.620     albertel  970:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       971:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    972:     return $total;
                    973: }
                    974: 
                    975: # ------------------------------------------------------- Validate an accesskey
                    976: 
                    977: sub validate_access_key {
                    978:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    979:     $cdom=
1.620     albertel  980:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       981:     $cnum=
1.620     albertel  982:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    983:     $udom=$env{'user.domain'} unless (defined($udom));
                    984:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       985:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  986:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       987: }
                    988: 
                    989: # ------------------------------------- Find the section of student in a course
1.652     albertel  990: sub devalidate_getsection_cache {
                    991:     my ($udom,$unam,$courseid)=@_;
                    992:     my $hashid="$udom:$unam:$courseid";
                    993:     &devalidate_cache_new('getsection',$hashid);
                    994: }
1.298     matthew   995: 
1.815     albertel  996: sub courseid_to_courseurl {
                    997:     my ($courseid) = @_;
                    998:     #already url style courseid
                    999:     return $courseid if ($courseid =~ m{^/});
                   1000: 
                   1001:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1002: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1003: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1004: 	return "/$cdom/$cnum";
                   1005:     }
                   1006: 
                   1007:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1008:     if (exists($courseinfo{'num'})) {
                   1009: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1010:     }
                   1011: 
                   1012:     return undef;
                   1013: }
                   1014: 
1.298     matthew  1015: sub getsection {
                   1016:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1017:     my $cachetime=1800;
1.551     albertel 1018: 
                   1019:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1020:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1021:     if (defined($cached)) { return $result; }
                   1022: 
1.298     matthew  1023:     my %Pending; 
                   1024:     my %Expired;
                   1025:     #
                   1026:     # Each role can either have not started yet (pending), be active, 
                   1027:     #    or have expired.
                   1028:     #
                   1029:     # If there is an active role, we are done.
                   1030:     #
                   1031:     # If there is more than one role which has not started yet, 
                   1032:     #     choose the one which will start sooner
                   1033:     # If there is one role which has not started yet, return it.
                   1034:     #
                   1035:     # If there is more than one expired role, choose the one which ended last.
                   1036:     # If there is a role which has expired, return it.
                   1037:     #
1.815     albertel 1038:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1039:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1040:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1041:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1042:         my $section=$1;
                   1043:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1044:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1045:         my $now=time;
1.548     albertel 1046:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1047:             $Expired{$end}=$section;
                   1048:             next;
                   1049:         }
1.548     albertel 1050:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1051:             $Pending{$start}=$section;
                   1052:             next;
                   1053:         }
1.599     albertel 1054:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1055:     }
                   1056:     #
                   1057:     # Presumedly there will be few matching roles from the above
                   1058:     # loop and the sorting time will be negligible.
                   1059:     if (scalar(keys(%Pending))) {
                   1060:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1061:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1062:     } 
                   1063:     if (scalar(keys(%Expired))) {
                   1064:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1065:         my $time = pop(@sorted);
1.599     albertel 1066:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1067:     }
1.599     albertel 1068:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1069: }
1.70      www      1070: 
1.599     albertel 1071: sub save_cache {
                   1072:     &purge_remembered();
1.722     albertel 1073:     #&Apache::loncommon::validate_page();
1.620     albertel 1074:     undef(%env);
1.780     albertel 1075:     undef($env_loaded);
1.599     albertel 1076: }
1.452     albertel 1077: 
1.599     albertel 1078: my $to_remember=-1;
                   1079: my %remembered;
                   1080: my %accessed;
                   1081: my $kicks=0;
                   1082: my $hits=0;
1.849     albertel 1083: sub make_key {
                   1084:     my ($name,$id) = @_;
1.872     albertel 1085:     if (length($id) > 65 
                   1086: 	&& length(&escape($id)) > 200) {
                   1087: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1088:     }
1.849     albertel 1089:     return &escape($name.':'.$id);
                   1090: }
                   1091: 
1.599     albertel 1092: sub devalidate_cache_new {
                   1093:     my ($name,$id,$debug) = @_;
                   1094:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1095:     $id=&make_key($name,$id);
1.599     albertel 1096:     $memcache->delete($id);
                   1097:     delete($remembered{$id});
                   1098:     delete($accessed{$id});
                   1099: }
                   1100: 
                   1101: sub is_cached_new {
                   1102:     my ($name,$id,$debug) = @_;
1.849     albertel 1103:     $id=&make_key($name,$id);
1.599     albertel 1104:     if (exists($remembered{$id})) {
                   1105: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1106: 	$accessed{$id}=[&gettimeofday()];
                   1107: 	$hits++;
                   1108: 	return ($remembered{$id},1);
                   1109:     }
                   1110:     my $value = $memcache->get($id);
                   1111:     if (!(defined($value))) {
                   1112: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1113: 	return (undef,undef);
1.416     albertel 1114:     }
1.599     albertel 1115:     if ($value eq '__undef__') {
                   1116: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1117: 	$value=undef;
                   1118:     }
                   1119:     &make_room($id,$value,$debug);
                   1120:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1121:     return ($value,1);
                   1122: }
                   1123: 
                   1124: sub do_cache_new {
                   1125:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1126:     $id=&make_key($name,$id);
1.599     albertel 1127:     my $setvalue=$value;
                   1128:     if (!defined($setvalue)) {
                   1129: 	$setvalue='__undef__';
                   1130:     }
1.623     albertel 1131:     if (!defined($time) ) {
                   1132: 	$time=600;
                   1133:     }
1.599     albertel 1134:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.872     albertel 1135:     if (!($memcache->set($id,$setvalue,$time))) {
                   1136: 	&logthis("caching of id -> $id  failed");
                   1137:     }
1.600     albertel 1138:     # need to make a copy of $value
                   1139:     #&make_room($id,$value,$debug);
1.599     albertel 1140:     return $value;
                   1141: }
                   1142: 
                   1143: sub make_room {
                   1144:     my ($id,$value,$debug)=@_;
                   1145:     $remembered{$id}=$value;
                   1146:     if ($to_remember<0) { return; }
                   1147:     $accessed{$id}=[&gettimeofday()];
                   1148:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1149:     my $to_kick;
                   1150:     my $max_time=0;
                   1151:     foreach my $other (keys(%accessed)) {
                   1152: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1153: 	    $to_kick=$other;
                   1154: 	    $max_time=&tv_interval($accessed{$other});
                   1155: 	}
                   1156:     }
                   1157:     delete($remembered{$to_kick});
                   1158:     delete($accessed{$to_kick});
                   1159:     $kicks++;
                   1160:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1161:     return;
                   1162: }
                   1163: 
1.599     albertel 1164: sub purge_remembered {
1.604     albertel 1165:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1166:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1167:     undef(%remembered);
                   1168:     undef(%accessed);
1.428     albertel 1169: }
1.70      www      1170: # ------------------------------------- Read an entry from a user's environment
                   1171: 
                   1172: sub userenvironment {
                   1173:     my ($udom,$unam,@what)=@_;
                   1174:     my %returnhash=();
                   1175:     my @answer=split(/\&/,
                   1176:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1177:                       &homeserver($unam,$udom)));
                   1178:     my $i;
                   1179:     for ($i=0;$i<=$#what;$i++) {
                   1180: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1181:     }
                   1182:     return %returnhash;
1.1       albertel 1183: }
                   1184: 
1.617     albertel 1185: # ---------------------------------------------------------- Get a studentphoto
                   1186: sub studentphoto {
                   1187:     my ($udom,$unam,$ext) = @_;
                   1188:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1189:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1190:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1191:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1192:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1193:             } else {
                   1194:                 my ($result,$perm_reqd)=
1.707     albertel 1195: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1196:                 if ($result eq 'ok') {
                   1197:                     if (!($perm_reqd eq 'yes')) {
                   1198:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1199:                     }
                   1200:                 }
                   1201:             }
                   1202:         }
                   1203:     } else {
                   1204:         my ($result,$perm_reqd) = 
1.707     albertel 1205: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1206:         if ($result eq 'ok') {
                   1207:             if (!($perm_reqd eq 'yes')) {
                   1208:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1209:             }
                   1210:         }
                   1211:     }
                   1212:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1213: }
                   1214: 
                   1215: sub retrievestudentphoto {
                   1216:     my ($udom,$unam,$ext,$type) = @_;
                   1217:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1218:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1219:     if ($ret eq 'ok') {
                   1220:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1221:         if ($type eq 'thumbnail') {
                   1222:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1223:         }
                   1224:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1225:         return $tokenurl;
                   1226:     } else {
                   1227:         if ($type eq 'thumbnail') {
                   1228:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1229:         } else { 
                   1230:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1231:         }
1.617     albertel 1232:     }
                   1233: }
                   1234: 
1.263     www      1235: # -------------------------------------------------------------------- New chat
                   1236: 
                   1237: sub chatsend {
1.724     raeburn  1238:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1239:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1240:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1241:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1242:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1243: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1244: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1245: }
                   1246: 
                   1247: # ------------------------------------------ Find current version of a resource
                   1248: 
                   1249: sub getversion {
                   1250:     my $fname=&clutter(shift);
                   1251:     unless ($fname=~/^\/res\//) { return -1; }
                   1252:     return &currentversion(&filelocation('',$fname));
                   1253: }
                   1254: 
                   1255: sub currentversion {
                   1256:     my $fname=shift;
1.599     albertel 1257:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1258:     if (defined($cached)) { return $result; }
1.292     www      1259:     my $author=$fname;
                   1260:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1261:     my ($udom,$uname)=split(/\//,$author);
                   1262:     my $home=homeserver($uname,$udom);
                   1263:     if ($home eq 'no_host') { 
                   1264:         return -1; 
                   1265:     }
                   1266:     my $answer=reply("currentversion:$fname",$home);
                   1267:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1268: 	return -1;
                   1269:     }
1.599     albertel 1270:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1271: }
                   1272: 
1.1       albertel 1273: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1274: 
1.1       albertel 1275: sub subscribe {
                   1276:     my $fname=shift;
1.761     raeburn  1277:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1278:     $fname=~s/[\n\r]//g;
1.1       albertel 1279:     my $author=$fname;
                   1280:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1281:     my ($udom,$uname)=split(/\//,$author);
                   1282:     my $home=homeserver($uname,$udom);
1.335     albertel 1283:     if ($home eq 'no_host') {
                   1284:         return 'not_found';
1.1       albertel 1285:     }
                   1286:     my $answer=reply("sub:$fname",$home);
1.64      www      1287:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1288: 	$answer.=' by '.$home;
                   1289:     }
1.1       albertel 1290:     return $answer;
                   1291: }
                   1292:     
1.8       www      1293: # -------------------------------------------------------------- Replicate file
                   1294: 
                   1295: sub repcopy {
                   1296:     my $filename=shift;
1.23      www      1297:     $filename=~s/\/+/\//g;
1.607     raeburn  1298:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1299:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1300:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1301: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1302: 	return &repcopy_userfile($filename);
                   1303:     }
1.532     albertel 1304:     $filename=~s/[\n\r]//g;
1.8       www      1305:     my $transname="$filename.in.transfer";
1.828     www      1306: # FIXME: this should flock
1.607     raeburn  1307:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1308:     my $remoteurl=subscribe($filename);
1.64      www      1309:     if ($remoteurl =~ /^con_lost by/) {
                   1310: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1311:            return 'unavailable';
1.8       www      1312:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1313: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1314: 	   return 'not_found';
1.64      www      1315:     } elsif ($remoteurl =~ /^rejected by/) {
                   1316: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1317:            return 'forbidden';
1.20      www      1318:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1319:            return 'ok';
1.8       www      1320:     } else {
1.290     www      1321:         my $author=$filename;
                   1322:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1323:         my ($udom,$uname)=split(/\//,$author);
                   1324:         my $home=homeserver($uname,$udom);
                   1325:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1326:            my @parts=split(/\//,$filename);
                   1327:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1328:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1329:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1330: 	       return 'bad_request';
1.8       www      1331:            }
                   1332:            my $count;
                   1333:            for ($count=5;$count<$#parts;$count++) {
                   1334:                $path.="/$parts[$count]";
                   1335:                if ((-e $path)!=1) {
                   1336: 		   mkdir($path,0777);
                   1337:                }
                   1338:            }
                   1339:            my $ua=new LWP::UserAgent;
                   1340:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1341:            my $response=$ua->request($request,$transname);
                   1342:            if ($response->is_error()) {
                   1343: 	       unlink($transname);
                   1344:                my $message=$response->status_line;
1.672     albertel 1345:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1346:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1347:                return 'unavailable';
1.8       www      1348:            } else {
1.16      www      1349: 	       if ($remoteurl!~/\.meta$/) {
                   1350:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1351:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1352:                   if ($mresponse->is_error()) {
                   1353: 		      unlink($filename.'.meta');
                   1354:                       &logthis(
1.672     albertel 1355:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1356:                   }
                   1357: 	       }
1.8       www      1358:                rename($transname,$filename);
1.607     raeburn  1359:                return 'ok';
1.8       www      1360:            }
1.290     www      1361:        }
1.8       www      1362:     }
1.330     www      1363: }
                   1364: 
                   1365: # ------------------------------------------------ Get server side include body
                   1366: sub ssi_body {
1.381     albertel 1367:     my ($filelink,%form)=@_;
1.606     matthew  1368:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1369:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1370:     }
1.330     www      1371:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1372:                                      &ssi($filelink,%form));
1.778     albertel 1373:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1374:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1375:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1376:     return $output;
1.8       www      1377: }
                   1378: 
1.15      www      1379: # --------------------------------------------------------- Server Side Include
                   1380: 
1.782     albertel 1381: sub absolute_url {
                   1382:     my ($host_name) = @_;
                   1383:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1384:     if ($host_name eq '') {
                   1385: 	$host_name = $ENV{'SERVER_NAME'};
                   1386:     }
                   1387:     return $protocol.$host_name;
                   1388: }
                   1389: 
1.15      www      1390: sub ssi {
                   1391: 
1.23      www      1392:     my ($fn,%form)=@_;
1.15      www      1393: 
                   1394:     my $ua=new LWP::UserAgent;
1.23      www      1395:     
                   1396:     my $request;
1.711     albertel 1397: 
                   1398:     $form{'no_update_last_known'}=1;
                   1399: 
1.23      www      1400:     if (%form) {
1.782     albertel 1401:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1402:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1403:     } else {
1.782     albertel 1404:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1405:     }
                   1406: 
1.15      www      1407:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1408:     my $response=$ua->request($request);
                   1409: 
1.324     www      1410:     return $response->content;
                   1411: }
                   1412: 
                   1413: sub externalssi {
                   1414:     my ($url)=@_;
                   1415:     my $ua=new LWP::UserAgent;
                   1416:     my $request=new HTTP::Request('GET',$url);
                   1417:     my $response=$ua->request($request);
1.15      www      1418:     return $response->content;
                   1419: }
1.254     www      1420: 
1.492     albertel 1421: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1422: 
                   1423: sub allowuploaded {
                   1424:     my ($srcurl,$url)=@_;
                   1425:     $url=&clutter(&declutter($url));
                   1426:     my $dir=$url;
                   1427:     $dir=~s/\/[^\/]+$//;
                   1428:     my %httpref=();
                   1429:     my $httpurl=&hreflocation('',$url);
                   1430:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1431:     &Apache::lonnet::appenv(%httpref);
1.254     www      1432: }
1.477     raeburn  1433: 
1.478     albertel 1434: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1435: # input: action, courseID, current domain, intended
1.637     raeburn  1436: #        path to file, source of file, instruction to parse file for objects,
                   1437: #        ref to hash for embedded objects,
                   1438: #        ref to hash for codebase of java objects.
                   1439: #
1.485     raeburn  1440: # output: url to file (if action was uploaddoc), 
                   1441: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1442: #
1.478     albertel 1443: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1444: # course.
1.477     raeburn  1445: #
1.478     albertel 1446: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1447: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1448: #          course's home server.
1.477     raeburn  1449: #
1.478     albertel 1450: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1451: #          be copied from $source (current location) to 
                   1452: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1453: #         and will then be copied to
                   1454: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1455: #         course's home server.
1.485     raeburn  1456: #
1.481     raeburn  1457: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1458: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1459: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1460: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1461: #         in course's home server.
1.637     raeburn  1462: #
1.477     raeburn  1463: 
                   1464: sub process_coursefile {
1.638     albertel 1465:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1466:     my $fetchresult;
1.638     albertel 1467:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1468:     if ($action eq 'propagate') {
1.638     albertel 1469:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1470: 			     $home);
1.481     raeburn  1471:     } else {
1.477     raeburn  1472:         my $fpath = '';
                   1473:         my $fname = $file;
1.478     albertel 1474:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1475:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1476:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1477:         if ($action eq 'copy') {
                   1478:             if ($source eq '') {
                   1479:                 $fetchresult = 'no source file';
                   1480:                 return $fetchresult;
                   1481:             } else {
                   1482:                 my $destination = $filepath.'/'.$fname;
                   1483:                 rename($source,$destination);
                   1484:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1485:                                  $home);
1.481     raeburn  1486:             }
                   1487:         } elsif ($action eq 'uploaddoc') {
                   1488:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1489:             print $fh $env{'form.'.$source};
1.481     raeburn  1490:             close($fh);
1.637     raeburn  1491:             if ($parser eq 'parse') {
                   1492:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1493:                 unless ($parse_result eq 'ok') {
                   1494:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1495:                 }
                   1496:             }
1.477     raeburn  1497:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1498:                                  $home);
1.481     raeburn  1499:             if ($fetchresult eq 'ok') {
                   1500:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1501:             } else {
                   1502:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1503:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1504:                 return '/adm/notfound.html';
                   1505:             }
1.477     raeburn  1506:         }
                   1507:     }
1.485     raeburn  1508:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1509:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1510:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1511:     }
                   1512:     return $fetchresult;
                   1513: }
                   1514: 
1.637     raeburn  1515: sub build_filepath {
                   1516:     my ($fpath) = @_;
                   1517:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1518:     unless ($fpath eq '') {
                   1519:         my @parts=split('/',$fpath);
                   1520:         foreach my $part (@parts) {
                   1521:             $filepath.= '/'.$part;
                   1522:             if ((-e $filepath)!=1) {
                   1523:                 mkdir($filepath,0777);
                   1524:             }
                   1525:         }
                   1526:     }
                   1527:     return $filepath;
                   1528: }
                   1529: 
                   1530: sub store_edited_file {
1.638     albertel 1531:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1532:     my $file = $primary_url;
                   1533:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1534:     my $fpath = '';
                   1535:     my $fname = $file;
                   1536:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1537:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1538:     my $filepath = &build_filepath($fpath);
                   1539:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1540:     print $fh $content;
                   1541:     close($fh);
1.638     albertel 1542:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1543:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1544: 			  $home);
1.637     raeburn  1545:     if ($$fetchresult eq 'ok') {
                   1546:         return '/uploaded/'.$fpath.'/'.$fname;
                   1547:     } else {
1.638     albertel 1548:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1549: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1550:         return '/adm/notfound.html';
                   1551:     }
                   1552: }
                   1553: 
1.531     albertel 1554: sub clean_filename {
1.831     albertel 1555:     my ($fname,$args)=@_;
1.315     www      1556: # Replace Windows backslashes by forward slashes
1.257     www      1557:     $fname=~s/\\/\//g;
1.831     albertel 1558:     if (!$args->{'keep_path'}) {
                   1559:         # Get rid of everything but the actual filename
                   1560: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1561:     }
1.315     www      1562: # Replace spaces by underscores
                   1563:     $fname=~s/\s+/\_/g;
                   1564: # Replace all other weird characters by nothing
1.831     albertel 1565:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1566: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1567: # numbers
                   1568:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1569:     return $fname;
                   1570: }
                   1571: 
1.608     albertel 1572: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1573: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1574: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1575: #        $coursedoc - if true up to the current course
                   1576: #                     if false
                   1577: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1578: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1579: #        $allfiles - reference to hash for embedded objects
                   1580: #        $codebase - reference to hash for codebase of java objects
                   1581: #        $desuname - username for permanent storage of uploaded file
                   1582: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1583: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1584: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1585: # 
1.686     albertel 1586: # output: url of file in userspace, or error: <message> 
                   1587: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1588: 
                   1589: 
1.531     albertel 1590: sub userfileupload {
1.860     raeburn  1591:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1592:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1593:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1594:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1595:     $fname=&clean_filename($fname);
1.315     www      1596: # See if there is anything left
1.257     www      1597:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1598:     chop($env{'form.'.$formname});
1.523     raeburn  1599:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1600:         my $now = time;
                   1601:         my $filepath = 'tmp/helprequests/'.$now;
                   1602:         my @parts=split(/\//,$filepath);
                   1603:         my $fullpath = $perlvar{'lonDaemons'};
                   1604:         for (my $i=0;$i<@parts;$i++) {
                   1605:             $fullpath .= '/'.$parts[$i];
                   1606:             if ((-e $fullpath)!=1) {
                   1607:                 mkdir($fullpath,0777);
                   1608:             }
                   1609:         }
                   1610:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1611:         print $fh $env{'form.'.$formname};
1.523     raeburn  1612:         close($fh);
1.741     raeburn  1613:         return $fullpath.'/'.$fname;
                   1614:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1615:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1616:                        '_'.$env{'user.domain'}.'/pending';
                   1617:         my @parts=split(/\//,$filepath);
                   1618:         my $fullpath = $perlvar{'lonDaemons'};
                   1619:         for (my $i=0;$i<@parts;$i++) {
                   1620:             $fullpath .= '/'.$parts[$i];
                   1621:             if ((-e $fullpath)!=1) {
                   1622:                 mkdir($fullpath,0777);
                   1623:             }
                   1624:         }
                   1625:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1626:         print $fh $env{'form.'.$formname};
                   1627:         close($fh);
                   1628:         return $fullpath.'/'.$fname;
1.523     raeburn  1629:     }
1.719     banghart 1630:     
1.258     www      1631: # Create the directory if not present
1.493     albertel 1632:     $fname="$subdir/$fname";
1.259     www      1633:     if ($coursedoc) {
1.638     albertel 1634: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1635: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1636:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1637:             return &finishuserfileupload($docuname,$docudom,
                   1638: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1639: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1640:         } else {
1.620     albertel 1641:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1642:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1643: 				       $fname,$formname,$parser,
                   1644: 				       $allfiles,$codebase);
1.481     raeburn  1645:         }
1.719     banghart 1646:     } elsif (defined($destuname)) {
                   1647:         my $docuname=$destuname;
                   1648:         my $docudom=$destudom;
1.860     raeburn  1649: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1650: 				     $parser,$allfiles,$codebase,
                   1651:                                      $thumbwidth,$thumbheight);
1.719     banghart 1652:         
1.259     www      1653:     } else {
1.638     albertel 1654:         my $docuname=$env{'user.name'};
                   1655:         my $docudom=$env{'user.domain'};
1.714     raeburn  1656:         if (exists($env{'form.group'})) {
                   1657:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1658:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1659:         }
1.860     raeburn  1660: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1661: 				     $parser,$allfiles,$codebase,
                   1662:                                      $thumbwidth,$thumbheight);
1.259     www      1663:     }
1.271     www      1664: }
                   1665: 
                   1666: sub finishuserfileupload {
1.860     raeburn  1667:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1668:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1669:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1670:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1671:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1672:     $file=$fname;
                   1673:     if ($fname=~m|/|) {
                   1674:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1675: 	$path.=$fnamepath.'/';
                   1676:     }
1.259     www      1677:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1678:     my $count;
                   1679:     for ($count=4;$count<=$#parts;$count++) {
                   1680:         $filepath.="/$parts[$count]";
                   1681:         if ((-e $filepath)!=1) {
                   1682: 	    mkdir($filepath,0777);
                   1683:         }
                   1684:     }
                   1685: # Save the file
                   1686:     {
1.701     albertel 1687: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1688: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1689: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1690: 	    return '/adm/notfound.html';
                   1691: 	}
                   1692: 	if (!print FH ($env{'form.'.$formname})) {
                   1693: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1694: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1695: 	    return '/adm/notfound.html';
                   1696: 	}
1.570     albertel 1697: 	close(FH);
1.258     www      1698:     }
1.637     raeburn  1699:     if ($parser eq 'parse') {
1.638     albertel 1700:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1701: 						   $codebase);
1.637     raeburn  1702:         unless ($parse_result eq 'ok') {
1.638     albertel 1703:             &logthis('Failed to parse '.$filepath.$file.
                   1704: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1705:         }
                   1706:     }
1.860     raeburn  1707:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1708:         my $input = $filepath.'/'.$file;
                   1709:         my $output = $filepath.'/'.'tn-'.$file;
                   1710:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1711:         system("convert -sample $thumbsize $input $output");
                   1712:         if (-e $filepath.'/'.'tn-'.$file) {
                   1713:             $fetchthumb  = 1; 
                   1714:         }
                   1715:     }
1.858     raeburn  1716:  
1.259     www      1717: # Notify homeserver to grep it
                   1718: #
1.638     albertel 1719:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1720:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1721:     if ($fetchresult eq 'ok') {
1.860     raeburn  1722:         if ($fetchthumb) {
                   1723:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1724:             if ($thumbresult ne 'ok') {
                   1725:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1726:                          $docuhome.': '.$thumbresult);
                   1727:             }
                   1728:         }
1.259     www      1729: #
1.258     www      1730: # Return the URL to it
1.494     albertel 1731:         return '/uploaded/'.$path.$file;
1.263     www      1732:     } else {
1.494     albertel 1733:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1734: 		 ': '.$fetchresult);
1.263     www      1735:         return '/adm/notfound.html';
1.858     raeburn  1736:     }
1.493     albertel 1737: }
                   1738: 
1.637     raeburn  1739: sub extract_embedded_items {
1.648     raeburn  1740:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1741:     my @state = ();
                   1742:     my %javafiles = (
                   1743:                       codebase => '',
                   1744:                       code => '',
                   1745:                       archive => ''
                   1746:                     );
                   1747:     my %mediafiles = (
                   1748:                       src => '',
                   1749:                       movie => '',
                   1750:                      );
1.648     raeburn  1751:     my $p;
                   1752:     if ($content) {
                   1753:         $p = HTML::LCParser->new($content);
                   1754:     } else {
                   1755:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1756:     }
1.641     albertel 1757:     while (my $t=$p->get_token()) {
1.640     albertel 1758: 	if ($t->[0] eq 'S') {
                   1759: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1760: 	    push(@state, $tagname);
1.648     raeburn  1761:             if (lc($tagname) eq 'allow') {
                   1762:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1763:             }
1.640     albertel 1764: 	    if (lc($tagname) eq 'img') {
                   1765: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1766: 	    }
1.886     albertel 1767: 	    if (lc($tagname) eq 'a') {
                   1768: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1769: 	    }
1.645     raeburn  1770:             if (lc($tagname) eq 'script') {
                   1771:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1772:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1773:                 } else {
                   1774:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1775:                 }
                   1776:             }
                   1777:             if (lc($tagname) eq 'link') {
                   1778:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1779:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1780:                 }
                   1781:             }
1.640     albertel 1782: 	    if (lc($tagname) eq 'object' ||
                   1783: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1784: 		foreach my $item (keys(%javafiles)) {
                   1785: 		    $javafiles{$item} = '';
                   1786: 		}
                   1787: 	    }
                   1788: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1789: 		my $name = lc($attr->{'name'});
                   1790: 		foreach my $item (keys(%javafiles)) {
                   1791: 		    if ($name eq $item) {
                   1792: 			$javafiles{$item} = $attr->{'value'};
                   1793: 			last;
                   1794: 		    }
                   1795: 		}
                   1796: 		foreach my $item (keys(%mediafiles)) {
                   1797: 		    if ($name eq $item) {
                   1798: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1799: 			last;
                   1800: 		    }
                   1801: 		}
                   1802: 	    }
                   1803: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1804: 		foreach my $item (keys(%javafiles)) {
                   1805: 		    if ($attr->{$item}) {
                   1806: 			$javafiles{$item} = $attr->{$item};
                   1807: 			last;
                   1808: 		    }
                   1809: 		}
                   1810: 		foreach my $item (keys(%mediafiles)) {
                   1811: 		    if ($attr->{$item}) {
                   1812: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1813: 			last;
                   1814: 		    }
                   1815: 		}
                   1816: 	    }
                   1817: 	} elsif ($t->[0] eq 'E') {
                   1818: 	    my ($tagname) = ($t->[1]);
                   1819: 	    if ($javafiles{'codebase'} ne '') {
                   1820: 		$javafiles{'codebase'} .= '/';
                   1821: 	    }  
                   1822: 	    if (lc($tagname) eq 'applet' ||
                   1823: 		lc($tagname) eq 'object' ||
                   1824: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1825: 		) {
                   1826: 		foreach my $item (keys(%javafiles)) {
                   1827: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1828: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1829: 			&add_filetype($allfiles,$file,$item);
                   1830: 		    }
                   1831: 		}
                   1832: 	    } 
                   1833: 	    pop @state;
                   1834: 	}
                   1835:     }
1.637     raeburn  1836:     return 'ok';
                   1837: }
                   1838: 
1.639     albertel 1839: sub add_filetype {
                   1840:     my ($allfiles,$file,$type)=@_;
                   1841:     if (exists($allfiles->{$file})) {
                   1842: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1843: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1844: 	}
                   1845:     } else {
                   1846: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1847:     }
                   1848: }
                   1849: 
1.493     albertel 1850: sub removeuploadedurl {
                   1851:     my ($url)=@_;
                   1852:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1853:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1854: }
                   1855: 
                   1856: sub removeuserfile {
                   1857:     my ($docuname,$docudom,$fname)=@_;
                   1858:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1859:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1860:     if ($result eq 'ok') {
                   1861:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1862:             my $metafile = $fname.'.meta';
                   1863:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1864: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1865:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1866:             my $sqlresult = 
1.823     albertel 1867:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1868:                                         'portfolio_metadata',$group,
                   1869:                                         'delete');
1.798     raeburn  1870:         }
                   1871:     }
                   1872:     return $result;
1.257     www      1873: }
1.15      www      1874: 
1.530     albertel 1875: sub mkdiruserfile {
                   1876:     my ($docuname,$docudom,$dir)=@_;
                   1877:     my $home=&homeserver($docuname,$docudom);
                   1878:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1879: }
                   1880: 
1.531     albertel 1881: sub renameuserfile {
                   1882:     my ($docuname,$docudom,$old,$new)=@_;
                   1883:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1884:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1885:                         &escape("$old").':'.&escape("$new"),$home);
                   1886:     if ($result eq 'ok') {
                   1887:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1888:             my $oldmeta = $old.'.meta';
                   1889:             my $newmeta = $new.'.meta';
                   1890:             my $metaresult = 
                   1891:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1892: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1893:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1894:             my $sqlresult = 
1.823     albertel 1895:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1896:                                         'portfolio_metadata',$group,
                   1897:                                         'delete');
1.798     raeburn  1898:         }
                   1899:     }
                   1900:     return $result;
1.531     albertel 1901: }
                   1902: 
1.14      www      1903: # ------------------------------------------------------------------------- Log
                   1904: 
                   1905: sub log {
                   1906:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1907:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1908: }
                   1909: 
                   1910: # ------------------------------------------------------------------ Course Log
1.352     www      1911: #
                   1912: # This routine flushes several buffers of non-mission-critical nature
                   1913: #
1.157     www      1914: 
                   1915: sub flushcourselogs {
1.352     www      1916:     &logthis('Flushing log buffers');
                   1917: #
                   1918: # course logs
                   1919: # This is a log of all transactions in a course, which can be used
                   1920: # for data mining purposes
                   1921: #
                   1922: # It also collects the courseid database, which lists last transaction
                   1923: # times and course titles for all courseids
                   1924: #
                   1925:     my %courseidbuffer=();
1.800     albertel 1926:     foreach my $crsid (keys %courselogs) {
1.352     www      1927:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1928: 		          &escape($courselogs{$crsid}),
                   1929: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1930: 	    delete $courselogs{$crsid};
                   1931:         } else {
                   1932:             &logthis('Failed to flush log buffer for '.$crsid);
                   1933:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1934:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1935:                         " exceeded maximum size, deleting.</font>");
                   1936:                delete $courselogs{$crsid};
                   1937:             }
1.352     www      1938:         }
                   1939:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1940:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1941: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1942:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1943:         } else {
                   1944:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1945: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1946:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1947:         }
1.191     harris41 1948:     }
1.352     www      1949: #
                   1950: # Write course id database (reverse lookup) to homeserver of courses 
                   1951: # Is used in pickcourse
                   1952: #
1.840     albertel 1953:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1954:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1955: 		     $crs_home);
1.352     www      1956:     }
                   1957: #
                   1958: # File accesses
                   1959: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1960: #
1.449     matthew  1961:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1962:         if ($entry =~ /___count$/) {
                   1963:             my ($dom,$name);
1.807     albertel 1964:             ($dom,$name,undef)=
1.811     albertel 1965: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1966:             if (! defined($dom) || $dom eq '' || 
                   1967:                 ! defined($name) || $name eq '') {
1.620     albertel 1968:                 my $cid = $env{'request.course.id'};
                   1969:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1970:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1971:             }
1.450     matthew  1972:             my $value = $accesshash{$entry};
                   1973:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1974:             my %temphash=($url => $value);
1.449     matthew  1975:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1976:             if ($result eq 'ok') {
                   1977:                 delete $accesshash{$entry};
                   1978:             } elsif ($result eq 'unknown_cmd') {
                   1979:                 # Target server has old code running on it.
1.450     matthew  1980:                 my %temphash=($entry => $value);
1.449     matthew  1981:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1982:                     delete $accesshash{$entry};
                   1983:                 }
                   1984:             }
                   1985:         } else {
1.811     albertel 1986:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1987:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1988:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1989:                 delete $accesshash{$entry};
                   1990:             }
1.185     www      1991:         }
1.191     harris41 1992:     }
1.352     www      1993: #
                   1994: # Roles
                   1995: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1996: #
1.800     albertel 1997:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1998:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1999: 	    split(/\:/,$entry);
                   2000:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2001:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2002:                 $rudom,$runame) eq 'ok') {
                   2003: 	    delete $userrolehash{$entry};
                   2004:         }
                   2005:     }
1.662     raeburn  2006: #
                   2007: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2008: #
                   2009:     my %domrolebuffer = ();
                   2010:     foreach my $entry (keys %domainrolehash) {
                   2011:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   2012:         if ($domrolebuffer{$rudom}) {
                   2013:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2014:                       '='.&escape($domainrolehash{$entry});
                   2015:         } else {
                   2016:             $domrolebuffer{$rudom}.=&escape($entry).
                   2017:                       '='.&escape($domainrolehash{$entry});
                   2018:         }
                   2019:         delete $domainrolehash{$entry};
                   2020:     }
                   2021:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2022: 	my %servers = &get_servers($dom,'library');
                   2023: 	foreach my $tryserver (keys(%servers)) {
                   2024: 	    unless (&reply('domroleput:'.$dom.':'.
                   2025: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2026: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2027: 	    }
1.662     raeburn  2028:         }
                   2029:     }
1.186     www      2030:     $dumpcount++;
1.157     www      2031: }
                   2032: 
                   2033: sub courselog {
                   2034:     my $what=shift;
1.158     www      2035:     $what=time.':'.$what;
1.620     albertel 2036:     unless ($env{'request.course.id'}) { return ''; }
                   2037:     $coursedombuf{$env{'request.course.id'}}=
                   2038:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2039:     $coursenumbuf{$env{'request.course.id'}}=
                   2040:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2041:     $coursehombuf{$env{'request.course.id'}}=
                   2042:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2043:     $coursedescrbuf{$env{'request.course.id'}}=
                   2044:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2045:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2046:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2047:     $courseownerbuf{$env{'request.course.id'}}=
                   2048:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2049:     $coursetypebuf{$env{'request.course.id'}}=
                   2050:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2051:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2052: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2053:     } else {
1.620     albertel 2054: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2055:     }
1.620     albertel 2056:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2057: 	&flushcourselogs();
                   2058:     }
1.158     www      2059: }
                   2060: 
                   2061: sub courseacclog {
                   2062:     my $fnsymb=shift;
1.620     albertel 2063:     unless ($env{'request.course.id'}) { return ''; }
                   2064:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2065:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2066:         $what.=':POST';
1.583     matthew  2067:         # FIXME: Probably ought to escape things....
1.800     albertel 2068: 	foreach my $key (keys(%env)) {
                   2069:             if ($key=~/^form\.(.*)/) {
                   2070: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2071:             }
1.191     harris41 2072:         }
1.583     matthew  2073:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2074:         # FIXME: We should not be depending on a form parameter that someone
                   2075:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2076:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2077:             $what.= ':POST';
                   2078:             # FIXME: Probably ought to escape things....
                   2079:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2080:                                  'crsdiscuss') {
1.620     albertel 2081:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2082:             }
                   2083:         }
1.158     www      2084:     }
                   2085:     &courselog($what);
1.149     www      2086: }
                   2087: 
1.185     www      2088: sub countacc {
                   2089:     my $url=&declutter(shift);
1.458     matthew  2090:     return if (! defined($url) || $url eq '');
1.620     albertel 2091:     unless ($env{'request.course.id'}) { return ''; }
                   2092:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2093:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2094:     $accesshash{$key}++;
1.185     www      2095: }
1.349     www      2096: 
1.361     www      2097: sub linklog {
                   2098:     my ($from,$to)=@_;
                   2099:     $from=&declutter($from);
                   2100:     $to=&declutter($to);
                   2101:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2102:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2103: }
                   2104:   
1.349     www      2105: sub userrolelog {
                   2106:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2107:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2108:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2109:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2110:         ($trole=~/^ta/)) {
1.350     www      2111:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2112:        $userrolehash
                   2113:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2114:                     =$tend.':'.$tstart;
1.662     raeburn  2115:     }
                   2116:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2117:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2118:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2119:         ($trole=~/^sc/)) {
                   2120:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2121:        $domainrolehash
                   2122:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2123:                     = $tend.':'.$tstart;
                   2124:     }
1.351     www      2125: }
                   2126: 
                   2127: sub get_course_adv_roles {
                   2128:     my $cid=shift;
1.620     albertel 2129:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2130:     my %coursehash=&coursedescription($cid);
1.470     www      2131:     my %nothide=();
1.800     albertel 2132:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2133: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2134:     }
1.351     www      2135:     my %returnhash=();
                   2136:     my %dumphash=
                   2137:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2138:     my $now=time;
1.800     albertel 2139:     foreach my $entry (keys %dumphash) {
                   2140: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2141:         if (($tstart) && ($tstart<0)) { next; }
                   2142:         if (($tend) && ($tend<$now)) { next; }
                   2143:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2144:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2145: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2146: 	if ((&privileged($username,$domain)) && 
                   2147: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2148: 	if ($role eq 'cr') { next; }
1.351     www      2149:         my $key=&plaintext($role);
                   2150:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2151:         if ($returnhash{$key}) {
                   2152: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2153:         } else {
                   2154:             $returnhash{$key}=$username.':'.$domain;
                   2155:         }
1.400     www      2156:      }
                   2157:     return %returnhash;
                   2158: }
                   2159: 
                   2160: sub get_my_roles {
1.858     raeburn  2161:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2162:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2163:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2164:     my %dumphash;
                   2165:     if ($context eq 'userroles') { 
                   2166:         %dumphash = &dump('roles',$udom,$uname);
                   2167:     } else {
                   2168:         %dumphash=
1.400     www      2169:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2170:     }
1.400     www      2171:     my %returnhash=();
                   2172:     my $now=time;
1.800     albertel 2173:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2174:         my ($role,$tend,$tstart);
                   2175:         if ($context eq 'userroles') {
                   2176: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2177:         } else {
                   2178:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2179:         }
1.400     www      2180:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2181:         my $status = 'active';
                   2182:         if (($tend) && ($tend<$now)) {
                   2183:             $status = 'previous';
                   2184:         } 
                   2185:         if (($tstart) && ($now<$tstart)) {
                   2186:             $status = 'future';
                   2187:         }
                   2188:         if (ref($types) eq 'ARRAY') {
                   2189:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2190:                 next;
                   2191:             } 
                   2192:         } else {
                   2193:             if ($status ne 'active') {
                   2194:                 next;
                   2195:             }
                   2196:         }
1.867     raeburn  2197:         my ($rolecode,$username,$domain,$section,$area);
                   2198:         if ($context eq 'userroles') {
                   2199:             ($area,$rolecode) = split(/_/,$entry);
                   2200:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2201:         } else {
                   2202:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2203:         }
1.832     raeburn  2204:         if (ref($roledoms) eq 'ARRAY') {
                   2205:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2206:                 next;
                   2207:             }
                   2208:         }
                   2209:         if (ref($roles) eq 'ARRAY') {
                   2210:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2211:                 next;
                   2212:             }
1.867     raeburn  2213:         }
1.400     www      2214: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2215:     }
1.373     www      2216:     return %returnhash;
1.399     www      2217: }
                   2218: 
                   2219: # ----------------------------------------------------- Frontpage Announcements
                   2220: #
                   2221: #
                   2222: 
                   2223: sub postannounce {
                   2224:     my ($server,$text)=@_;
1.844     albertel 2225:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2226:     unless ($text=~/\w/) { $text=''; }
                   2227:     return &reply('setannounce:'.&escape($text),$server);
                   2228: }
                   2229: 
                   2230: sub getannounce {
1.448     albertel 2231: 
                   2232:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2233: 	my $announcement='';
1.800     albertel 2234: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2235: 	close($fh);
1.399     www      2236: 	if ($announcement=~/\w/) { 
                   2237: 	    return 
                   2238:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2239:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2240: 	} else {
                   2241: 	    return '';
                   2242: 	}
                   2243:     } else {
                   2244: 	return '';
                   2245:     }
1.351     www      2246: }
1.353     www      2247: 
                   2248: # ---------------------------------------------------------- Course ID routines
                   2249: # Deal with domain's nohist_courseid.db files
                   2250: #
                   2251: 
                   2252: sub courseidput {
                   2253:     my ($domain,$what,$coursehome)=@_;
                   2254:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2255: }
                   2256: 
                   2257: sub courseiddump {
1.791     raeburn  2258:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2259:     my %returnhash=();
1.355     www      2260:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2261:     my %libserv = &all_library();
                   2262:     foreach my $tryserver (keys(%libserv)) {
                   2263:         if ( (  $hostidflag == 1 
                   2264: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2265: 	     || (!defined($hostidflag)) ) {
                   2266: 
                   2267: 	    if ($domfilter eq ''
                   2268: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2269: 	        foreach my $line (
1.844     albertel 2270:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2271: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2272:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2273:                                $tryserver))) {
1.800     albertel 2274: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2275:                     if (($key) && ($value)) {
1.516     raeburn  2276: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2277:                     }
1.353     www      2278:                 }
                   2279:             }
                   2280:         }
                   2281:     }
                   2282:     return %returnhash;
                   2283: }
                   2284: 
1.658     raeburn  2285: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2286: 
                   2287: sub dcmailput {
1.685     raeburn  2288:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2289:     my $status = &Apache::lonnet::critical(
1.740     www      2290:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2291:        &escape($message),$server);
1.662     raeburn  2292:     return $status;
                   2293: }
                   2294: 
1.658     raeburn  2295: sub dcmaildump {
                   2296:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2297:     my %returnhash=();
1.846     albertel 2298: 
                   2299:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2300:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2301:                                                          &escape($enddate).':';
                   2302: 	my @esc_senders=map { &escape($_)} @$senders;
                   2303: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2304: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2305:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2306:             if (($key) && ($value)) {
                   2307:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2308:             }
                   2309:         }
                   2310:     }
                   2311:     return %returnhash;
                   2312: }
1.662     raeburn  2313: # ---------------------------------------------------------- Domain roles
                   2314: 
                   2315: sub get_domain_roles {
                   2316:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2317:     if (undef($startdate) || $startdate eq '') {
                   2318:         $startdate = '.';
                   2319:     }
                   2320:     if (undef($enddate) || $enddate eq '') {
                   2321:         $enddate = '.';
                   2322:     }
                   2323:     my $rolelist = join(':',@{$roles});
                   2324:     my %personnel = ();
1.841     albertel 2325: 
                   2326:     my %servers = &get_servers($dom,'library');
                   2327:     foreach my $tryserver (keys(%servers)) {
                   2328: 	%{$personnel{$tryserver}}=();
                   2329: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2330: 					    &escape($startdate).':'.
                   2331: 					    &escape($enddate).':'.
                   2332: 					    &escape($rolelist), $tryserver))) {
                   2333: 	    my ($key,$value) = split(/\=/,$line,2);
                   2334: 	    if (($key) && ($value)) {
                   2335: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2336: 	    }
                   2337: 	}
1.662     raeburn  2338:     }
                   2339:     return %personnel;
                   2340: }
1.658     raeburn  2341: 
1.149     www      2342: # ----------------------------------------------------------- Check out an item
                   2343: 
1.504     albertel 2344: sub get_first_access {
                   2345:     my ($type,$argsymb)=@_;
1.790     albertel 2346:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2347:     if ($argsymb) { $symb=$argsymb; }
                   2348:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2349:     if ($type eq 'map') {
                   2350: 	$res=&symbread($map);
                   2351:     } else {
                   2352: 	$res=$symb;
                   2353:     }
                   2354:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2355:     return $times{"$courseid\0$res"};
1.504     albertel 2356: }
                   2357: 
                   2358: sub set_first_access {
                   2359:     my ($type)=@_;
1.790     albertel 2360:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2361:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2362:     if ($type eq 'map') {
                   2363: 	$res=&symbread($map);
                   2364:     } else {
                   2365: 	$res=$symb;
                   2366:     }
                   2367:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2368:     if (!$firstaccess) {
1.588     albertel 2369: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2370:     }
                   2371:     return 'already_set';
1.504     albertel 2372: }
                   2373: 
1.149     www      2374: sub checkout {
                   2375:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2376:     my $now=time;
                   2377:     my $lonhost=$perlvar{'lonHostID'};
                   2378:     my $infostr=&escape(
1.234     www      2379:                  'CHECKOUTTOKEN&'.
1.149     www      2380:                  $tuname.'&'.
                   2381:                  $tudom.'&'.
                   2382:                  $tcrsid.'&'.
                   2383:                  $symb.'&'.
                   2384: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2385:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2386:     if ($token=~/^error\:/) { 
1.672     albertel 2387:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2388:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2389:                  "</font>");
                   2390:         return ''; 
                   2391:     }
                   2392: 
1.149     www      2393:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2394:     $token=~tr/a-z/A-Z/;
                   2395: 
1.153     www      2396:     my %infohash=('resource.0.outtoken' => $token,
                   2397:                   'resource.0.checkouttime' => $now,
                   2398:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2399: 
                   2400:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2401:        return '';
1.151     www      2402:     } else {
1.672     albertel 2403:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2404:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2405:                  "</font>");
1.149     www      2406:     }    
                   2407: 
                   2408:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2409:                          &escape('Checkout '.$infostr.' - '.
                   2410:                                                  $token)) ne 'ok') {
                   2411: 	return '';
1.151     www      2412:     } else {
1.672     albertel 2413:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2414:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2415:                  "</font>");
1.149     www      2416:     }
1.151     www      2417:     return $token;
1.149     www      2418: }
                   2419: 
                   2420: # ------------------------------------------------------------ Check in an item
                   2421: 
                   2422: sub checkin {
                   2423:     my $token=shift;
1.150     www      2424:     my $now=time;
                   2425:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2426:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2427:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2428:     $dtoken=~s/\W/\_/g;
1.234     www      2429:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2430:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2431: 
1.154     www      2432:     unless (($tuname) && ($tudom)) {
                   2433:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2434:         return '';
                   2435:     }
                   2436:     
                   2437:     unless (&allowed('mgr',$tcrsid)) {
                   2438:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2439:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2440:         return '';
                   2441:     }
                   2442: 
1.153     www      2443:     my %infohash=('resource.0.intoken' => $token,
                   2444:                   'resource.0.checkintime' => $now,
                   2445:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2446: 
                   2447:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2448:        return '';
                   2449:     }    
                   2450: 
                   2451:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2452:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2453: 	return '';
                   2454:     }
                   2455: 
                   2456:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2457: }
                   2458: 
                   2459: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2460: 
                   2461: sub expirespread {
                   2462:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2463:     my $cid=$env{'request.course.id'}; 
1.110     www      2464:     if ($cid) {
                   2465:        my $now=time;
                   2466:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2467:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2468:                             $env{'course.'.$cid.'.num'}.
1.110     www      2469: 	        	    ':nohist_expirationdates:'.
                   2470:                             &escape($key).'='.$now,
1.620     albertel 2471:                             $env{'course.'.$cid.'.home'})
1.110     www      2472:     }
                   2473:     return 'ok';
1.14      www      2474: }
                   2475: 
1.109     www      2476: # ----------------------------------------------------- Devalidate Spreadsheets
                   2477: 
                   2478: sub devalidate {
1.325     www      2479:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2480:     my $cid=$env{'request.course.id'}; 
1.109     www      2481:     if ($cid) {
1.391     matthew  2482:         # delete the stored spreadsheets for
                   2483:         # - the student level sheet of this user in course's homespace
                   2484:         # - the assessment level sheet for this resource 
                   2485:         #   for this user in user's homespace
1.553     albertel 2486: 	# - current conditional state info
1.325     www      2487: 	my $key=$uname.':'.$udom.':';
1.109     www      2488:         my $status=
1.299     matthew  2489: 	    &del('nohist_calculatedsheets',
1.391     matthew  2490: 		 [$key.'studentcalc:'],
1.620     albertel 2491: 		 $env{'course.'.$cid.'.domain'},
                   2492: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2493: 		.' '.
                   2494: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2495: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2496:         unless ($status eq 'ok ok') {
                   2497:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2498:                     $uname.' at '.$udom.' for '.
1.109     www      2499: 		    $symb.': '.$status);
1.133     albertel 2500:         }
1.553     albertel 2501: 	&delenv('user.state.'.$cid);
1.109     www      2502:     }
                   2503: }
                   2504: 
1.265     albertel 2505: sub get_scalar {
                   2506:     my ($string,$end) = @_;
                   2507:     my $value;
                   2508:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2509: 	$value = $1;
                   2510:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2511: 	$value = $1;
                   2512:     }
                   2513:     return &unescape($value);
                   2514: }
                   2515: 
                   2516: sub array2str {
                   2517:   my (@array) = @_;
                   2518:   my $result=&arrayref2str(\@array);
                   2519:   $result=~s/^__ARRAY_REF__//;
                   2520:   $result=~s/__END_ARRAY_REF__$//;
                   2521:   return $result;
                   2522: }
                   2523: 
1.204     albertel 2524: sub arrayref2str {
                   2525:   my ($arrayref) = @_;
1.265     albertel 2526:   my $result='__ARRAY_REF__';
1.204     albertel 2527:   foreach my $elem (@$arrayref) {
1.265     albertel 2528:     if(ref($elem) eq 'ARRAY') {
                   2529:       $result.=&arrayref2str($elem).'&';
                   2530:     } elsif(ref($elem) eq 'HASH') {
                   2531:       $result.=&hashref2str($elem).'&';
                   2532:     } elsif(ref($elem)) {
                   2533:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2534:     } else {
                   2535:       $result.=&escape($elem).'&';
                   2536:     }
                   2537:   }
                   2538:   $result=~s/\&$//;
1.265     albertel 2539:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2540:   return $result;
                   2541: }
                   2542: 
1.168     albertel 2543: sub hash2str {
1.204     albertel 2544:   my (%hash) = @_;
                   2545:   my $result=&hashref2str(\%hash);
1.265     albertel 2546:   $result=~s/^__HASH_REF__//;
                   2547:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2548:   return $result;
                   2549: }
                   2550: 
                   2551: sub hashref2str {
                   2552:   my ($hashref)=@_;
1.265     albertel 2553:   my $result='__HASH_REF__';
1.800     albertel 2554:   foreach my $key (sort(keys(%$hashref))) {
                   2555:     if (ref($key) eq 'ARRAY') {
                   2556:       $result.=&arrayref2str($key).'=';
                   2557:     } elsif (ref($key) eq 'HASH') {
                   2558:       $result.=&hashref2str($key).'=';
                   2559:     } elsif (ref($key)) {
1.265     albertel 2560:       $result.='=';
1.800     albertel 2561:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2562:     } else {
1.800     albertel 2563: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2564:     }
                   2565: 
1.800     albertel 2566:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2567:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2568:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2569:       $result.=&hashref2str($hashref->{$key}).'&';
                   2570:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2571:        $result.='&';
1.800     albertel 2572:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2573:     } else {
1.800     albertel 2574:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2575:     }
                   2576:   }
1.168     albertel 2577:   $result=~s/\&$//;
1.265     albertel 2578:   $result .= '__END_HASH_REF__';
1.168     albertel 2579:   return $result;
                   2580: }
                   2581: 
                   2582: sub str2hash {
1.265     albertel 2583:     my ($string)=@_;
                   2584:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2585:     return %$hash;
                   2586: }
                   2587: 
                   2588: sub str2hashref {
1.168     albertel 2589:   my ($string) = @_;
1.265     albertel 2590: 
                   2591:   my %hash;
                   2592: 
                   2593:   if($string !~ /^__HASH_REF__/) {
                   2594:       if (! ($string eq '' || !defined($string))) {
                   2595: 	  $hash{'error'}='Not hash reference';
                   2596:       }
                   2597:       return (\%hash, $string);
                   2598:   }
                   2599: 
                   2600:   $string =~ s/^__HASH_REF__//;
                   2601: 
                   2602:   while($string !~ /^__END_HASH_REF__/) {
                   2603:       #key
                   2604:       my $key='';
                   2605:       if($string =~ /^__HASH_REF__/) {
                   2606:           ($key, $string)=&str2hashref($string);
                   2607:           if(defined($key->{'error'})) {
                   2608:               $hash{'error'}='Bad data';
                   2609:               return (\%hash, $string);
                   2610:           }
                   2611:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2612:           ($key, $string)=&str2arrayref($string);
                   2613:           if($key->[0] eq 'Array reference error') {
                   2614:               $hash{'error'}='Bad data';
                   2615:               return (\%hash, $string);
                   2616:           }
                   2617:       } else {
                   2618:           $string =~ s/^(.*?)=//;
1.267     albertel 2619: 	  $key=&unescape($1);
1.265     albertel 2620:       }
                   2621:       $string =~ s/^=//;
                   2622: 
                   2623:       #value
                   2624:       my $value='';
                   2625:       if($string =~ /^__HASH_REF__/) {
                   2626:           ($value, $string)=&str2hashref($string);
                   2627:           if(defined($value->{'error'})) {
                   2628:               $hash{'error'}='Bad data';
                   2629:               return (\%hash, $string);
                   2630:           }
                   2631:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2632:           ($value, $string)=&str2arrayref($string);
                   2633:           if($value->[0] eq 'Array reference error') {
                   2634:               $hash{'error'}='Bad data';
                   2635:               return (\%hash, $string);
                   2636:           }
                   2637:       } else {
                   2638: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2639:       }
                   2640:       $string =~ s/^&//;
                   2641: 
                   2642:       $hash{$key}=$value;
1.204     albertel 2643:   }
1.265     albertel 2644: 
                   2645:   $string =~ s/^__END_HASH_REF__//;
                   2646: 
                   2647:   return (\%hash, $string);
1.204     albertel 2648: }
                   2649: 
                   2650: sub str2array {
1.265     albertel 2651:     my ($string)=@_;
                   2652:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2653:     return @$array;
                   2654: }
                   2655: 
                   2656: sub str2arrayref {
1.204     albertel 2657:   my ($string) = @_;
1.265     albertel 2658:   my @array;
                   2659: 
                   2660:   if($string !~ /^__ARRAY_REF__/) {
                   2661:       if (! ($string eq '' || !defined($string))) {
                   2662: 	  $array[0]='Array reference error';
                   2663:       }
                   2664:       return (\@array, $string);
                   2665:   }
                   2666: 
                   2667:   $string =~ s/^__ARRAY_REF__//;
                   2668: 
                   2669:   while($string !~ /^__END_ARRAY_REF__/) {
                   2670:       my $value='';
                   2671:       if($string =~ /^__HASH_REF__/) {
                   2672:           ($value, $string)=&str2hashref($string);
                   2673:           if(defined($value->{'error'})) {
                   2674:               $array[0] ='Array reference error';
                   2675:               return (\@array, $string);
                   2676:           }
                   2677:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2678:           ($value, $string)=&str2arrayref($string);
                   2679:           if($value->[0] eq 'Array reference error') {
                   2680:               $array[0] ='Array reference error';
                   2681:               return (\@array, $string);
                   2682:           }
                   2683:       } else {
                   2684: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2685:       }
                   2686:       $string =~ s/^&//;
                   2687: 
                   2688:       push(@array, $value);
1.191     harris41 2689:   }
1.265     albertel 2690: 
                   2691:   $string =~ s/^__END_ARRAY_REF__//;
                   2692: 
                   2693:   return (\@array, $string);
1.168     albertel 2694: }
                   2695: 
1.167     albertel 2696: # -------------------------------------------------------------------Temp Store
                   2697: 
1.168     albertel 2698: sub tmpreset {
                   2699:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2700:   if (!$symb) {
                   2701:     $symb=&symbread();
1.620     albertel 2702:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2703:   }
                   2704:   $symb=escape($symb);
                   2705: 
1.620     albertel 2706:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2707:   $namespace=~s/\//\_/g;
                   2708:   $namespace=~s/\W//g;
                   2709: 
1.620     albertel 2710:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2711:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2712:   if ($domain eq 'public' && $stuname eq 'public') {
                   2713:       $stuname=$ENV{'REMOTE_ADDR'};
                   2714:   }
1.168     albertel 2715:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2716:   my %hash;
                   2717:   if (tie(%hash,'GDBM_File',
                   2718: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2719: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2720:     foreach my $key (keys %hash) {
1.180     albertel 2721:       if ($key=~ /:$symb/) {
1.168     albertel 2722: 	delete($hash{$key});
                   2723:       }
                   2724:     }
                   2725:   }
                   2726: }
                   2727: 
1.167     albertel 2728: sub tmpstore {
1.168     albertel 2729:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2730: 
                   2731:   if (!$symb) {
                   2732:     $symb=&symbread();
1.620     albertel 2733:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2734:   }
                   2735:   $symb=escape($symb);
                   2736: 
                   2737:   if (!$namespace) {
                   2738:     # I don't think we would ever want to store this for a course.
                   2739:     # it seems this will only be used if we don't have a course.
1.620     albertel 2740:     #$namespace=$env{'request.course.id'};
1.168     albertel 2741:     #if (!$namespace) {
1.620     albertel 2742:       $namespace=$env{'request.state'};
1.168     albertel 2743:     #}
                   2744:   }
                   2745:   $namespace=~s/\//\_/g;
                   2746:   $namespace=~s/\W//g;
1.620     albertel 2747:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2748:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2749:   if ($domain eq 'public' && $stuname eq 'public') {
                   2750:       $stuname=$ENV{'REMOTE_ADDR'};
                   2751:   }
1.168     albertel 2752:   my $now=time;
                   2753:   my %hash;
                   2754:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2755:   if (tie(%hash,'GDBM_File',
                   2756: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2757: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2758:     $hash{"version:$symb"}++;
                   2759:     my $version=$hash{"version:$symb"};
                   2760:     my $allkeys=''; 
                   2761:     foreach my $key (keys(%$storehash)) {
                   2762:       $allkeys.=$key.':';
1.591     albertel 2763:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2764:     }
                   2765:     $hash{"$version:$symb:timestamp"}=$now;
                   2766:     $allkeys.='timestamp';
                   2767:     $hash{"$version:keys:$symb"}=$allkeys;
                   2768:     if (untie(%hash)) {
                   2769:       return 'ok';
                   2770:     } else {
                   2771:       return "error:$!";
                   2772:     }
                   2773:   } else {
                   2774:     return "error:$!";
                   2775:   }
                   2776: }
1.167     albertel 2777: 
1.168     albertel 2778: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2779: 
1.168     albertel 2780: sub tmprestore {
                   2781:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2782: 
1.168     albertel 2783:   if (!$symb) {
                   2784:     $symb=&symbread();
1.620     albertel 2785:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2786:   }
                   2787:   $symb=escape($symb);
                   2788: 
1.620     albertel 2789:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2790: 
1.620     albertel 2791:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2792:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2793:   if ($domain eq 'public' && $stuname eq 'public') {
                   2794:       $stuname=$ENV{'REMOTE_ADDR'};
                   2795:   }
1.168     albertel 2796:   my %returnhash;
                   2797:   $namespace=~s/\//\_/g;
                   2798:   $namespace=~s/\W//g;
                   2799:   my %hash;
                   2800:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2801:   if (tie(%hash,'GDBM_File',
                   2802: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2803: 	  &GDBM_READER(),0640)) {
1.168     albertel 2804:     my $version=$hash{"version:$symb"};
                   2805:     $returnhash{'version'}=$version;
                   2806:     my $scope;
                   2807:     for ($scope=1;$scope<=$version;$scope++) {
                   2808:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2809:       my @keys=split(/:/,$vkeys);
                   2810:       my $key;
                   2811:       $returnhash{"$scope:keys"}=$vkeys;
                   2812:       foreach $key (@keys) {
1.591     albertel 2813: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2814: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2815:       }
                   2816:     }
1.168     albertel 2817:     if (!(untie(%hash))) {
                   2818:       return "error:$!";
                   2819:     }
                   2820:   } else {
                   2821:     return "error:$!";
                   2822:   }
                   2823:   return %returnhash;
1.167     albertel 2824: }
                   2825: 
1.9       www      2826: # ----------------------------------------------------------------------- Store
                   2827: 
                   2828: sub store {
1.124     www      2829:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2830:     my $home='';
                   2831: 
1.168     albertel 2832:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2833: 
1.213     www      2834:     $symb=&symbclean($symb);
1.122     albertel 2835:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2836: 
1.620     albertel 2837:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2838:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2839: 
                   2840:     &devalidate($symb,$stuname,$domain);
1.109     www      2841: 
                   2842:     $symb=escape($symb);
1.187     www      2843:     if (!$namespace) { 
1.620     albertel 2844:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2845:           return ''; 
                   2846:        } 
                   2847:     }
1.620     albertel 2848:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2849: 
                   2850:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2851:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2852: 
1.12      www      2853:     my $namevalue='';
1.800     albertel 2854:     foreach my $key (keys(%$storehash)) {
                   2855:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2856:     }
1.12      www      2857:     $namevalue=~s/\&$//;
1.187     www      2858:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2859:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2860: }
                   2861: 
1.47      www      2862: # -------------------------------------------------------------- Critical Store
                   2863: 
                   2864: sub cstore {
1.124     www      2865:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2866:     my $home='';
                   2867: 
1.168     albertel 2868:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2869: 
1.213     www      2870:     $symb=&symbclean($symb);
1.122     albertel 2871:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2872: 
1.620     albertel 2873:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2874:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2875: 
                   2876:     &devalidate($symb,$stuname,$domain);
1.109     www      2877: 
                   2878:     $symb=escape($symb);
1.187     www      2879:     if (!$namespace) { 
1.620     albertel 2880:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2881:           return ''; 
                   2882:        } 
                   2883:     }
1.620     albertel 2884:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2885: 
                   2886:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2887:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2888: 
1.47      www      2889:     my $namevalue='';
1.800     albertel 2890:     foreach my $key (keys(%$storehash)) {
                   2891:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2892:     }
1.47      www      2893:     $namevalue=~s/\&$//;
1.187     www      2894:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2895:     return critical
                   2896:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2897: }
                   2898: 
1.9       www      2899: # --------------------------------------------------------------------- Restore
                   2900: 
                   2901: sub restore {
1.124     www      2902:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2903:     my $home='';
                   2904: 
1.168     albertel 2905:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2906: 
1.122     albertel 2907:     if (!$symb) {
                   2908:       unless ($symb=escape(&symbread())) { return ''; }
                   2909:     } else {
1.213     www      2910:       $symb=&escape(&symbclean($symb));
1.122     albertel 2911:     }
1.188     www      2912:     if (!$namespace) { 
1.620     albertel 2913:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2914:           return ''; 
                   2915:        } 
                   2916:     }
1.620     albertel 2917:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2918:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2919:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2920:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2921: 
1.12      www      2922:     my %returnhash=();
1.800     albertel 2923:     foreach my $line (split(/\&/,$answer)) {
                   2924: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2925:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2926:     }
1.75      www      2927:     my $version;
                   2928:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2929:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2930:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2931:        }
1.75      www      2932:     }
1.13      www      2933:     return %returnhash;
1.34      www      2934: }
                   2935: 
                   2936: # ---------------------------------------------------------- Course Description
                   2937: 
                   2938: sub coursedescription {
1.731     albertel 2939:     my ($courseid,$args)=@_;
1.34      www      2940:     $courseid=~s/^\///;
1.49      www      2941:     $courseid=~s/\_/\//g;
1.34      www      2942:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2943:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2944:     my $normalid=$cdomain.'_'.$cnum;
                   2945:     # need to always cache even if we get errors otherwise we keep 
                   2946:     # trying and trying and trying to get the course description.
                   2947:     my %envhash=();
                   2948:     my %returnhash=();
1.731     albertel 2949:     
                   2950:     my $expiretime=600;
                   2951:     if ($env{'request.course.id'} eq $normalid) {
                   2952: 	$expiretime=120;
                   2953:     }
                   2954: 
                   2955:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2956:     if (!$args->{'freshen_cache'}
                   2957: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2958: 	foreach my $key (keys(%env)) {
                   2959: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2960: 	    my ($setting) = $1;
                   2961: 	    $returnhash{$setting} = $env{$key};
                   2962: 	}
                   2963: 	return %returnhash;
                   2964:     }
                   2965: 
                   2966:     # get the data agin
                   2967:     if (!$args->{'one_time'}) {
                   2968: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2969:     }
1.811     albertel 2970: 
1.34      www      2971:     if ($chome ne 'no_host') {
1.302     albertel 2972:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2973:        if (!exists($returnhash{'con_lost'})) {
                   2974:            $returnhash{'home'}= $chome;
                   2975: 	   $returnhash{'domain'} = $cdomain;
                   2976: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2977:            if (!defined($returnhash{'type'})) {
                   2978:                $returnhash{'type'} = 'Course';
                   2979:            }
1.130     albertel 2980:            while (my ($name,$value) = each %returnhash) {
1.53      www      2981:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2982:            }
1.270     www      2983:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2984:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2985: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2986:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2987:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2988:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2989:        }
                   2990:     }
1.731     albertel 2991:     if (!$args->{'one_time'}) {
                   2992: 	&appenv(%envhash);
                   2993:     }
1.302     albertel 2994:     return %returnhash;
1.461     www      2995: }
                   2996: 
                   2997: # -------------------------------------------------See if a user is privileged
                   2998: 
                   2999: sub privileged {
                   3000:     my ($username,$domain)=@_;
                   3001:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3002: 			&homeserver($username,$domain));
                   3003:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3004:     my $now=time;
                   3005:     if ($rolesdump ne '') {
1.800     albertel 3006:         foreach my $entry (split(/&/,$rolesdump)) {
                   3007: 	    if ($entry!~/^rolesdef_/) {
                   3008: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3009: 		$area=~s/\_\w\w$//;
                   3010: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3011: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3012: 		    my $active=1;
                   3013: 		    if ($tend) {
                   3014: 			if ($tend<$now) { $active=0; }
                   3015: 		    }
                   3016: 		    if ($tstart) {
                   3017: 			if ($tstart>$now) { $active=0; }
                   3018: 		    }
                   3019: 		    if ($active) { return 1; }
                   3020: 		}
                   3021: 	    }
                   3022: 	}
                   3023:     }
                   3024:     return 0;
1.9       www      3025: }
1.1       albertel 3026: 
1.103     harris41 3027: # -------------------------------------------------------- Get user privileges
1.11      www      3028: 
                   3029: sub rolesinit {
                   3030:     my ($domain,$username,$authhost)=@_;
                   3031:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3032:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3033:     my %allroles=();
1.678     raeburn  3034:     my %allgroups=();   
1.11      www      3035:     my $now=time;
1.743     albertel 3036:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3037:     my $group_privs;
1.11      www      3038: 
                   3039:     if ($rolesdump ne '') {
1.800     albertel 3040:         foreach my $entry (split(/&/,$rolesdump)) {
                   3041: 	  if ($entry!~/^rolesdef_/) {
                   3042:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3043: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3044:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3045: 	    if ($role=~/^cr/) { 
1.807     albertel 3046: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3047: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3048: 		    ($tend,$tstart)=split('_',$trest);
                   3049: 		} else {
                   3050: 		    $trole=$role;
                   3051: 		}
1.678     raeburn  3052:             } elsif ($role =~ m|^gr/|) {
                   3053:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3054:                 ($trole,$group_privs) = split(/\//,$trole);
                   3055:                 $group_privs = &unescape($group_privs);
1.587     albertel 3056: 	    } else {
                   3057: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3058: 	    }
1.743     albertel 3059: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3060: 					 $username);
                   3061: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3062:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3063:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3064:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3065: 		my $spec=$trole.'.'.$area;
                   3066: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3067: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3068:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3069:                 } elsif ($trole eq 'gr') {
                   3070:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3071: 		} else {
1.567     raeburn  3072:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3073: 		}
1.12      www      3074:             }
1.662     raeburn  3075:           }
1.191     harris41 3076:         }
1.743     albertel 3077:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3078:         $userroles{'user.adv'}    = $adv;
                   3079: 	$userroles{'user.author'} = $author;
1.620     albertel 3080:         $env{'user.adv'}=$adv;
1.11      www      3081:     }
1.743     albertel 3082:     return \%userroles;  
1.11      www      3083: }
                   3084: 
1.567     raeburn  3085: sub set_arearole {
                   3086:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3087: # log the associated role with the area
                   3088:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3089:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3090: }
                   3091: 
                   3092: sub custom_roleprivs {
                   3093:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3094:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3095:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3096:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3097:         my ($rdummy,$roledef)=
                   3098:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3099:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3100:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3101:             if (defined($syspriv)) {
                   3102:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3103:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3104:             }
                   3105:             if ($tdomain ne '') {
                   3106:                 if (defined($dompriv)) {
                   3107:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3108:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3109:                 }
                   3110:                 if (($trest ne '') && (defined($coursepriv))) {
                   3111:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3112:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3113:                 }
                   3114:             }
                   3115:         }
                   3116:     }
                   3117: }
                   3118: 
1.678     raeburn  3119: sub group_roleprivs {
                   3120:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3121:     my $access = 1;
                   3122:     my $now = time;
                   3123:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3124:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3125:     if ($access) {
1.811     albertel 3126:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3127:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3128:     }
                   3129: }
1.567     raeburn  3130: 
                   3131: sub standard_roleprivs {
                   3132:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3133:     if (defined($pr{$trole.':s'})) {
                   3134:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3135:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3136:     }
                   3137:     if ($tdomain ne '') {
                   3138:         if (defined($pr{$trole.':d'})) {
                   3139:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3140:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3141:         }
                   3142:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3143:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3144:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3145:         }
                   3146:     }
                   3147: }
                   3148: 
                   3149: sub set_userprivs {
1.678     raeburn  3150:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3151:     my $author=0;
                   3152:     my $adv=0;
1.678     raeburn  3153:     my %grouproles = ();
                   3154:     if (keys(%{$allgroups}) > 0) {
                   3155:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3156:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3157:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3158:                 $trole = $1;
                   3159:                 $area = $2;
1.681     raeburn  3160:                 $sec = $3;
                   3161:                 $extendedarea = $area.$sec;
                   3162:                 if (exists($$allgroups{$area})) {
                   3163:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3164:                         my $spec = $trole.'.'.$extendedarea;
                   3165:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3166:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3167:                     }
                   3168:                 }
                   3169:             }
                   3170:         }
                   3171:     }
1.800     albertel 3172:     foreach my $group (keys(%grouproles)) {
                   3173:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3174:     }
1.800     albertel 3175:     foreach my $role (keys(%{$allroles})) {
                   3176:         my %thesepriv;
                   3177:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3178:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3179:             if ($item ne '') {
                   3180:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3181:                 if ($restrictions eq '') {
                   3182:                     $thesepriv{$privilege}='F';
                   3183:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3184:                     $thesepriv{$privilege}.=$restrictions;
                   3185:                 }
                   3186:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3187:             }
                   3188:         }
                   3189:         my $thesestr='';
1.800     albertel 3190:         foreach my $priv (keys(%thesepriv)) {
                   3191: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3192: 	}
                   3193:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3194:     }
                   3195:     return ($author,$adv);
                   3196: }
                   3197: 
1.12      www      3198: # --------------------------------------------------------------- get interface
                   3199: 
                   3200: sub get {
1.131     albertel 3201:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3202:    my $items='';
1.800     albertel 3203:    foreach my $item (@$storearr) {
                   3204:        $items.=&escape($item).'&';
1.191     harris41 3205:    }
1.12      www      3206:    $items=~s/\&$//;
1.620     albertel 3207:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3208:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3209:    my $uhome=&homeserver($uname,$udomain);
                   3210: 
1.133     albertel 3211:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3212:    my @pairs=split(/\&/,$rep);
1.273     albertel 3213:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3214:      return @pairs;
                   3215:    }
1.15      www      3216:    my %returnhash=();
1.42      www      3217:    my $i=0;
1.800     albertel 3218:    foreach my $item (@$storearr) {
                   3219:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3220:       $i++;
1.191     harris41 3221:    }
1.15      www      3222:    return %returnhash;
1.27      www      3223: }
                   3224: 
                   3225: # --------------------------------------------------------------- del interface
                   3226: 
                   3227: sub del {
1.133     albertel 3228:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3229:    my $items='';
1.800     albertel 3230:    foreach my $item (@$storearr) {
                   3231:        $items.=&escape($item).'&';
1.191     harris41 3232:    }
1.27      www      3233:    $items=~s/\&$//;
1.620     albertel 3234:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3235:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3236:    my $uhome=&homeserver($uname,$udomain);
                   3237: 
                   3238:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3239: }
                   3240: 
                   3241: # -------------------------------------------------------------- dump interface
                   3242: 
                   3243: sub dump {
1.755     albertel 3244:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3245:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3246:     if (!$uname) { $uname=$env{'user.name'}; }
                   3247:     my $uhome=&homeserver($uname,$udomain);
                   3248:     if ($regexp) {
                   3249: 	$regexp=&escape($regexp);
                   3250:     } else {
                   3251: 	$regexp='.';
                   3252:     }
                   3253:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3254:     my @pairs=split(/\&/,$rep);
                   3255:     my %returnhash=();
                   3256:     foreach my $item (@pairs) {
                   3257: 	my ($key,$value)=split(/=/,$item,2);
                   3258: 	$key = &unescape($key);
                   3259: 	next if ($key =~ /^error: 2 /);
                   3260: 	$returnhash{$key}=&thaw_unescape($value);
                   3261:     }
                   3262:     return %returnhash;
1.407     www      3263: }
                   3264: 
1.717     albertel 3265: # --------------------------------------------------------- dumpstore interface
                   3266: 
                   3267: sub dumpstore {
                   3268:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3269:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3270:    if (!$uname) { $uname=$env{'user.name'}; }
                   3271:    my $uhome=&homeserver($uname,$udomain);
                   3272:    if ($regexp) {
                   3273:        $regexp=&escape($regexp);
                   3274:    } else {
                   3275:        $regexp='.';
                   3276:    }
                   3277:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3278:    my @pairs=split(/\&/,$rep);
                   3279:    my %returnhash=();
                   3280:    foreach my $item (@pairs) {
                   3281:        my ($key,$value)=split(/=/,$item,2);
                   3282:        next if ($key =~ /^error: 2 /);
                   3283:        $returnhash{$key}=&thaw_unescape($value);
                   3284:    }
                   3285:    return %returnhash;
1.717     albertel 3286: }
                   3287: 
1.407     www      3288: # -------------------------------------------------------------- keys interface
                   3289: 
                   3290: sub getkeys {
                   3291:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3292:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3293:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3294:    my $uhome=&homeserver($uname,$udomain);
                   3295:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3296:    my @keyarray=();
1.800     albertel 3297:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3298:       next if ($key =~ /^error: 2 /);
1.800     albertel 3299:       push(@keyarray,&unescape($key));
1.407     www      3300:    }
                   3301:    return @keyarray;
1.318     matthew  3302: }
                   3303: 
1.319     matthew  3304: # --------------------------------------------------------------- currentdump
                   3305: sub currentdump {
1.328     matthew  3306:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3307:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3308:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3309:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3310:    my $uhome = &homeserver($sname,$sdom);
                   3311:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3312:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3313:    #
1.318     matthew  3314:    my %returnhash=();
1.319     matthew  3315:    #
                   3316:    if ($rep eq "unknown_cmd") { 
                   3317:        # an old lond will not know currentdump
                   3318:        # Do a dump and make it look like a currentdump
1.822     albertel 3319:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3320:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3321:        my %hash = @tmp;
                   3322:        @tmp=();
1.424     matthew  3323:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3324:    } else {
                   3325:        my @pairs=split(/\&/,$rep);
1.800     albertel 3326:        foreach my $pair (@pairs) {
                   3327:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3328:            my ($symb,$param) = split(/:/,$key);
                   3329:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3330:                                                         &thaw_unescape($value);
1.319     matthew  3331:        }
1.191     harris41 3332:    }
1.12      www      3333:    return %returnhash;
1.424     matthew  3334: }
                   3335: 
                   3336: sub convert_dump_to_currentdump{
                   3337:     my %hash = %{shift()};
                   3338:     my %returnhash;
                   3339:     # Code ripped from lond, essentially.  The only difference
                   3340:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3341:     # we might run in to problems with parameter names =~ /^v\./
                   3342:     while (my ($key,$value) = each(%hash)) {
                   3343:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3344: 	$symb  = &unescape($symb);
                   3345: 	$param = &unescape($param);
1.424     matthew  3346:         next if ($v eq 'version' || $symb eq 'keys');
                   3347:         next if (exists($returnhash{$symb}) &&
                   3348:                  exists($returnhash{$symb}->{$param}) &&
                   3349:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3350:         $returnhash{$symb}->{$param}=$value;
                   3351:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3352:     }
                   3353:     #
                   3354:     # Remove all of the keys in the hashes which keep track of
                   3355:     # the version of the parameter.
                   3356:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3357:         # use a foreach because we are going to delete from the hash.
                   3358:         foreach my $key (keys(%$param_hash)) {
                   3359:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3360:         }
                   3361:     }
                   3362:     return \%returnhash;
1.12      www      3363: }
                   3364: 
1.627     albertel 3365: # ------------------------------------------------------ critical inc interface
                   3366: 
                   3367: sub cinc {
                   3368:     return &inc(@_,'critical');
                   3369: }
                   3370: 
1.449     matthew  3371: # --------------------------------------------------------------- inc interface
                   3372: 
                   3373: sub inc {
1.627     albertel 3374:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3375:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3376:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3377:     my $uhome=&homeserver($uname,$udomain);
                   3378:     my $items='';
                   3379:     if (! ref($store)) {
                   3380:         # got a single value, so use that instead
                   3381:         $items = &escape($store).'=&';
                   3382:     } elsif (ref($store) eq 'SCALAR') {
                   3383:         $items = &escape($$store).'=&';        
                   3384:     } elsif (ref($store) eq 'ARRAY') {
                   3385:         $items = join('=&',map {&escape($_);} @{$store});
                   3386:     } elsif (ref($store) eq 'HASH') {
                   3387:         while (my($key,$value) = each(%{$store})) {
                   3388:             $items.= &escape($key).'='.&escape($value).'&';
                   3389:         }
                   3390:     }
                   3391:     $items=~s/\&$//;
1.627     albertel 3392:     if ($critical) {
                   3393: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3394:     } else {
                   3395: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3396:     }
1.449     matthew  3397: }
                   3398: 
1.12      www      3399: # --------------------------------------------------------------- put interface
                   3400: 
                   3401: sub put {
1.134     albertel 3402:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3403:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3404:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3405:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3406:    my $items='';
1.800     albertel 3407:    foreach my $item (keys(%$storehash)) {
                   3408:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3409:    }
1.12      www      3410:    $items=~s/\&$//;
1.134     albertel 3411:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3412: }
                   3413: 
1.631     albertel 3414: # ------------------------------------------------------------ newput interface
                   3415: 
                   3416: sub newput {
                   3417:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3418:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3419:    if (!$uname) { $uname=$env{'user.name'}; }
                   3420:    my $uhome=&homeserver($uname,$udomain);
                   3421:    my $items='';
                   3422:    foreach my $key (keys(%$storehash)) {
                   3423:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3424:    }
                   3425:    $items=~s/\&$//;
                   3426:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3427: }
                   3428: 
                   3429: # ---------------------------------------------------------  putstore interface
                   3430: 
1.524     raeburn  3431: sub putstore {
1.715     albertel 3432:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3433:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3434:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3435:    my $uhome=&homeserver($uname,$udomain);
                   3436:    my $items='';
1.715     albertel 3437:    foreach my $key (keys(%$storehash)) {
                   3438:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3439:    }
1.715     albertel 3440:    $items=~s/\&$//;
1.716     albertel 3441:    my $esc_symb=&escape($symb);
                   3442:    my $esc_v=&escape($version);
1.715     albertel 3443:    my $reply =
1.716     albertel 3444:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3445: 	      $uhome);
                   3446:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3447:        # gfall back to way things use to be done
1.715     albertel 3448:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3449: 			    $uname);
1.524     raeburn  3450:    }
1.715     albertel 3451:    return $reply;
                   3452: }
                   3453: 
                   3454: sub old_putstore {
1.716     albertel 3455:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3456:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3457:     if (!$uname) { $uname=$env{'user.name'}; }
                   3458:     my $uhome=&homeserver($uname,$udomain);
                   3459:     my %newstorehash;
1.800     albertel 3460:     foreach my $item (keys(%$storehash)) {
                   3461: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3462: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3463:     }
                   3464:     my $items='';
                   3465:     my %allitems = ();
1.800     albertel 3466:     foreach my $item (keys(%newstorehash)) {
                   3467: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3468: 	    my $key = $1.':keys:'.$2;
                   3469: 	    $allitems{$key} .= $3.':';
                   3470: 	}
1.800     albertel 3471: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3472:     }
1.800     albertel 3473:     foreach my $item (keys(%allitems)) {
                   3474: 	$allitems{$item} =~ s/\:$//;
                   3475: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3476:     }
                   3477:     $items=~s/\&$//;
                   3478:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3479: }
                   3480: 
1.47      www      3481: # ------------------------------------------------------ critical put interface
                   3482: 
                   3483: sub cput {
1.134     albertel 3484:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3485:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3486:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3487:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3488:    my $items='';
1.800     albertel 3489:    foreach my $item (keys(%$storehash)) {
                   3490:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3491:    }
1.47      www      3492:    $items=~s/\&$//;
1.134     albertel 3493:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3494: }
                   3495: 
                   3496: # -------------------------------------------------------------- eget interface
                   3497: 
                   3498: sub eget {
1.133     albertel 3499:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3500:    my $items='';
1.800     albertel 3501:    foreach my $item (@$storearr) {
                   3502:        $items.=&escape($item).'&';
1.191     harris41 3503:    }
1.12      www      3504:    $items=~s/\&$//;
1.620     albertel 3505:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3506:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3507:    my $uhome=&homeserver($uname,$udomain);
                   3508:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3509:    my @pairs=split(/\&/,$rep);
                   3510:    my %returnhash=();
1.42      www      3511:    my $i=0;
1.800     albertel 3512:    foreach my $item (@$storearr) {
                   3513:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3514:       $i++;
1.191     harris41 3515:    }
1.12      www      3516:    return %returnhash;
                   3517: }
                   3518: 
1.667     albertel 3519: # ------------------------------------------------------------ tmpput interface
                   3520: sub tmpput {
1.802     raeburn  3521:     my ($storehash,$server,$context)=@_;
1.667     albertel 3522:     my $items='';
1.800     albertel 3523:     foreach my $item (keys(%$storehash)) {
                   3524: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3525:     }
                   3526:     $items=~s/\&$//;
1.802     raeburn  3527:     if (defined($context)) {
                   3528:         $items .= ':'.&escape($context);
                   3529:     }
1.667     albertel 3530:     return &reply("tmpput:$items",$server);
                   3531: }
                   3532: 
                   3533: # ------------------------------------------------------------ tmpget interface
                   3534: sub tmpget {
1.688     albertel 3535:     my ($token,$server)=@_;
                   3536:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3537:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3538:     my %returnhash;
                   3539:     foreach my $item (split(/\&/,$rep)) {
                   3540: 	my ($key,$value)=split(/=/,$item);
                   3541: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3542:     }
                   3543:     return %returnhash;
                   3544: }
                   3545: 
1.688     albertel 3546: # ------------------------------------------------------------ tmpget interface
                   3547: sub tmpdel {
                   3548:     my ($token,$server)=@_;
                   3549:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3550:     return &reply("tmpdel:$token",$server);
                   3551: }
                   3552: 
1.765     albertel 3553: # -------------------------------------------------- portfolio access checking
                   3554: 
                   3555: sub portfolio_access {
1.766     albertel 3556:     my ($requrl) = @_;
1.765     albertel 3557:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3558:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3559:     if ($result) {
                   3560:         my %setters;
                   3561:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3562:             my ($startblock,$endblock) =
                   3563:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3564:             if ($startblock && $endblock) {
                   3565:                 return 'B';
                   3566:             }
                   3567:         } else {
                   3568:             my ($startblock,$endblock) =
                   3569:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3570:             if ($startblock && $endblock) {
                   3571:                 return 'B';
                   3572:             }
                   3573:         }
                   3574:     }
1.765     albertel 3575:     if ($result eq 'ok') {
1.766     albertel 3576:        return 'F';
1.765     albertel 3577:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3578:        return 'A';
1.765     albertel 3579:     }
1.766     albertel 3580:     return '';
1.765     albertel 3581: }
                   3582: 
                   3583: sub get_portfolio_access {
1.767     albertel 3584:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3585: 
                   3586:     if (!ref($access_hash)) {
                   3587: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3588: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3589: 						   $file_name);
                   3590: 	$access_hash = $access_controls{$file_name};
                   3591:     }
                   3592: 
1.765     albertel 3593:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3594:     my $now = time;
                   3595:     if (ref($access_hash) eq 'HASH') {
                   3596:         foreach my $key (keys(%{$access_hash})) {
                   3597:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3598:             if ($start > $now) {
                   3599:                 next;
                   3600:             }
                   3601:             if ($end && $end<$now) {
                   3602:                 next;
                   3603:             }
                   3604:             if ($scope eq 'public') {
                   3605:                 $public = $key;
                   3606:                 last;
                   3607:             } elsif ($scope eq 'guest') {
                   3608:                 $guest = $key;
                   3609:             } elsif ($scope eq 'domains') {
                   3610:                 push(@domains,$key);
                   3611:             } elsif ($scope eq 'users') {
                   3612:                 push(@users,$key);
                   3613:             } elsif ($scope eq 'course') {
                   3614:                 push(@courses,$key);
                   3615:             } elsif ($scope eq 'group') {
                   3616:                 push(@groups,$key);
                   3617:             }
                   3618:         }
                   3619:         if ($public) {
                   3620:             return 'ok';
                   3621:         }
                   3622:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3623:             if ($guest) {
                   3624:                 return $guest;
                   3625:             }
                   3626:         } else {
                   3627:             if (@domains > 0) {
                   3628:                 foreach my $domkey (@domains) {
                   3629:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3630:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3631:                             return 'ok';
                   3632:                         }
                   3633:                     }
                   3634:                 }
                   3635:             }
                   3636:             if (@users > 0) {
                   3637:                 foreach my $userkey (@users) {
1.865     raeburn  3638:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3639:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3640:                             if (ref($item) eq 'HASH') {
                   3641:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3642:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3643:                                     return 'ok';
                   3644:                                 }
                   3645:                             }
                   3646:                         }
                   3647:                     } 
1.765     albertel 3648:                 }
                   3649:             }
                   3650:             my %roleshash;
                   3651:             my @courses_and_groups = @courses;
                   3652:             push(@courses_and_groups,@groups); 
                   3653:             if (@courses_and_groups > 0) {
                   3654:                 my (%allgroups,%allroles); 
                   3655:                 my ($start,$end,$role,$sec,$group);
                   3656:                 foreach my $envkey (%env) {
1.811     albertel 3657:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3658:                         my $cid = $2.'_'.$3; 
                   3659:                         if ($1 eq 'gr') {
                   3660:                             $group = $4;
                   3661:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3662:                         } else {
                   3663:                             if ($4 eq '') {
                   3664:                                 $sec = 'none';
                   3665:                             } else {
                   3666:                                 $sec = $4;
                   3667:                             }
                   3668:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3669:                         }
1.811     albertel 3670:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3671:                         my $cid = $2.'_'.$3;
                   3672:                         if ($4 eq '') {
                   3673:                             $sec = 'none';
                   3674:                         } else {
                   3675:                             $sec = $4;
                   3676:                         }
                   3677:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3678:                     }
                   3679:                 }
                   3680:                 if (keys(%allroles) == 0) {
                   3681:                     return;
                   3682:                 }
                   3683:                 foreach my $key (@courses_and_groups) {
                   3684:                     my %content = %{$$access_hash{$key}};
                   3685:                     my $cnum = $content{'number'};
                   3686:                     my $cdom = $content{'domain'};
                   3687:                     my $cid = $cdom.'_'.$cnum;
                   3688:                     if (!exists($allroles{$cid})) {
                   3689:                         next;
                   3690:                     }    
                   3691:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3692:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3693:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3694:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3695:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3696:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3697:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3698:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3699:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3700:                                         if (grep/^all$/,@sections) {
                   3701:                                             return 'ok';
                   3702:                                         } else {
                   3703:                                             if (grep/^$sec$/,@sections) {
                   3704:                                                 return 'ok';
                   3705:                                             }
                   3706:                                         }
                   3707:                                     }
                   3708:                                 }
                   3709:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3710:                                     if (grep/^none$/,@groups) {
                   3711:                                         return 'ok';
                   3712:                                     }
                   3713:                                 } else {
                   3714:                                     if (grep/^all$/,@groups) {
                   3715:                                         return 'ok';
                   3716:                                     } 
                   3717:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3718:                                         if (grep/^$group$/,@groups) {
                   3719:                                             return 'ok';
                   3720:                                         }
                   3721:                                     }
                   3722:                                 } 
                   3723:                             }
                   3724:                         }
                   3725:                     }
                   3726:                 }
                   3727:             }
                   3728:             if ($guest) {
                   3729:                 return $guest;
                   3730:             }
                   3731:         }
                   3732:     }
                   3733:     return;
                   3734: }
                   3735: 
                   3736: sub course_group_datechecker {
                   3737:     my ($dates,$now,$status) = @_;
                   3738:     my ($start,$end) = split(/\./,$dates);
                   3739:     if (!$start && !$end) {
                   3740:         return 'ok';
                   3741:     }
                   3742:     if (grep/^active$/,@{$status}) {
                   3743:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3744:             return 'ok';
                   3745:         }
                   3746:     }
                   3747:     if (grep/^previous$/,@{$status}) {
                   3748:         if ($end > $now ) {
                   3749:             return 'ok';
                   3750:         }
                   3751:     }
                   3752:     if (grep/^future$/,@{$status}) {
                   3753:         if ($start > $now) {
                   3754:             return 'ok';
                   3755:         }
                   3756:     }
                   3757:     return; 
                   3758: }
                   3759: 
                   3760: sub parse_portfolio_url {
                   3761:     my ($url) = @_;
                   3762: 
                   3763:     my ($type,$udom,$unum,$group,$file_name);
                   3764:     
1.823     albertel 3765:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3766: 	$type = 1;
                   3767:         $udom = $1;
                   3768:         $unum = $2;
                   3769:         $file_name = $3;
1.823     albertel 3770:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3771: 	$type = 2;
                   3772:         $udom = $1;
                   3773:         $unum = $2;
                   3774:         $group = $3;
                   3775:         $file_name = $3.'/'.$4;
                   3776:     }
                   3777:     if (wantarray) {
                   3778: 	return ($type,$udom,$unum,$file_name,$group);
                   3779:     }
                   3780:     return $type;
                   3781: }
                   3782: 
                   3783: sub is_portfolio_url {
                   3784:     my ($url) = @_;
                   3785:     return scalar(&parse_portfolio_url($url));
                   3786: }
                   3787: 
1.798     raeburn  3788: sub is_portfolio_file {
                   3789:     my ($file) = @_;
1.820     raeburn  3790:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3791:         return 1;
                   3792:     }
                   3793:     return;
                   3794: }
                   3795: 
                   3796: 
1.341     www      3797: # ---------------------------------------------- Custom access rule evaluation
                   3798: 
                   3799: sub customaccess {
                   3800:     my ($priv,$uri)=@_;
1.807     albertel 3801:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3802:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3803:     $udom = &LONCAPA::clean_domain($udom);
                   3804:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3805:     my $access=0;
1.800     albertel 3806:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3807: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3808:         if ($role) {
                   3809: 	   if ($role ne $urole) { next; }
                   3810:         }
1.800     albertel 3811:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3812:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3813:             if ($tdom) {
                   3814: 		if ($tdom ne $udom) { next; }
                   3815:             }
                   3816:             if ($tcrs) {
                   3817: 		if ($tcrs ne $ucrs) { next; }
                   3818:             }
                   3819:             if ($tsec) {
                   3820: 		if ($tsec ne $usec) { next; }
                   3821:             }
                   3822:             $access=($effect eq 'allow');
                   3823:             last;
1.342     www      3824:         }
1.402     bowersj2 3825: 	if ($realm eq '' && $role eq '') {
                   3826:             $access=($effect eq 'allow');
                   3827: 	}
1.341     www      3828:     }
                   3829:     return $access;
                   3830: }
                   3831: 
1.103     harris41 3832: # ------------------------------------------------- Check for a user privilege
1.12      www      3833: 
                   3834: sub allowed {
1.810     raeburn  3835:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3836:     my $ver_orguri=$uri;
1.439     www      3837:     $uri=&deversion($uri);
1.152     www      3838:     my $orguri=$uri;
1.52      www      3839:     $uri=&declutter($uri);
1.809     raeburn  3840: 
1.810     raeburn  3841:     if ($priv eq 'evb') {
                   3842: # Evade communication block restrictions for specified role in a course
                   3843:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3844:             return $1;
                   3845:         } else {
                   3846:             return;
                   3847:         }
                   3848:     }
                   3849: 
1.620     albertel 3850:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3851: # Free bre access to adm and meta resources
1.775     albertel 3852:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3853: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3854: 	&& ($priv eq 'bre')) {
1.14      www      3855: 	return 'F';
1.159     www      3856:     }
                   3857: 
1.545     banghart 3858: # Free bre access to user's own portfolio contents
1.714     raeburn  3859:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3860:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3861: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3862:         my %setters;
                   3863:         my ($startblock,$endblock) = 
                   3864:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3865:         if ($startblock && $endblock) {
                   3866:             return 'B';
                   3867:         } else {
                   3868:             return 'F';
                   3869:         }
1.545     banghart 3870:     }
                   3871: 
1.762     raeburn  3872: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3873:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3874:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3875:         if (exists($env{'request.course.id'})) {
                   3876:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3877:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3878:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3879:                 my $courseprivid=$env{'request.course.id'};
                   3880:                 $courseprivid=~s/\_/\//;
                   3881:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3882:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3883:                     return $1; 
1.762     raeburn  3884:                 } else {
                   3885:                     if ($env{'request.course.sec'}) {
                   3886:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3887:                     }
                   3888:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3889:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3890:                         return $2;
                   3891:                     }
1.714     raeburn  3892:                 }
                   3893:             }
                   3894:         }
                   3895:     }
                   3896: 
1.159     www      3897: # Free bre to public access
                   3898: 
                   3899:     if ($priv eq 'bre') {
1.238     www      3900:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3901: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3902:            return 'F'; 
                   3903:         }
1.238     www      3904:         if ($copyright eq 'priv') {
                   3905:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3906: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3907: 		return '';
                   3908:             }
                   3909:         }
                   3910:         if ($copyright eq 'domain') {
                   3911:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3912: 	    unless (($env{'user.domain'} eq $1) ||
                   3913:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3914: 		return '';
                   3915:             }
1.262     matthew  3916:         }
1.620     albertel 3917:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3918:             # Library role, so allow browsing of resources in this domain.
                   3919:             return 'F';
1.238     www      3920:         }
1.341     www      3921:         if ($copyright eq 'custom') {
                   3922: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3923:         }
1.14      www      3924:     }
1.264     matthew  3925:     # Domain coordinator is trying to create a course
1.620     albertel 3926:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3927:         # uri is the requested domain in this case.
                   3928:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3929:         # a role of dc for the domain in question.
1.620     albertel 3930:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3931:     }
1.29      www      3932: 
1.52      www      3933:     my $thisallowed='';
                   3934:     my $statecond=0;
                   3935:     my $courseprivid='';
                   3936: 
                   3937: # Course
                   3938: 
1.620     albertel 3939:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3940:        $thisallowed.=$1;
                   3941:     }
1.29      www      3942: 
1.52      www      3943: # Domain
                   3944: 
1.620     albertel 3945:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3946:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3947:        $thisallowed.=$1;
                   3948:     }
1.52      www      3949: 
                   3950: # Course: uri itself is a course
1.66      www      3951:     my $courseuri=$uri;
                   3952:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3953:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3954: 
1.620     albertel 3955:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3956:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3957:        $thisallowed.=$1;
                   3958:     }
1.29      www      3959: 
1.665     albertel 3960: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3961: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3962:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3963: 	$thisallowed='';
1.671     raeburn  3964:         my ($match)=&is_on_map($uri);
                   3965:         if ($match) {
                   3966:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3967:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3968:                 $thisallowed.=$1;
                   3969:             }
                   3970:         } else {
1.705     albertel 3971:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3972:             if ($refuri) {
                   3973:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3974:                     $thisallowed='F';
1.671     raeburn  3975:                 } else {
                   3976:                     $refuri=&declutter($refuri);
                   3977:                     my ($match) = &is_on_map($refuri);
                   3978:                     if ($match) {
                   3979:                         $thisallowed='F';
                   3980:                     }
1.669     raeburn  3981:                 }
1.671     raeburn  3982:             }
                   3983:         }
1.314     www      3984:     }
1.492     albertel 3985: 
1.766     albertel 3986:     if ($priv eq 'bre'
                   3987: 	&& $thisallowed ne 'F' 
                   3988: 	&& $thisallowed ne '2'
                   3989: 	&& &is_portfolio_url($uri)) {
                   3990: 	$thisallowed = &portfolio_access($uri);
                   3991:     }
                   3992:     
1.52      www      3993: # Full access at system, domain or course-wide level? Exit.
1.29      www      3994: 
                   3995:     if ($thisallowed=~/F/) {
                   3996: 	return 'F';
                   3997:     }
                   3998: 
1.52      www      3999: # If this is generating or modifying users, exit with special codes
1.29      www      4000: 
1.643     www      4001:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4002: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4003: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4004: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4005: 	    unless ($auname) { return $thisallowed; }
                   4006: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4007: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4008: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4009: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4010: 	}
1.52      www      4011: 	return $thisallowed;
                   4012:     }
                   4013: #
1.103     harris41 4014: # Gathered so far: system, domain and course wide privileges
1.52      www      4015: #
                   4016: # Course: See if uri or referer is an individual resource that is part of 
                   4017: # the course
                   4018: 
1.620     albertel 4019:     if ($env{'request.course.id'}) {
1.232     www      4020: 
1.620     albertel 4021:        $courseprivid=$env{'request.course.id'};
                   4022:        if ($env{'request.course.sec'}) {
                   4023:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4024:        }
                   4025:        $courseprivid=~s/\_/\//;
                   4026:        my $checkreferer=1;
1.232     www      4027:        my ($match,$cond)=&is_on_map($uri);
                   4028:        if ($match) {
                   4029:            $statecond=$cond;
1.620     albertel 4030:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4031:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4032:                $thisallowed.=$1;
                   4033:                $checkreferer=0;
                   4034:            }
1.29      www      4035:        }
1.83      www      4036:        
1.148     www      4037:        if ($checkreferer) {
1.620     albertel 4038: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4039:             unless ($refuri) {
1.800     albertel 4040:                 foreach my $key (keys(%env)) {
                   4041: 		    if ($key=~/^httpref\..*\*/) {
                   4042: 			my $pattern=$key;
1.156     www      4043:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4044:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4045:                         $pattern=~s/\//\\\//g;
1.152     www      4046:                         if ($orguri=~/$pattern/) {
1.800     albertel 4047: 			    $refuri=$env{$key};
1.148     www      4048:                         }
                   4049:                     }
1.191     harris41 4050:                 }
1.148     www      4051:             }
1.232     www      4052: 
1.148     www      4053:          if ($refuri) { 
1.152     www      4054: 	  $refuri=&declutter($refuri);
1.232     www      4055:           my ($match,$cond)=&is_on_map($refuri);
                   4056:             if ($match) {
                   4057:               my $refstatecond=$cond;
1.620     albertel 4058:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4059:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4060:                   $thisallowed.=$1;
1.53      www      4061:                   $uri=$refuri;
                   4062:                   $statecond=$refstatecond;
1.52      www      4063:               }
                   4064:           }
1.148     www      4065:         }
1.29      www      4066:        }
1.52      www      4067:    }
1.29      www      4068: 
1.52      www      4069: #
1.103     harris41 4070: # Gathered now: all privileges that could apply, and condition number
1.52      www      4071: # 
                   4072: #
                   4073: # Full or no access?
                   4074: #
1.29      www      4075: 
1.52      www      4076:     if ($thisallowed=~/F/) {
                   4077: 	return 'F';
                   4078:     }
1.29      www      4079: 
1.52      www      4080:     unless ($thisallowed) {
                   4081:         return '';
                   4082:     }
1.29      www      4083: 
1.52      www      4084: # Restrictions exist, deal with them
                   4085: #
                   4086: #   C:according to course preferences
                   4087: #   R:according to resource settings
                   4088: #   L:unless locked
                   4089: #   X:according to user session state
                   4090: #
                   4091: 
                   4092: # Possibly locked functionality, check all courses
1.54      www      4093: # Locks might take effect only after 10 minutes cache expiration for other
                   4094: # courses, and 2 minutes for current course
1.52      www      4095: 
                   4096:     my $envkey;
                   4097:     if ($thisallowed=~/L/) {
1.620     albertel 4098:         foreach $envkey (keys %env) {
1.54      www      4099:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4100:                my $courseid=$2;
                   4101:                my $roleid=$1.'.'.$2;
1.92      www      4102:                $courseid=~s/^\///;
1.54      www      4103:                my $expiretime=600;
1.620     albertel 4104:                if ($env{'request.role'} eq $roleid) {
1.54      www      4105: 		  $expiretime=120;
                   4106:                }
                   4107: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4108:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4109:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4110: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4111:                }
1.620     albertel 4112:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4113:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4114: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4115:                        &log($env{'user.domain'},$env{'user.name'},
                   4116:                             $env{'user.home'},
1.57      www      4117:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4118:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4119:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4120: 		       return '';
                   4121:                    }
                   4122:                }
1.620     albertel 4123:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4124:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4125: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4126:                        &log($env{'user.domain'},$env{'user.name'},
                   4127:                             $env{'user.home'},
1.57      www      4128:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4129:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4130:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4131: 		       return '';
                   4132:                    }
                   4133:                }
                   4134: 	   }
1.29      www      4135:        }
1.52      www      4136:     }
                   4137:    
                   4138: #
                   4139: # Rest of the restrictions depend on selected course
                   4140: #
                   4141: 
1.620     albertel 4142:     unless ($env{'request.course.id'}) {
1.766     albertel 4143: 	if ($thisallowed eq 'A') {
                   4144: 	    return 'A';
1.814     raeburn  4145:         } elsif ($thisallowed eq 'B') {
                   4146:             return 'B';
1.766     albertel 4147: 	} else {
                   4148: 	    return '1';
                   4149: 	}
1.52      www      4150:     }
1.29      www      4151: 
1.52      www      4152: #
                   4153: # Now user is definitely in a course
                   4154: #
1.53      www      4155: 
                   4156: 
                   4157: # Course preferences
                   4158: 
                   4159:    if ($thisallowed=~/C/) {
1.620     albertel 4160:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4161:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4162:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4163: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4164: 	   if ($priv ne 'pch') { 
                   4165: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4166: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4167: 			$env{'request.course.id'});
                   4168: 	   }
1.237     www      4169:            return '';
                   4170:        }
                   4171: 
1.620     albertel 4172:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4173: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4174: 	   if ($priv ne 'pch') { 
                   4175: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4176: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4177: 			$env{'request.course.id'});
                   4178: 	   }
1.54      www      4179:            return '';
                   4180:        }
1.53      www      4181:    }
                   4182: 
                   4183: # Resource preferences
                   4184: 
                   4185:    if ($thisallowed=~/R/) {
1.620     albertel 4186:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4187:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4188: 	   if ($priv ne 'pch') { 
                   4189: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4190: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4191: 	   }
                   4192: 	   return '';
1.54      www      4193:        }
1.53      www      4194:    }
1.30      www      4195: 
1.246     www      4196: # Restricted by state or randomout?
1.30      www      4197: 
1.52      www      4198:    if ($thisallowed=~/X/) {
1.620     albertel 4199:       if ($env{'acc.randomout'}) {
1.579     albertel 4200: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4201:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4202:             return ''; 
                   4203:          }
1.247     www      4204:       }
                   4205:       if (&condval($statecond)) {
1.52      www      4206: 	 return '2';
                   4207:       } else {
                   4208:          return '';
                   4209:       }
                   4210:    }
1.30      www      4211: 
1.766     albertel 4212:     if ($thisallowed eq 'A') {
                   4213: 	return 'A';
1.814     raeburn  4214:     } elsif ($thisallowed eq 'B') {
                   4215:         return 'B';
1.766     albertel 4216:     }
1.52      www      4217:    return 'F';
1.232     www      4218: }
                   4219: 
1.710     albertel 4220: sub split_uri_for_cond {
                   4221:     my $uri=&deversion(&declutter(shift));
                   4222:     my @uriparts=split(/\//,$uri);
                   4223:     my $filename=pop(@uriparts);
                   4224:     my $pathname=join('/',@uriparts);
                   4225:     return ($pathname,$filename);
                   4226: }
1.232     www      4227: # --------------------------------------------------- Is a resource on the map?
                   4228: 
                   4229: sub is_on_map {
1.710     albertel 4230:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4231:     #Trying to find the conditional for the file
1.620     albertel 4232:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4233: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4234:     if ($match) {
1.289     bowersj2 4235: 	return (1,$1);
                   4236:     } else {
1.434     www      4237: 	return (0,0);
1.289     bowersj2 4238:     }
1.12      www      4239: }
                   4240: 
1.427     www      4241: # --------------------------------------------------------- Get symb from alias
                   4242: 
                   4243: sub get_symb_from_alias {
                   4244:     my $symb=shift;
                   4245:     my ($map,$resid,$url)=&decode_symb($symb);
                   4246: # Already is a symb
                   4247:     if ($url) { return $symb; }
                   4248: # Must be an alias
                   4249:     my $aliassymb='';
                   4250:     my %bighash;
1.620     albertel 4251:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4252:                             &GDBM_READER(),0640)) {
                   4253:         my $rid=$bighash{'mapalias_'.$symb};
                   4254: 	if ($rid) {
                   4255: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4256: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4257: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4258: 	}
                   4259:         untie %bighash;
                   4260:     }
                   4261:     return $aliassymb;
                   4262: }
                   4263: 
1.12      www      4264: # ----------------------------------------------------------------- Define Role
                   4265: 
                   4266: sub definerole {
                   4267:   if (allowed('mcr','/')) {
                   4268:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4269:     foreach my $role (split(':',$sysrole)) {
                   4270: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4271:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4272:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4273: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4274:                return "refused:s:$crole&$cqual"; 
                   4275:             }
                   4276:         }
1.191     harris41 4277:     }
1.800     albertel 4278:     foreach my $role (split(':',$domrole)) {
                   4279: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4280:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4281:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4282: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4283:                return "refused:d:$crole&$cqual"; 
                   4284:             }
                   4285:         }
1.191     harris41 4286:     }
1.800     albertel 4287:     foreach my $role (split(':',$courole)) {
                   4288: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4289:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4290:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4291: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4292:                return "refused:c:$crole&$cqual"; 
                   4293:             }
                   4294:         }
1.191     harris41 4295:     }
1.620     albertel 4296:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4297:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4298: 	        "rolesdef_$rolename=".
                   4299:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4300:     return reply($command,$env{'user.home'});
1.12      www      4301:   } else {
                   4302:     return 'refused';
                   4303:   }
1.105     harris41 4304: }
                   4305: 
                   4306: # ---------------- Make a metadata query against the network of library servers
                   4307: 
                   4308: sub metadata_query {
1.244     matthew  4309:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4310:     my %rhash;
1.845     albertel 4311:     my %libserv = &all_library();
1.244     matthew  4312:     my @server_list = (defined($server_array) ? @$server_array
                   4313:                                               : keys(%libserv) );
                   4314:     for my $server (@server_list) {
1.118     harris41 4315: 	unless ($custom or $customshow) {
                   4316: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4317: 	    $rhash{$server}=$reply;
                   4318: 	}
                   4319: 	else {
                   4320: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4321: 			     &escape($custom).':'.&escape($customshow),
                   4322: 			     $server);
                   4323: 	    $rhash{$server}=$reply;
                   4324: 	}
1.112     harris41 4325:     }
1.118     harris41 4326:     return \%rhash;
1.240     www      4327: }
                   4328: 
                   4329: # ----------------------------------------- Send log queries and wait for reply
                   4330: 
                   4331: sub log_query {
                   4332:     my ($uname,$udom,$query,%filters)=@_;
                   4333:     my $uhome=&homeserver($uname,$udom);
                   4334:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4335:     my $uhost=&hostname($uhome);
1.800     albertel 4336:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4337:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4338:                        $uhome);
1.479     albertel 4339:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4340:     return get_query_reply($queryid);
                   4341: }
                   4342: 
1.818     raeburn  4343: # -------------------------- Update MySQL table for portfolio file
                   4344: 
                   4345: sub update_portfolio_table {
1.821     raeburn  4346:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4347:     my $homeserver = &homeserver($uname,$udom);
                   4348:     my $queryid=
1.821     raeburn  4349:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4350:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4351:     my $reply = &get_query_reply($queryid);
                   4352:     return $reply;
                   4353: }
                   4354: 
1.508     raeburn  4355: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4356: 
                   4357: sub fetch_enrollment_query {
1.511     raeburn  4358:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4359:     my $homeserver;
1.547     raeburn  4360:     my $maxtries = 1;
1.508     raeburn  4361:     if ($context eq 'automated') {
                   4362:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4363:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4364:     } else {
                   4365:         $homeserver = &homeserver($cnum,$dom);
                   4366:     }
1.838     albertel 4367:     my $host=&hostname($homeserver);
1.506     raeburn  4368:     my $cmd = '';
1.800     albertel 4369:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4370:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4371:     }
                   4372:     $cmd =~ s/%%$//;
                   4373:     $cmd = &escape($cmd);
                   4374:     my $query = 'fetchenrollment';
1.620     albertel 4375:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4376:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4377:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4378:         return 'error: '.$queryid;
                   4379:     }
1.506     raeburn  4380:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4381:     my $tries = 1;
                   4382:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4383:         $reply = &get_query_reply($queryid);
                   4384:         $tries ++;
                   4385:     }
1.526     raeburn  4386:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4387:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4388:     } else {
1.515     raeburn  4389:         my @responses = split/:/,$reply;
                   4390:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4391:             foreach my $line (@responses) {
                   4392:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4393:                 $$replyref{$key} = $value;
                   4394:             }
                   4395:         } else {
1.506     raeburn  4396:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4397:             foreach my $line (@responses) {
                   4398:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4399:                 $$replyref{$key} = $value;
                   4400:                 if ($value > 0) {
1.800     albertel 4401:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4402:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4403:                         my $destname = $pathname.'/'.$filename;
                   4404:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4405:                         if ($xml_classlist =~ /^error/) {
                   4406:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4407:                         } else {
1.506     raeburn  4408:                             if ( open(FILE,">$destname") ) {
                   4409:                                 print FILE &unescape($xml_classlist);
                   4410:                                 close(FILE);
1.526     raeburn  4411:                             } else {
                   4412:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4413:                             }
                   4414:                         }
                   4415:                     }
                   4416:                 }
                   4417:             }
                   4418:         }
                   4419:         return 'ok';
                   4420:     }
                   4421:     return 'error';
                   4422: }
                   4423: 
1.242     www      4424: sub get_query_reply {
                   4425:     my $queryid=shift;
1.240     www      4426:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4427:     my $reply='';
                   4428:     for (1..100) {
                   4429: 	sleep 2;
                   4430:         if (-e $replyfile.'.end') {
1.448     albertel 4431: 	    if (open(my $fh,$replyfile)) {
1.240     www      4432:                $reply.=<$fh>;
1.448     albertel 4433:                close($fh);
1.240     www      4434: 	   } else { return 'error: reply_file_error'; }
1.242     www      4435:            return &unescape($reply);
                   4436: 	}
1.240     www      4437:     }
1.242     www      4438:     return 'timeout:'.$queryid;
1.240     www      4439: }
                   4440: 
                   4441: sub courselog_query {
1.241     www      4442: #
                   4443: # possible filters:
                   4444: # url: url or symb
                   4445: # username
                   4446: # domain
                   4447: # action: view, submit, grade
                   4448: # start: timestamp
                   4449: # end: timestamp
                   4450: #
1.240     www      4451:     my (%filters)=@_;
1.620     albertel 4452:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4453:     if ($filters{'url'}) {
                   4454: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4455:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4456:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4457:     }
1.620     albertel 4458:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4459:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4460:     return &log_query($cname,$cdom,'courselog',%filters);
                   4461: }
                   4462: 
                   4463: sub userlog_query {
1.858     raeburn  4464: #
                   4465: # possible filters:
                   4466: # action: log check role
                   4467: # start: timestamp
                   4468: # end: timestamp
                   4469: #
1.240     www      4470:     my ($uname,$udom,%filters)=@_;
                   4471:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4472: }
                   4473: 
1.506     raeburn  4474: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4475: 
                   4476: sub auto_run {
1.508     raeburn  4477:     my ($cnum,$cdom) = @_;
1.876     raeburn  4478:     my $response = 0;
                   4479:     my $settings;
                   4480:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4481:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4482:         $settings = $domconfig{'autoenroll'};
                   4483:         if ($settings->{'run'} eq '1') {
                   4484:             $response = 1;
                   4485:         }
                   4486:     } else {
                   4487:         my $homeserver = &homeserver($cnum,$cdom);
                   4488:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4489:     }
1.506     raeburn  4490:     return $response;
                   4491: }
1.776     albertel 4492: 
1.506     raeburn  4493: sub auto_get_sections {
1.508     raeburn  4494:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4495:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4496:     my @secs = ();
1.511     raeburn  4497:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4498:     unless ($response eq 'refused') {
                   4499:         @secs = split/:/,$response;
                   4500:     }
                   4501:     return @secs;
                   4502: }
1.776     albertel 4503: 
1.506     raeburn  4504: sub auto_new_course {
1.508     raeburn  4505:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4506:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4507:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4508:     return $response;
                   4509: }
1.776     albertel 4510: 
1.506     raeburn  4511: sub auto_validate_courseID {
1.508     raeburn  4512:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4513:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4514:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4515:     return $response;
                   4516: }
1.776     albertel 4517: 
1.506     raeburn  4518: sub auto_create_password {
1.873     raeburn  4519:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4520:     my ($homeserver,$response);
1.506     raeburn  4521:     my $create_passwd = 0;
                   4522:     my $authchk = '';
1.873     raeburn  4523:     if ($udom =~ /^$match_domain$/) {
                   4524:         $homeserver = &domain($udom,'primary');
                   4525:     }
                   4526:     if ($homeserver eq '') {
                   4527:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4528:             $homeserver = &homeserver($cnum,$cdom);
                   4529:         }
                   4530:     }
                   4531:     if ($homeserver eq '') {
                   4532:         $authchk = 'nodomain';
1.506     raeburn  4533:     } else {
1.873     raeburn  4534:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4535:         if ($response eq 'refused') {
                   4536:             $authchk = 'refused';
                   4537:         } else {
                   4538:             ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4539:         }
1.506     raeburn  4540:     }
                   4541:     return ($authparam,$create_passwd,$authchk);
                   4542: }
                   4543: 
1.706     raeburn  4544: sub auto_photo_permission {
                   4545:     my ($cnum,$cdom,$students) = @_;
                   4546:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4547:     my ($outcome,$perm_reqd,$conditions) = 
                   4548: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4549:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4550: 	return (undef,undef);
                   4551:     }
1.706     raeburn  4552:     return ($outcome,$perm_reqd,$conditions);
                   4553: }
                   4554: 
                   4555: sub auto_checkphotos {
                   4556:     my ($uname,$udom,$pid) = @_;
                   4557:     my $homeserver = &homeserver($uname,$udom);
                   4558:     my ($result,$resulttype);
                   4559:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4560: 				   &escape($uname).':'.&escape($pid),
                   4561: 				   $homeserver));
1.709     albertel 4562:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4563: 	return (undef,undef);
                   4564:     }
1.706     raeburn  4565:     if ($outcome) {
                   4566:         ($result,$resulttype) = split(/:/,$outcome);
                   4567:     } 
                   4568:     return ($result,$resulttype);
                   4569: }
                   4570: 
                   4571: sub auto_photochoice {
                   4572:     my ($cnum,$cdom) = @_;
                   4573:     my $homeserver = &homeserver($cnum,$cdom);
                   4574:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4575: 						       &escape($cdom),
                   4576: 						       $homeserver)));
1.709     albertel 4577:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4578: 	return (undef,undef);
                   4579:     }
1.706     raeburn  4580:     return ($update,$comment);
                   4581: }
                   4582: 
                   4583: sub auto_photoupdate {
                   4584:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4585:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4586:     my $host=&hostname($homeserver);
1.706     raeburn  4587:     my $cmd = '';
                   4588:     my $maxtries = 1;
1.800     albertel 4589:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4590:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4591:     }
                   4592:     $cmd =~ s/%%$//;
                   4593:     $cmd = &escape($cmd);
                   4594:     my $query = 'institutionalphotos';
                   4595:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4596:     unless ($queryid=~/^\Q$host\E\_/) {
                   4597:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4598:         return 'error: '.$queryid;
                   4599:     }
                   4600:     my $reply = &get_query_reply($queryid);
                   4601:     my $tries = 1;
                   4602:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4603:         $reply = &get_query_reply($queryid);
                   4604:         $tries ++;
                   4605:     }
                   4606:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4607:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4608:     } else {
                   4609:         my @responses = split(/:/,$reply);
                   4610:         my $outcome = shift(@responses); 
                   4611:         foreach my $item (@responses) {
                   4612:             my ($key,$value) = split(/=/,$item);
                   4613:             $$photo{$key} = $value;
                   4614:         }
                   4615:         return $outcome;
                   4616:     }
                   4617:     return 'error';
                   4618: }
                   4619: 
1.521     raeburn  4620: sub auto_instcode_format {
1.793     albertel 4621:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4622: 	$cat_order) = @_;
1.521     raeburn  4623:     my $courses = '';
1.772     raeburn  4624:     my @homeservers;
1.521     raeburn  4625:     if ($caller eq 'global') {
1.841     albertel 4626: 	my %servers = &get_servers($codedom,'library');
                   4627: 	foreach my $tryserver (keys(%servers)) {
                   4628: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4629: 		push(@homeservers,$tryserver);
                   4630: 	    }
1.584     raeburn  4631:         }
1.521     raeburn  4632:     } else {
1.772     raeburn  4633:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4634:     }
1.793     albertel 4635:     foreach my $code (keys(%{$instcodes})) {
                   4636:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4637:     }
                   4638:     chop($courses);
1.772     raeburn  4639:     my $ok_response = 0;
                   4640:     my $response;
                   4641:     while (@homeservers > 0 && $ok_response == 0) {
                   4642:         my $server = shift(@homeservers); 
                   4643:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4644:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4645:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4646: 		split/:/,$response;
1.772     raeburn  4647:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4648:             push(@{$codetitles},&str2array($codetitles_str));
                   4649:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4650:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4651:             $ok_response = 1;
                   4652:         }
                   4653:     }
                   4654:     if ($ok_response) {
1.521     raeburn  4655:         return 'ok';
1.772     raeburn  4656:     } else {
                   4657:         return $response;
1.521     raeburn  4658:     }
                   4659: }
                   4660: 
1.792     raeburn  4661: sub auto_instcode_defaults {
                   4662:     my ($domain,$returnhash,$code_order) = @_;
                   4663:     my @homeservers;
1.841     albertel 4664: 
                   4665:     my %servers = &get_servers($domain,'library');
                   4666:     foreach my $tryserver (keys(%servers)) {
                   4667: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4668: 	    push(@homeservers,$tryserver);
                   4669: 	}
1.792     raeburn  4670:     }
1.841     albertel 4671: 
1.792     raeburn  4672:     my $response;
1.841     albertel 4673:     foreach my $server (@homeservers) {
1.792     raeburn  4674:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4675:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4676: 	
                   4677: 	foreach my $pair (split(/\&/,$response)) {
                   4678: 	    my ($name,$value)=split(/\=/,$pair);
                   4679: 	    if ($name eq 'code_order') {
                   4680: 		@{$code_order} = split(/\&/,&unescape($value));
                   4681: 	    } else {
                   4682: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4683: 	    }
                   4684: 	}
                   4685: 	return 'ok';
1.792     raeburn  4686:     }
1.841     albertel 4687: 
                   4688:     return $response;
1.792     raeburn  4689: } 
                   4690: 
1.777     albertel 4691: sub auto_validate_class_sec {
1.773     raeburn  4692:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4693:     my $homeserver = &homeserver($cnum,$cdom);
                   4694:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4695:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4696:     return $response;
                   4697: }
                   4698: 
1.679     raeburn  4699: # ------------------------------------------------------- Course Group routines
                   4700: 
                   4701: sub get_coursegroups {
1.809     raeburn  4702:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4703:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4704: }
                   4705: 
1.679     raeburn  4706: sub modify_coursegroup {
                   4707:     my ($cdom,$cnum,$groupsettings) = @_;
                   4708:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4709: }
                   4710: 
1.809     raeburn  4711: sub toggle_coursegroup_status {
                   4712:     my ($cdom,$cnum,$group,$action) = @_;
                   4713:     my ($from_namespace,$to_namespace);
                   4714:     if ($action eq 'delete') {
                   4715:         $from_namespace = 'coursegroups';
                   4716:         $to_namespace = 'deleted_groups';
                   4717:     } else {
                   4718:         $from_namespace = 'deleted_groups';
                   4719:         $to_namespace = 'coursegroups';
                   4720:     }
                   4721:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4722:     if (my $tmp = &error(%curr_group)) {
                   4723:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4724:         return ('read error',$tmp);
                   4725:     } else {
                   4726:         my %savedsettings = %curr_group; 
1.809     raeburn  4727:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4728:         my $deloutcome;
                   4729:         if ($result eq 'ok') {
1.809     raeburn  4730:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4731:         } else {
                   4732:             return ('write error',$result);
                   4733:         }
                   4734:         if ($deloutcome eq 'ok') {
                   4735:             return 'ok';
                   4736:         } else {
                   4737:             return ('delete error',$deloutcome);
                   4738:         }
                   4739:     }
                   4740: }
                   4741: 
1.679     raeburn  4742: sub modify_group_roles {
                   4743:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4744:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4745:     my $role = 'gr/'.&escape($userprivs);
                   4746:     my ($uname,$udom) = split(/:/,$user);
                   4747:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4748:     if ($result eq 'ok') {
                   4749:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4750:     }
1.679     raeburn  4751:     return $result;
                   4752: }
                   4753: 
                   4754: sub modify_coursegroup_membership {
                   4755:     my ($cdom,$cnum,$membership) = @_;
                   4756:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4757:     return $result;
                   4758: }
                   4759: 
1.682     raeburn  4760: sub get_active_groups {
                   4761:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4762:     my $now = time;
                   4763:     my %groups = ();
                   4764:     foreach my $key (keys(%env)) {
1.811     albertel 4765:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4766:             my ($start,$end) = split(/\./,$env{$key});
                   4767:             if (($end!=0) && ($end<$now)) { next; }
                   4768:             if (($start!=0) && ($start>$now)) { next; }
                   4769:             if ($1 eq $cdom && $2 eq $cnum) {
                   4770:                 $groups{$3} = $env{$key} ;
                   4771:             }
                   4772:         }
                   4773:     }
                   4774:     return %groups;
                   4775: }
                   4776: 
1.683     raeburn  4777: sub get_group_membership {
                   4778:     my ($cdom,$cnum,$group) = @_;
                   4779:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4780: }
                   4781: 
                   4782: sub get_users_groups {
                   4783:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4784:     my @usersgroups;
1.683     raeburn  4785:     my $cachetime=1800;
                   4786: 
                   4787:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4788:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4789:     if (defined($cached)) {
1.734     albertel 4790:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4791:     } else {  
                   4792:         $grouplist = '';
1.816     raeburn  4793:         my $courseurl = &courseid_to_courseurl($courseid);
                   4794:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4795:         my $access_end = $env{'course.'.$courseid.
                   4796:                               '.default_enrollment_end_date'};
                   4797:         my $now = time;
                   4798:         foreach my $key (keys(%roleshash)) {
                   4799:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4800:                 my $group = $1;
                   4801:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4802:                     my $start = $2;
                   4803:                     my $end = $1;
                   4804:                     if ($start == -1) { next; } # deleted from group
                   4805:                     if (($start!=0) && ($start>$now)) { next; }
                   4806:                     if (($end!=0) && ($end<$now)) {
                   4807:                         if ($access_end && $access_end < $now) {
                   4808:                             if ($access_end - $end < 86400) {
                   4809:                                 push(@usersgroups,$group);
1.733     raeburn  4810:                             }
                   4811:                         }
1.817     raeburn  4812:                         next;
1.733     raeburn  4813:                     }
1.817     raeburn  4814:                     push(@usersgroups,$group);
1.683     raeburn  4815:                 }
                   4816:             }
                   4817:         }
1.817     raeburn  4818:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4819:         $grouplist = join(':',@usersgroups);
                   4820:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4821:     }
1.733     raeburn  4822:     return @usersgroups;
1.683     raeburn  4823: }
                   4824: 
                   4825: sub devalidate_getgroups_cache {
                   4826:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4827:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4828: 
1.683     raeburn  4829:     my $hashid="$udom:$uname:$courseid";
                   4830:     &devalidate_cache_new('getgroups',$hashid);
                   4831: }
                   4832: 
1.12      www      4833: # ------------------------------------------------------------------ Plain Text
                   4834: 
                   4835: sub plaintext {
1.742     raeburn  4836:     my ($short,$type,$cid) = @_;
1.758     albertel 4837:     if ($short =~ /^cr/) {
                   4838: 	return (split('/',$short))[-1];
                   4839:     }
1.742     raeburn  4840:     if (!defined($cid)) {
                   4841:         $cid = $env{'request.course.id'};
                   4842:     }
                   4843:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4844:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4845:                                           '.plaintext'});
                   4846:     }
                   4847:     my %rolenames = (
                   4848:                       Course => 'std',
                   4849:                       Group => 'alt1',
                   4850:                     );
                   4851:     if (defined($type) && 
                   4852:          defined($rolenames{$type}) && 
                   4853:          defined($prp{$short}{$rolenames{$type}})) {
                   4854:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4855:     } else {
                   4856:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4857:     }
1.12      www      4858: }
                   4859: 
                   4860: # ----------------------------------------------------------------- Assign Role
                   4861: 
                   4862: sub assignrole {
1.357     www      4863:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4864:     my $mrole;
                   4865:     if ($role =~ /^cr\//) {
1.393     www      4866:         my $cwosec=$url;
1.811     albertel 4867:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4868: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4869:            &logthis('Refused custom assignrole: '.
                   4870:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4871: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4872:            return 'refused'; 
                   4873:         }
1.21      www      4874:         $mrole='cr';
1.678     raeburn  4875:     } elsif ($role =~ /^gr\//) {
                   4876:         my $cwogrp=$url;
1.811     albertel 4877:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4878:         unless (&allowed('mdg',$cwogrp)) {
                   4879:             &logthis('Refused group assignrole: '.
                   4880:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4881:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4882:             return 'refused';
                   4883:         }
                   4884:         $mrole='gr';
1.21      www      4885:     } else {
1.82      www      4886:         my $cwosec=$url;
1.811     albertel 4887:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4888:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4889:            &logthis('Refused assignrole: '.
                   4890:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4891: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4892:            return 'refused'; 
                   4893:         }
1.21      www      4894:         $mrole=$role;
                   4895:     }
1.620     albertel 4896:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4897:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4898:     if ($end) { $command.='_'.$end; }
1.21      www      4899:     if ($start) {
                   4900: 	if ($end) { 
1.81      www      4901:            $command.='_'.$start; 
1.21      www      4902:         } else {
1.81      www      4903:            $command.='_0_'.$start;
1.21      www      4904:         }
                   4905:     }
1.739     raeburn  4906:     my $origstart = $start;
                   4907:     my $origend = $end;
1.357     www      4908: # actually delete
                   4909:     if ($deleteflag) {
1.373     www      4910: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4911: # modify command to delete the role
1.620     albertel 4912:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4913:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4914: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4915: # set start and finish to negative values for userrolelog
                   4916:            $start=-1;
                   4917:            $end=-1;
                   4918:         }
                   4919:     }
                   4920: # send command
1.349     www      4921:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4922: # log new user role if status is ok
1.349     www      4923:     if ($answer eq 'ok') {
1.663     raeburn  4924: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4925: # for course roles, perform group memberships changes triggered by role change.
                   4926:         unless ($role =~ /^gr/) {
                   4927:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4928:                                              $origstart);
                   4929:         }
1.349     www      4930:     }
                   4931:     return $answer;
1.169     harris41 4932: }
                   4933: 
                   4934: # -------------------------------------------------- Modify user authentication
1.197     www      4935: # Overrides without validation
                   4936: 
1.169     harris41 4937: sub modifyuserauth {
                   4938:     my ($udom,$uname,$umode,$upass)=@_;
                   4939:     my $uhome=&homeserver($uname,$udom);
1.197     www      4940:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4941:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4942:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4943:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4944:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4945: 		     &escape($upass),$uhome);
1.620     albertel 4946:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4947:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4948:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4949:     &log($udom,,$uname,$uhome,
1.620     albertel 4950:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4951:                                      $env{'user.name'}.', '.$umode.
1.197     www      4952:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4953:     unless ($reply eq 'ok') {
1.197     www      4954:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4955: 	return 'error: '.$reply;
                   4956:     }   
1.170     harris41 4957:     return 'ok';
1.80      www      4958: }
                   4959: 
1.81      www      4960: # --------------------------------------------------------------- Modify a user
1.80      www      4961: 
1.81      www      4962: sub modifyuser {
1.206     matthew  4963:     my ($udom,    $uname, $uid,
                   4964:         $umode,   $upass, $first,
                   4965:         $middle,  $last,  $gene,
1.387     www      4966:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4967:     $udom= &LONCAPA::clean_domain($udom);
                   4968:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4969:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4970:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4971: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4972:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4973:                                      ' desiredhome not specified'). 
1.620     albertel 4974:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4975:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4976:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4977: # ----------------------------------------------------------------- Create User
1.406     albertel 4978:     if (($uhome eq 'no_host') && 
                   4979: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4980:         my $unhome='';
1.844     albertel 4981:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4982:             $unhome = $desiredhome;
1.620     albertel 4983: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4984: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4985:         } else { # load balancing routine for determining $unhome
1.81      www      4986:             my $loadm=10000000;
1.841     albertel 4987: 	    my %servers = &get_servers($udom,'library');
                   4988: 	    foreach my $tryserver (keys(%servers)) {
                   4989: 		my $answer=reply('load',$tryserver);
                   4990: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4991: 		    $loadm=$answer;
                   4992: 		    $unhome=$tryserver;
                   4993: 		}
1.80      www      4994: 	    }
                   4995:         }
                   4996:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4997: 	    return 'error: unable to find a home server for '.$uname.
                   4998:                    ' in domain '.$udom;
1.80      www      4999:         }
                   5000:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5001:                          &escape($upass),$unhome);
                   5002: 	unless ($reply eq 'ok') {
                   5003:             return 'error: '.$reply;
                   5004:         }   
1.230     stredwic 5005:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5006:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5007: 	    return 'error: unable verify users home machine.';
1.80      www      5008:         }
1.209     matthew  5009:     }   # End of creation of new user
1.80      www      5010: # ---------------------------------------------------------------------- Add ID
                   5011:     if ($uid) {
                   5012:        $uid=~tr/A-Z/a-z/;
                   5013:        my %uidhash=&idrget($udom,$uname);
1.196     www      5014:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5015:          && (!$forceid)) {
1.80      www      5016: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5017: 	      return 'error: user id "'.$uid.'" does not match '.
                   5018:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5019:           }
                   5020:        } else {
                   5021: 	  &idput($udom,($uname => $uid));
                   5022:        }
                   5023:     }
                   5024: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5025:     my @tmp=&get('environment',
1.134     albertel 5026: 		   ['firstname','middlename','lastname','generation'],
                   5027: 		   $udom,$uname);
1.313     matthew  5028:     my %names;
                   5029:     if ($tmp[0] =~ m/^error:.*/) { 
                   5030:         %names=(); 
                   5031:     } else {
                   5032:         %names = @tmp;
                   5033:     }
1.388     www      5034: #
                   5035: # Make sure to not trash student environment if instructor does not bother
                   5036: # to supply name and email information
                   5037: #
                   5038:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5039:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5040:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5041:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5042:     if ($email) {
                   5043:        $email=~s/[^\w\@\.\-\,]//gs;
                   5044:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5045: 			   $names{'critnotification'} = $email;
                   5046: 			   $names{'permanentemail'} = $email; }
                   5047:     }
1.134     albertel 5048:     my $reply = &put('environment', \%names, $udom,$uname);
                   5049:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      5050:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5051:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5052:              $umode.', '.$first.', '.$middle.', '.
                   5053: 	     $last.', '.$gene.' by '.
1.620     albertel 5054:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5055:     return 'ok';
1.80      www      5056: }
                   5057: 
1.81      www      5058: # -------------------------------------------------------------- Modify student
1.80      www      5059: 
1.81      www      5060: sub modifystudent {
                   5061:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5062:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5063:     if (!$cid) {
1.620     albertel 5064: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5065: 	    return 'not_in_class';
                   5066: 	}
1.80      www      5067:     }
                   5068: # --------------------------------------------------------------- Make the user
1.81      www      5069:     my $reply=&modifyuser
1.209     matthew  5070: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5071:          $desiredhome,$email);
1.80      www      5072:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5073:     # This will cause &modify_student_enrollment to get the uid from the
                   5074:     # students environment
                   5075:     $uid = undef if (!$forceid);
1.455     albertel 5076:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5077: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5078:     return $reply;
                   5079: }
                   5080: 
                   5081: sub modify_student_enrollment {
1.515     raeburn  5082:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5083:     my ($cdom,$cnum,$chome);
                   5084:     if (!$cid) {
1.620     albertel 5085: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5086: 	    return 'not_in_class';
                   5087: 	}
1.620     albertel 5088: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5089: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5090:     } else {
                   5091: 	($cdom,$cnum)=split(/_/,$cid);
                   5092:     }
1.620     albertel 5093:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5094:     if (!$chome) {
1.457     raeburn  5095: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5096:     }
1.455     albertel 5097:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5098:     # Make sure the user exists
1.81      www      5099:     my $uhome=&homeserver($uname,$udom);
                   5100:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5101: 	return 'error: no such user';
                   5102:     }
1.297     matthew  5103:     # Get student data if we were not given enough information
                   5104:     if (!defined($first)  || $first  eq '' || 
                   5105:         !defined($last)   || $last   eq '' || 
                   5106:         !defined($uid)    || $uid    eq '' || 
                   5107:         !defined($middle) || $middle eq '' || 
                   5108:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5109:         # They did not supply us with enough data to enroll the student, so
                   5110:         # we need to pick up more information.
1.297     matthew  5111:         my %tmp = &get('environment',
1.294     matthew  5112:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5113:                        ,$udom,$uname);
                   5114: 
1.800     albertel 5115:         #foreach my $key (keys(%tmp)) {
                   5116:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5117:         #}
1.294     matthew  5118:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5119:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5120:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5121:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5122:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5123:     }
1.556     albertel 5124:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5125:     my $reply=cput('classlist',
                   5126: 		   {"$uname:$udom" => 
1.515     raeburn  5127: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5128: 		   $cdom,$cnum);
1.81      www      5129:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5130: 	return 'error: '.$reply;
1.652     albertel 5131:     } else {
                   5132: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5133:     }
1.297     matthew  5134:     # Add student role to user
1.83      www      5135:     my $uurl='/'.$cid;
1.81      www      5136:     $uurl=~s/\_/\//g;
                   5137:     if ($usec) {
                   5138: 	$uurl.='/'.$usec;
                   5139:     }
                   5140:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5141: }
                   5142: 
1.556     albertel 5143: sub format_name {
                   5144:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5145:     my $name;
                   5146:     if ($first ne 'lastname') {
                   5147: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5148:     } else {
                   5149: 	if ($lastname=~/\S/) {
                   5150: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5151: 	    $name=~s/\s+,/,/;
                   5152: 	} else {
                   5153: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5154: 	}
                   5155:     }
                   5156:     $name=~s/^\s+//;
                   5157:     $name=~s/\s+$//;
                   5158:     $name=~s/\s+/ /g;
                   5159:     return $name;
                   5160: }
                   5161: 
1.84      www      5162: # ------------------------------------------------- Write to course preferences
                   5163: 
                   5164: sub writecoursepref {
                   5165:     my ($courseid,%prefs)=@_;
                   5166:     $courseid=~s/^\///;
                   5167:     $courseid=~s/\_/\//g;
                   5168:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5169:     my $chome=homeserver($cnum,$cdomain);
                   5170:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5171: 	return 'error: no such course';
                   5172:     }
                   5173:     my $cstring='';
1.800     albertel 5174:     foreach my $pref (keys(%prefs)) {
                   5175: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5176:     }
1.84      www      5177:     $cstring=~s/\&$//;
                   5178:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5179: }
                   5180: 
                   5181: # ---------------------------------------------------------- Make/modify course
                   5182: 
                   5183: sub createcourse {
1.741     raeburn  5184:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5185:         $course_owner,$crstype)=@_;
1.84      www      5186:     $url=&declutter($url);
                   5187:     my $cid='';
1.264     matthew  5188:     unless (&allowed('ccc',$udom)) {
1.84      www      5189:         return 'refused';
                   5190:     }
                   5191: # ------------------------------------------------------------------- Create ID
1.674     www      5192:    my $uname=int(1+rand(9)).
                   5193:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5194:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5195:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5196: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5197:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5198:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5199:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5200:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5201:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5202:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5203:            return 'error: unable to generate unique course-ID';
                   5204:        } 
                   5205:    }
1.264     matthew  5206: # ------------------------------------------------ Check supplied server name
1.620     albertel 5207:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5208:     if (! &is_library($course_server)) {
1.264     matthew  5209:         return 'error:bad server name '.$course_server;
                   5210:     }
1.84      www      5211: # ------------------------------------------------------------- Make the course
                   5212:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5213:                       $course_server);
1.84      www      5214:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5215:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5216:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5217: 	return 'error: no such course';
                   5218:     }
1.271     www      5219: # ----------------------------------------------------------------- Course made
1.516     raeburn  5220: # log existence
                   5221:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5222:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5223:                   &escape($crstype),$uhome);
1.358     www      5224:     &flushcourselogs();
                   5225: # set toplevel url
1.271     www      5226:     my $topurl=$url;
                   5227:     unless ($nonstandard) {
                   5228: # ------------------------------------------ For standard courses, make top url
                   5229:         my $mapurl=&clutter($url);
1.278     www      5230:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5231:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5232: <map>
                   5233: <resource id="1" type="start"></resource>
                   5234: <resource id="2" src="$mapurl"></resource>
                   5235: <resource id="3" type="finish"></resource>
                   5236: <link index="1" from="1" to="2"></link>
                   5237: <link index="2" from="2" to="3"></link>
                   5238: </map>
                   5239: ENDINITMAP
                   5240:         $topurl=&declutter(
1.638     albertel 5241:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5242:                           );
                   5243:     }
                   5244: # ----------------------------------------------------------- Write preferences
1.84      www      5245:     &writecoursepref($udom.'_'.$uname,
                   5246:                      ('description' => $description,
1.271     www      5247:                       'url'         => $topurl));
1.84      www      5248:     return '/'.$udom.'/'.$uname;
                   5249: }
                   5250: 
1.813     albertel 5251: sub is_course {
                   5252:     my ($cdom,$cnum) = @_;
                   5253:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5254: 				undef,'.');
                   5255:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5256:         return 1;
                   5257:     }
                   5258:     return 0;
                   5259: }
                   5260: 
1.21      www      5261: # ---------------------------------------------------------- Assign Custom Role
                   5262: 
                   5263: sub assigncustomrole {
1.357     www      5264:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5265:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5266:                        $end,$start,$deleteflag);
1.21      www      5267: }
                   5268: 
                   5269: # ----------------------------------------------------------------- Revoke Role
                   5270: 
                   5271: sub revokerole {
1.357     www      5272:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5273:     my $now=time;
1.357     www      5274:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5275: }
                   5276: 
                   5277: # ---------------------------------------------------------- Revoke Custom Role
                   5278: 
                   5279: sub revokecustomrole {
1.357     www      5280:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5281:     my $now=time;
1.357     www      5282:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5283:            $deleteflag);
1.17      www      5284: }
                   5285: 
1.533     banghart 5286: # ------------------------------------------------------------ Disk usage
1.535     albertel 5287: sub diskusage {
1.533     banghart 5288:     my ($udom,$uname,$directoryRoot)=@_;
                   5289:     $directoryRoot =~ s/\/$//;
1.535     albertel 5290:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5291:     return $listing;
1.512     banghart 5292: }
                   5293: 
1.566     banghart 5294: sub is_locked {
                   5295:     my ($file_name, $domain, $user) = @_;
                   5296:     my @check;
                   5297:     my $is_locked;
                   5298:     push @check, $file_name;
1.613     albertel 5299:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5300: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5301:     my ($tmp)=keys(%locked);
                   5302:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5303:     
1.566     banghart 5304:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5305:         $is_locked = 'false';
                   5306:         foreach my $entry (@{$locked{$file_name}}) {
                   5307:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5308:                $is_locked = 'true';
                   5309:                last;
1.745     raeburn  5310:            }
                   5311:        }
1.566     banghart 5312:     } else {
                   5313:         $is_locked = 'false';
                   5314:     }
                   5315: }
                   5316: 
1.759     albertel 5317: sub declutter_portfile {
                   5318:     my ($file) = @_;
1.833     albertel 5319:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5320:     return $file;
                   5321: }
                   5322: 
1.559     banghart 5323: # ------------------------------------------------------------- Mark as Read Only
                   5324: 
                   5325: sub mark_as_readonly {
                   5326:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5327:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5328:     my ($tmp)=keys(%current_permissions);
                   5329:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5330:     foreach my $file (@{$files}) {
1.759     albertel 5331: 	$file = &declutter_portfile($file);
1.561     banghart 5332:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5333:     }
1.613     albertel 5334:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5335:     return;
                   5336: }
                   5337: 
1.572     banghart 5338: # ------------------------------------------------------------Save Selected Files
                   5339: 
                   5340: sub save_selected_files {
                   5341:     my ($user, $path, @files) = @_;
                   5342:     my $filename = $user."savedfiles";
1.573     banghart 5343:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5344:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5345:     foreach my $file (@files) {
1.620     albertel 5346:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5347:     }
                   5348:     foreach my $file (@other_files) {
1.574     banghart 5349:         print (OUT $file."\n");
1.572     banghart 5350:     }
1.574     banghart 5351:     close (OUT);
1.572     banghart 5352:     return 'ok';
                   5353: }
                   5354: 
1.574     banghart 5355: sub clear_selected_files {
                   5356:     my ($user) = @_;
                   5357:     my $filename = $user."savedfiles";
                   5358:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5359:     print (OUT undef);
                   5360:     close (OUT);
                   5361:     return ("ok");    
                   5362: }
                   5363: 
1.572     banghart 5364: sub files_in_path {
                   5365:     my ($user, $path) = @_;
                   5366:     my $filename = $user."savedfiles";
                   5367:     my %return_files;
1.574     banghart 5368:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5369:     while (my $line_in = <IN>) {
1.574     banghart 5370:         chomp ($line_in);
                   5371:         my @paths_and_file = split (m!/!, $line_in);
                   5372:         my $file_part = pop (@paths_and_file);
                   5373:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5374:         $path_part.='/';
                   5375:         my $path_and_file = $path_part.$file_part;
                   5376:         if ($path_part eq $path) {
                   5377:             $return_files{$file_part}= 'selected';
                   5378:         }
                   5379:     }
1.574     banghart 5380:     close (IN);
                   5381:     return (\%return_files);
1.572     banghart 5382: }
                   5383: 
                   5384: # called in portfolio select mode, to show files selected NOT in current directory
                   5385: sub files_not_in_path {
                   5386:     my ($user, $path) = @_;
                   5387:     my $filename = $user."savedfiles";
                   5388:     my @return_files;
                   5389:     my $path_part;
1.800     albertel 5390:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5391:     while (my $line = <IN>) {
1.572     banghart 5392:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5393:         my @paths_and_file = split(m|/|, $line);
                   5394:         my $file_part = pop(@paths_and_file);
                   5395:         chomp($file_part);
                   5396:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5397:         $path_part .= '/';
                   5398:         my $path_and_file = $path_part.$file_part;
                   5399:         if ($path_part ne $path) {
1.800     albertel 5400:             push(@return_files, ($path_and_file));
1.572     banghart 5401:         }
                   5402:     }
1.800     albertel 5403:     close(OUT);
1.574     banghart 5404:     return (@return_files);
1.572     banghart 5405: }
                   5406: 
1.745     raeburn  5407: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5408: 
1.745     raeburn  5409: sub get_portfile_permissions {
                   5410:     my ($domain,$user) = @_;
1.613     albertel 5411:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5412:     my ($tmp)=keys(%current_permissions);
                   5413:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5414:     return \%current_permissions;
                   5415: }
                   5416: 
                   5417: #---------------------------------------------Get portfolio file access controls
                   5418: 
1.749     raeburn  5419: sub get_access_controls {
1.745     raeburn  5420:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5421:     my %access;
                   5422:     my $real_file = $file;
                   5423:     $file =~ s/\.meta$//;
1.745     raeburn  5424:     if (defined($file)) {
1.749     raeburn  5425:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5426:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5427:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5428:             }
                   5429:         }
1.745     raeburn  5430:     } else {
1.749     raeburn  5431:         foreach my $key (keys(%{$current_permissions})) {
                   5432:             if ($key =~ /\0accesscontrol$/) {
                   5433:                 if (defined($group)) {
                   5434:                     if ($key !~ m-^\Q$group\E/-) {
                   5435:                         next;
                   5436:                     }
                   5437:                 }
                   5438:                 my ($fullpath) = split(/\0/,$key);
                   5439:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5440:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5441:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5442:                     }
                   5443:                 }
                   5444:             }
                   5445:         }
                   5446:     }
                   5447:     return %access;
                   5448: }
                   5449: 
                   5450: sub modify_access_controls {
                   5451:     my ($file_name,$changes,$domain,$user)=@_;
                   5452:     my ($outcome,$deloutcome);
                   5453:     my %store_permissions;
                   5454:     my %new_values;
                   5455:     my %new_control;
                   5456:     my %translation;
                   5457:     my @deletions = ();
                   5458:     my $now = time;
                   5459:     if (exists($$changes{'activate'})) {
                   5460:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5461:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5462:             my $numnew = scalar(@newitems);
                   5463:             for (my $i=0; $i<$numnew; $i++) {
                   5464:                 my $newkey = $newitems[$i];
                   5465:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5466:                 if ($newkey =~ /^\d+:/) { 
                   5467:                     $newkey =~ s/^(\d+)/$newid/;
                   5468:                     $translation{$1} = $newid;
                   5469:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5470:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5471:                     $translation{$1} = $newid;
                   5472:                 }
1.749     raeburn  5473:                 $new_values{$file_name."\0".$newkey} = 
                   5474:                                           $$changes{'activate'}{$newitems[$i]};
                   5475:                 $new_control{$newkey} = $now;
                   5476:             }
                   5477:         }
                   5478:     }
                   5479:     my %todelete;
                   5480:     my %changed_items;
                   5481:     foreach my $action ('delete','update') {
                   5482:         if (exists($$changes{$action})) {
                   5483:             if (ref($$changes{$action}) eq 'HASH') {
                   5484:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5485:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5486:                     if ($action eq 'delete') { 
                   5487:                         $todelete{$itemnum} = 1;
                   5488:                     } else {
                   5489:                         $changed_items{$itemnum} = $key;
                   5490:                     }
                   5491:                 }
1.745     raeburn  5492:             }
                   5493:         }
1.749     raeburn  5494:     }
                   5495:     # get lock on access controls for file.
                   5496:     my $lockhash = {
                   5497:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5498:                                                        ':'.$env{'user.domain'},
                   5499:                    }; 
                   5500:     my $tries = 0;
                   5501:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5502:    
                   5503:     while (($gotlock ne 'ok') && $tries <3) {
                   5504:         $tries ++;
                   5505:         sleep 1;
                   5506:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5507:     }
                   5508:     if ($gotlock eq 'ok') {
                   5509:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5510:         my ($tmp)=keys(%curr_permissions);
                   5511:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5512:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5513:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5514:             if (ref($curr_controls) eq 'HASH') {
                   5515:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5516:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5517:                     if (defined($todelete{$itemnum})) {
                   5518:                         push(@deletions,$file_name."\0".$control_item);
                   5519:                     } else {
                   5520:                         if (defined($changed_items{$itemnum})) {
                   5521:                             $new_control{$changed_items{$itemnum}} = $now;
                   5522:                             push(@deletions,$file_name."\0".$control_item);
                   5523:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5524:                         } else {
                   5525:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5526:                         }
                   5527:                     }
1.745     raeburn  5528:                 }
                   5529:             }
                   5530:         }
1.749     raeburn  5531:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5532:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5533:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5534:         #  remove lock
                   5535:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5536:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5537:         my ($file,$group);
                   5538:         if (&is_course($domain,$user)) {
                   5539:             ($group,$file) = split(/\//,$file_name,2);
                   5540:         } else {
                   5541:             $file = $file_name;
                   5542:         }
                   5543:         my $sqlresult =
                   5544:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5545:                                     $group);
1.749     raeburn  5546:     } else {
                   5547:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5548:     }
1.749     raeburn  5549:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5550: }
                   5551: 
1.827     raeburn  5552: sub make_public_indefinitely {
                   5553:     my ($requrl) = @_;
                   5554:     my $now = time;
                   5555:     my $action = 'activate';
                   5556:     my $aclnum = 0;
                   5557:     if (&is_portfolio_url($requrl)) {
                   5558:         my (undef,$udom,$unum,$file_name,$group) =
                   5559:             &parse_portfolio_url($requrl);
                   5560:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5561:         my %access_controls = &get_access_controls($current_perms,
                   5562:                                                    $group,$file_name);
                   5563:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5564:             my ($num,$scope,$end,$start) = 
                   5565:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5566:             if ($scope eq 'public') {
                   5567:                 if ($start <= $now && $end == 0) {
                   5568:                     $action = 'none';
                   5569:                 } else {
                   5570:                     $action = 'update';
                   5571:                     $aclnum = $num;
                   5572:                 }
                   5573:                 last;
                   5574:             }
                   5575:         }
                   5576:         if ($action eq 'none') {
                   5577:              return 'ok';
                   5578:         } else {
                   5579:             my %changes;
                   5580:             my $newend = 0;
                   5581:             my $newstart = $now;
                   5582:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5583:             $changes{$action}{$newkey} = {
                   5584:                 type => 'public',
                   5585:                 time => {
                   5586:                     start => $newstart,
                   5587:                     end   => $newend,
                   5588:                 },
                   5589:             };
                   5590:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5591:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5592:             return $outcome;
                   5593:         }
                   5594:     } else {
                   5595:         return 'invalid';
                   5596:     }
                   5597: }
                   5598: 
1.745     raeburn  5599: #------------------------------------------------------Get Marked as Read Only
                   5600: 
                   5601: sub get_marked_as_readonly {
                   5602:     my ($domain,$user,$what,$group) = @_;
                   5603:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5604:     my @readonly_files;
1.629     banghart 5605:     my $cmp1=$what;
                   5606:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5607:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5608:         if (defined($group)) {
                   5609:             if ($file_name !~ m-^\Q$group\E/-) {
                   5610:                 next;
                   5611:             }
                   5612:         }
1.561     banghart 5613:         if (ref($value) eq "ARRAY"){
                   5614:             foreach my $stored_what (@{$value}) {
1.629     banghart 5615:                 my $cmp2=$stored_what;
1.759     albertel 5616:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5617:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5618:                 }
1.629     banghart 5619:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5620:                     push(@readonly_files, $file_name);
1.745     raeburn  5621:                     last;
1.563     banghart 5622:                 } elsif (!defined($what)) {
                   5623:                     push(@readonly_files, $file_name);
1.745     raeburn  5624:                     last;
1.561     banghart 5625:                 }
                   5626:             }
1.745     raeburn  5627:         }
1.561     banghart 5628:     }
                   5629:     return @readonly_files;
                   5630: }
1.577     banghart 5631: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5632: 
1.577     banghart 5633: sub get_marked_as_readonly_hash {
1.745     raeburn  5634:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5635:     my %readonly_files;
1.745     raeburn  5636:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5637:         if (defined($group)) {
                   5638:             if ($file_name !~ m-^\Q$group\E/-) {
                   5639:                 next;
                   5640:             }
                   5641:         }
1.577     banghart 5642:         if (ref($value) eq "ARRAY"){
                   5643:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5644:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5645:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5646:                         if ($lock_descriptor eq 'graded') {
                   5647:                             $readonly_files{$file_name} = 'graded';
                   5648:                         } elsif ($lock_descriptor eq 'handback') {
                   5649:                             $readonly_files{$file_name} = 'handback';
                   5650:                         } else {
                   5651:                             if (!exists($readonly_files{$file_name})) {
                   5652:                                 $readonly_files{$file_name} = 'locked';
                   5653:                             }
                   5654:                         }
1.745     raeburn  5655:                     }
1.750     banghart 5656:                 } 
1.577     banghart 5657:             }
                   5658:         } 
                   5659:     }
                   5660:     return %readonly_files;
                   5661: }
1.559     banghart 5662: # ------------------------------------------------------------ Unmark as Read Only
                   5663: 
                   5664: sub unmark_as_readonly {
1.629     banghart 5665:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5666:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5667:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5668:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5669:     my $symb_crs = $what;
                   5670:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5671:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5672:     my ($tmp)=keys(%current_permissions);
                   5673:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5674:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5675:     foreach my $file (@readonly_files) {
1.759     albertel 5676: 	my $clean_file = &declutter_portfile($file);
                   5677: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5678: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5679:         my @new_locks;
                   5680:         my @del_keys;
                   5681:         if (ref($current_locks) eq "ARRAY"){
                   5682:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5683:                 my $compare=$locker;
1.749     raeburn  5684:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5685:                     $compare=join('',@{$locker});
1.746     raeburn  5686:                     if ($compare ne $symb_crs) {
                   5687:                         push(@new_locks, $locker);
                   5688:                     }
1.563     banghart 5689:                 }
                   5690:             }
1.650     albertel 5691:             if (scalar(@new_locks) > 0) {
1.563     banghart 5692:                 $current_permissions{$file} = \@new_locks;
                   5693:             } else {
                   5694:                 push(@del_keys, $file);
1.613     albertel 5695:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5696:                 delete($current_permissions{$file});
1.563     banghart 5697:             }
                   5698:         }
1.561     banghart 5699:     }
1.613     albertel 5700:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5701:     return;
                   5702: }
1.512     banghart 5703: 
1.17      www      5704: # ------------------------------------------------------------ Directory lister
                   5705: 
                   5706: sub dirlist {
1.253     stredwic 5707:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5708: 
1.18      www      5709:     $uri=~s/^\///;
                   5710:     $uri=~s/\/$//;
1.253     stredwic 5711:     my ($udom, $uname);
                   5712:     (undef,$udom,$uname)=split(/\//,$uri);
                   5713:     if(defined($userdomain)) {
                   5714:         $udom = $userdomain;
                   5715:     }
                   5716:     if(defined($username)) {
                   5717:         $uname = $username;
                   5718:     }
                   5719: 
                   5720:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5721:     if(defined($alternateDirectoryRoot)) {
                   5722:         $dirRoot = $alternateDirectoryRoot;
                   5723:         $dirRoot =~ s/\/$//;
1.751     banghart 5724:     }
1.253     stredwic 5725: 
                   5726:     if($udom) {
                   5727:         if($uname) {
1.800     albertel 5728:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5729: 				 &homeserver($uname,$udom));
1.605     matthew  5730:             my @listing_results;
                   5731:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5732:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5733: 				  &homeserver($uname,$udom));
1.605     matthew  5734:                 @listing_results = split(/:/,$listing);
                   5735:             } else {
                   5736:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5737:             }
                   5738:             return @listing_results;
1.253     stredwic 5739:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5740:             my %allusers;
1.841     albertel 5741: 	    my %servers = &get_servers($udom,'library');
                   5742: 	    foreach my $tryserver (keys(%servers)) {
                   5743: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5744: 				     $udom, $tryserver);
                   5745: 		my @listing_results;
                   5746: 		if ($listing eq 'unknown_cmd') {
                   5747: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5748: 				      $udom, $tryserver);
                   5749: 		    @listing_results = split(/:/,$listing);
                   5750: 		} else {
                   5751: 		    @listing_results =
                   5752: 			map { &unescape($_); } split(/:/,$listing);
                   5753: 		}
                   5754: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5755: 		    $listing_results[0] ne 'empty'       &&
                   5756: 		    $listing_results[0] ne 'con_lost') {
                   5757: 		    foreach my $line (@listing_results) {
                   5758: 			my ($entry) = split(/&/,$line,2);
                   5759: 			$allusers{$entry} = 1;
                   5760: 		    }
                   5761: 		}
1.253     stredwic 5762:             }
                   5763:             my $alluserstr='';
1.800     albertel 5764:             foreach my $user (sort(keys(%allusers))) {
                   5765:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5766:             }
                   5767:             $alluserstr=~s/:$//;
                   5768:             return split(/:/,$alluserstr);
                   5769:         } else {
1.800     albertel 5770:             return ('missing user name');
1.253     stredwic 5771:         }
                   5772:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5773:         my @all_domains = sort(&all_domains());
                   5774:          foreach my $domain (@all_domains) {
                   5775:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5776:          }
                   5777:          return @all_domains;
                   5778:      } else {
1.800     albertel 5779:         return ('missing domain');
1.275     stredwic 5780:     }
                   5781: }
                   5782: 
                   5783: # --------------------------------------------- GetFileTimestamp
                   5784: # This function utilizes dirlist and returns the date stamp for
                   5785: # when it was last modified.  It will also return an error of -1
                   5786: # if an error occurs
                   5787: 
1.410     matthew  5788: ##
                   5789: ## FIXME: This subroutine assumes its caller knows something about the
                   5790: ## directory structure of the home server for the student ($root).
                   5791: ## Not a good assumption to make.  Since this is for looking up files
                   5792: ## in user directories, the full path should be constructed by lond, not
                   5793: ## whatever machine we request data from.
                   5794: ##
1.275     stredwic 5795: sub GetFileTimestamp {
                   5796:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5797:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5798:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5799:     my $subdir=$studentName.'__';
                   5800:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5801:     my $proname="$studentDomain/$subdir/$studentName";
                   5802:     $proname .= '/'.$filename;
1.375     matthew  5803:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5804:                                               $studentName, $root);
1.275     stredwic 5805:     my @stats = split('&', $fileStat);
                   5806:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5807:         # @stats contains first the filename, then the stat output
                   5808:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5809:     } else {
                   5810:         return -1;
1.253     stredwic 5811:     }
1.26      www      5812: }
                   5813: 
1.712     albertel 5814: sub stat_file {
                   5815:     my ($uri) = @_;
1.787     albertel 5816:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5817: 
1.712     albertel 5818:     my ($udom,$uname,$file,$dir);
                   5819:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5820: 	($udom,$uname,$file) =
1.811     albertel 5821: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5822: 	$file = 'userfiles/'.$file;
1.740     www      5823: 	$dir = &propath($udom,$uname);
1.712     albertel 5824:     }
                   5825:     if ($uri =~ m-^/res/-) {
                   5826: 	($udom,$uname) = 
1.807     albertel 5827: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5828: 	$file = $uri;
                   5829:     }
                   5830: 
                   5831:     if (!$udom || !$uname || !$file) {
                   5832: 	# unable to handle the uri
                   5833: 	return ();
                   5834:     }
                   5835: 
                   5836:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5837:     my @stats = split('&', $result);
1.721     banghart 5838:     
1.712     albertel 5839:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5840: 	shift(@stats); #filename is first
                   5841: 	return @stats;
                   5842:     }
                   5843:     return ();
                   5844: }
                   5845: 
1.26      www      5846: # -------------------------------------------------------- Value of a Condition
                   5847: 
1.713     albertel 5848: # gets the value of a specific preevaluated condition
                   5849: #    stored in the string  $env{user.state.<cid>}
                   5850: # or looks up a condition reference in the bighash and if if hasn't
                   5851: # already been evaluated recurses into docondval to get the value of
                   5852: # the condition, then memoizing it to 
                   5853: #   $env{user.state.<cid>.<condition>}
1.40      www      5854: sub directcondval {
                   5855:     my $number=shift;
1.620     albertel 5856:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5857: 	&Apache::lonuserstate::evalstate();
                   5858:     }
1.713     albertel 5859:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5860: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5861:     } elsif ($number =~ /^_/) {
                   5862: 	my $sub_condition;
                   5863: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5864: 		&GDBM_READER(),0640)) {
                   5865: 	    $sub_condition=$bighash{'conditions'.$number};
                   5866: 	    untie(%bighash);
                   5867: 	}
                   5868: 	my $value = &docondval($sub_condition);
                   5869: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5870: 	return $value;
                   5871:     }
1.620     albertel 5872:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5873:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5874:     } else {
                   5875:        return 2;
                   5876:     }
                   5877: }
                   5878: 
1.713     albertel 5879: # get the collection of conditions for this resource
1.26      www      5880: sub condval {
                   5881:     my $condidx=shift;
1.54      www      5882:     my $allpathcond='';
1.713     albertel 5883:     foreach my $cond (split(/\|/,$condidx)) {
                   5884: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5885: 	    $allpathcond.=
                   5886: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5887: 	}
1.191     harris41 5888:     }
1.54      www      5889:     $allpathcond=~s/\|$//;
1.713     albertel 5890:     return &docondval($allpathcond);
                   5891: }
                   5892: 
                   5893: #evaluates an expression of conditions
                   5894: sub docondval {
                   5895:     my ($allpathcond) = @_;
                   5896:     my $result=0;
                   5897:     if ($env{'request.course.id'}
                   5898: 	&& defined($allpathcond)) {
                   5899: 	my $operand='|';
                   5900: 	my @stack;
                   5901: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5902: 	    if ($chunk eq '(') {
                   5903: 		push @stack,($operand,$result);
                   5904: 	    } elsif ($chunk eq ')') {
                   5905: 		my $before=pop @stack;
                   5906: 		if (pop @stack eq '&') {
                   5907: 		    $result=$result>$before?$before:$result;
                   5908: 		} else {
                   5909: 		    $result=$result>$before?$result:$before;
                   5910: 		}
                   5911: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5912: 		$operand=$chunk;
                   5913: 	    } else {
                   5914: 		my $new=directcondval($chunk);
                   5915: 		if ($operand eq '&') {
                   5916: 		    $result=$result>$new?$new:$result;
                   5917: 		} else {
                   5918: 		    $result=$result>$new?$result:$new;
                   5919: 		}
                   5920: 	    }
                   5921: 	}
1.26      www      5922:     }
                   5923:     return $result;
1.421     albertel 5924: }
                   5925: 
                   5926: # ---------------------------------------------------- Devalidate courseresdata
                   5927: 
                   5928: sub devalidatecourseresdata {
                   5929:     my ($coursenum,$coursedomain)=@_;
                   5930:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5931:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5932: }
                   5933: 
1.763     www      5934: 
1.200     www      5935: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     5936: #
                   5937: #  Parameters:
                   5938: #      $coursenum    - Number of the course.
                   5939: #      $coursedomain - Domain at which the course was created.
                   5940: #  Returns:
                   5941: #     A hash of the course parameters along (I think) with timestamps
                   5942: #     and version info.
1.877     foxr     5943: 
1.624     albertel 5944: sub get_courseresdata {
                   5945:     my ($coursenum,$coursedomain)=@_;
1.200     www      5946:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5947:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5948:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5949:     my %dumpreply;
1.417     albertel 5950:     unless (defined($cached)) {
1.624     albertel 5951: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5952: 	$result=\%dumpreply;
1.251     albertel 5953: 	my ($tmp) = keys(%dumpreply);
                   5954: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5955: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5956: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5957: 	    return $tmp;
1.416     albertel 5958: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5959: 	    $result=undef;
1.599     albertel 5960: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5961: 	}
                   5962:     }
1.624     albertel 5963:     return $result;
                   5964: }
                   5965: 
1.633     albertel 5966: sub devalidateuserresdata {
                   5967:     my ($uname,$udom)=@_;
                   5968:     my $hashid="$udom:$uname";
                   5969:     &devalidate_cache_new('userres',$hashid);
                   5970: }
                   5971: 
1.624     albertel 5972: sub get_userresdata {
                   5973:     my ($uname,$udom)=@_;
                   5974:     #most student don\'t have any data set, check if there is some data
                   5975:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5976: 
                   5977:     my $hashid="$udom:$uname";
                   5978:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5979:     if (!defined($cached)) {
                   5980: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5981: 	$result=\%resourcedata;
                   5982: 	&do_cache_new('userres',$hashid,$result,600);
                   5983:     }
                   5984:     my ($tmp)=keys(%$result);
                   5985:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5986: 	return $result;
                   5987:     }
                   5988:     #error 2 occurs when the .db doesn't exist
                   5989:     if ($tmp!~/error: 2 /) {
1.672     albertel 5990: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5991: 		 " Trying to get resource data for ".
                   5992: 		 $uname." at ".$udom.": ".
                   5993: 		 $tmp."</font>");
                   5994:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5995: 	#&EXT_cache_set($udom,$uname);
                   5996: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5997: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5998:     }
                   5999:     return $tmp;
                   6000: }
1.879     foxr     6001: #----------------------------------------------- resdata - return resource data
                   6002: #  Purpose:
                   6003: #    Return resource data for either users or for a course.
                   6004: #  Parameters:
                   6005: #     $name      - Course/user name.
                   6006: #     $domain    - Name of the domain the user/course is registered on.
                   6007: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6008: #     @which     - Array of names of resources desired.
                   6009: #  Returns:
                   6010: #     The value of the first reasource in @which that is found in the
                   6011: #     resource hash.
                   6012: #  Exceptional Conditions:
                   6013: #     If the $type passed in is not valid (not the string 'course' or 
                   6014: #     'user', an undefined  reference is returned.
                   6015: #     If none of the resources are found, an undef is returned
1.624     albertel 6016: sub resdata {
                   6017:     my ($name,$domain,$type,@which)=@_;
                   6018:     my $result;
                   6019:     if ($type eq 'course') {
                   6020: 	$result=&get_courseresdata($name,$domain);
                   6021:     } elsif ($type eq 'user') {
                   6022: 	$result=&get_userresdata($name,$domain);
                   6023:     }
                   6024:     if (!ref($result)) { return $result; }    
1.251     albertel 6025:     foreach my $item (@which) {
1.417     albertel 6026: 	if (defined($result->{$item})) {
                   6027: 	    return $result->{$item};
1.251     albertel 6028: 	}
1.250     albertel 6029:     }
1.291     albertel 6030:     return undef;
1.200     www      6031: }
                   6032: 
1.379     matthew  6033: #
                   6034: # EXT resource caching routines
                   6035: #
                   6036: 
                   6037: sub clear_EXT_cache_status {
1.383     albertel 6038:     &delenv('cache.EXT.');
1.379     matthew  6039: }
                   6040: 
                   6041: sub EXT_cache_status {
                   6042:     my ($target_domain,$target_user) = @_;
1.383     albertel 6043:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6044:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6045:         # We know already the user has no data
                   6046:         return 1;
                   6047:     } else {
                   6048:         return 0;
                   6049:     }
                   6050: }
                   6051: 
                   6052: sub EXT_cache_set {
                   6053:     my ($target_domain,$target_user) = @_;
1.383     albertel 6054:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6055:     #&appenv($cachename => time);
1.379     matthew  6056: }
                   6057: 
1.28      www      6058: # --------------------------------------------------------- Value of a Variable
1.58      www      6059: sub EXT {
1.715     albertel 6060: 
1.395     albertel 6061:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6062:     unless ($varname) { return ''; }
1.218     albertel 6063:     #get real user name/domain, courseid and symb
                   6064:     my $courseid;
1.359     albertel 6065:     my $publicuser;
1.427     www      6066:     if ($symbparm) {
                   6067: 	$symbparm=&get_symb_from_alias($symbparm);
                   6068:     }
1.218     albertel 6069:     if (!($uname && $udom)) {
1.790     albertel 6070:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6071:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6072:     } else {
1.620     albertel 6073: 	$courseid=$env{'request.course.id'};
1.218     albertel 6074:     }
1.48      www      6075:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6076:     my $rest;
1.320     albertel 6077:     if (defined($therest[0])) {
1.48      www      6078:        $rest=join('.',@therest);
                   6079:     } else {
                   6080:        $rest='';
                   6081:     }
1.320     albertel 6082: 
1.57      www      6083:     my $qualifierrest=$qualifier;
                   6084:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6085:     my $spacequalifierrest=$space;
                   6086:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6087:     if ($realm eq 'user') {
1.48      www      6088: # --------------------------------------------------------------- user.resource
                   6089: 	if ($space eq 'resource') {
1.651     albertel 6090: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6091: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6092: 		 &&
1.744     albertel 6093: 		 ($symbparm eq &symbread()) ) {	
                   6094: 		# if we are in the middle of processing the resource the
                   6095: 		# get the value we are planning on committing
                   6096:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6097:                     return $Apache::lonhomework::results{$qualifierrest};
                   6098:                 } else {
                   6099:                     return $Apache::lonhomework::history{$qualifierrest};
                   6100:                 }
1.335     albertel 6101: 	    } else {
1.359     albertel 6102: 		my %restored;
1.620     albertel 6103: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6104: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6105: 		} else {
                   6106: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6107: 		}
1.335     albertel 6108: 		return $restored{$qualifierrest};
                   6109: 	    }
1.48      www      6110: # ----------------------------------------------------------------- user.access
                   6111:         } elsif ($space eq 'access') {
1.218     albertel 6112: 	    # FIXME - not supporting calls for a specific user
1.48      www      6113:             return &allowed($qualifier,$rest);
                   6114: # ------------------------------------------ user.preferences, user.environment
                   6115:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6116: 	    if (($uname eq $env{'user.name'}) &&
                   6117: 		($udom eq $env{'user.domain'})) {
                   6118: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6119: 	    } else {
1.359     albertel 6120: 		my %returnhash;
                   6121: 		if (!$publicuser) {
                   6122: 		    %returnhash=&userenvironment($udom,$uname,
                   6123: 						 $qualifierrest);
                   6124: 		}
1.218     albertel 6125: 		return $returnhash{$qualifierrest};
                   6126: 	    }
1.48      www      6127: # ----------------------------------------------------------------- user.course
                   6128:         } elsif ($space eq 'course') {
1.218     albertel 6129: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6130:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6131: # ------------------------------------------------------------------- user.role
                   6132:         } elsif ($space eq 'role') {
1.218     albertel 6133: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6134:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6135:             if ($qualifier eq 'value') {
                   6136: 		return $role;
                   6137:             } elsif ($qualifier eq 'extent') {
                   6138:                 return $where;
                   6139:             }
                   6140: # ----------------------------------------------------------------- user.domain
                   6141:         } elsif ($space eq 'domain') {
1.218     albertel 6142:             return $udom;
1.48      www      6143: # ------------------------------------------------------------------- user.name
                   6144:         } elsif ($space eq 'name') {
1.218     albertel 6145:             return $uname;
1.48      www      6146: # ---------------------------------------------------- Any other user namespace
1.29      www      6147:         } else {
1.359     albertel 6148: 	    my %reply;
                   6149: 	    if (!$publicuser) {
                   6150: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6151: 	    }
                   6152: 	    return $reply{$qualifierrest};
1.48      www      6153:         }
1.236     www      6154:     } elsif ($realm eq 'query') {
                   6155: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6156:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6157: 						[$spacequalifierrest]);
1.620     albertel 6158: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6159:    } elsif ($realm eq 'request') {
1.48      www      6160: # ------------------------------------------------------------- request.browser
                   6161:         if ($space eq 'browser') {
1.430     www      6162: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6163: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6164: 		    return 1;
                   6165: 		} else {
                   6166: 		    return 0;
                   6167: 		}
                   6168: 	    } else {
1.620     albertel 6169: 		return $env{'browser.'.$qualifier};
1.430     www      6170: 	    }
1.57      www      6171: # ------------------------------------------------------------ request.filename
                   6172:         } else {
1.620     albertel 6173:             return $env{'request.'.$spacequalifierrest};
1.29      www      6174:         }
1.28      www      6175:     } elsif ($realm eq 'course') {
1.48      www      6176: # ---------------------------------------------------------- course.description
1.620     albertel 6177:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6178:     } elsif ($realm eq 'resource') {
1.165     www      6179: 
1.620     albertel 6180: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6181: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6182: 	}
1.693     albertel 6183: 
                   6184: 	if ($space eq 'title') {
                   6185: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6186: 	    return &gettitle($symbparm);
                   6187: 	}
                   6188: 	
                   6189: 	if ($space eq 'map') {
                   6190: 	    my ($map) = &decode_symb($symbparm);
                   6191: 	    return &symbread($map);
                   6192: 	}
                   6193: 
                   6194: 	my ($section, $group, @groups);
1.593     albertel 6195: 	my ($courselevelm,$courselevel);
1.539     albertel 6196: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6197: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6198: 
1.218     albertel 6199: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6200: 
1.60      www      6201: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6202: 	    my $symbp=$symbparm;
1.735     albertel 6203: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6204: 
                   6205: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6206: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6207: 
1.620     albertel 6208: 	    if (($env{'user.name'} eq $uname) &&
                   6209: 		($env{'user.domain'} eq $udom)) {
                   6210: 		$section=$env{'request.course.sec'};
1.733     raeburn  6211:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6212:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6213: 	    } else {
1.539     albertel 6214: 		if (! defined($usection)) {
1.551     albertel 6215: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6216: 		} else {
                   6217: 		    $section = $usection;
                   6218: 		}
1.733     raeburn  6219:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6220: 	    }
                   6221: 
                   6222: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6223: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6224: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6225: 
1.593     albertel 6226: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6227: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6228: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6229: 
1.60      www      6230: # ----------------------------------------------------------- first, check user
1.624     albertel 6231: 
                   6232: 	    my $userreply=&resdata($uname,$udom,'user',
                   6233: 				       ($courselevelr,$courselevelm,
                   6234: 					$courselevel));
                   6235: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6236: 
1.594     albertel 6237: # ------------------------------------------------ second, check some of course
1.684     raeburn  6238:             my $coursereply;
1.691     raeburn  6239:             if (@groups > 0) {
                   6240:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6241:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6242:                 if (defined($coursereply)) { return $coursereply; }
                   6243:             }
1.96      www      6244: 
1.684     raeburn  6245: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6246: 				     $env{'course.'.$courseid.'.domain'},
                   6247: 				     'course',
                   6248: 				     ($seclevelr,$seclevelm,$seclevel,
                   6249: 				      $courselevelr));
1.287     albertel 6250: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6251: 
1.60      www      6252: # ------------------------------------------------------ third, check map parms
1.218     albertel 6253: 	    my %parmhash=();
                   6254: 	    my $thisparm='';
                   6255: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6256: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6257: 		    &GDBM_READER(),0640)) {
1.218     albertel 6258: 		$thisparm=$parmhash{$symbparm};
                   6259: 		untie(%parmhash);
                   6260: 	    }
                   6261: 	    if ($thisparm) { return $thisparm; }
                   6262: 	}
1.594     albertel 6263: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6264: 
1.218     albertel 6265: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6266: 	my $filename;
                   6267: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6268: 	if ($symbparm) {
1.409     www      6269: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6270: 	} else {
1.620     albertel 6271: 	    $filename=$env{'request.filename'};
1.282     albertel 6272: 	}
                   6273: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6274: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6275: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6276: 	if (defined($metadata)) { return $metadata; }
1.142     www      6277: 
1.594     albertel 6278: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6279: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6280: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6281: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6282: 				     $env{'course.'.$courseid.'.domain'},
                   6283: 				     'course',
                   6284: 				     ($courselevelm,$courselevel));
1.593     albertel 6285: 	    if (defined($coursereply)) { return $coursereply; }
                   6286: 	}
1.145     www      6287: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6288: 	unless ($space eq '0') {
1.336     albertel 6289: 	    my @parts=split(/_/,$space);
                   6290: 	    my $id=pop(@parts);
                   6291: 	    my $part=join('_',@parts);
                   6292: 	    if ($part eq '') { $part='0'; }
                   6293: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6294: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6295: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6296: 	}
1.395     albertel 6297: 	if ($recurse) { return undef; }
                   6298: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6299: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6300: 
1.48      www      6301: # ---------------------------------------------------- Any other user namespace
                   6302:     } elsif ($realm eq 'environment') {
                   6303: # ----------------------------------------------------------------- environment
1.620     albertel 6304: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6305: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6306: 	} else {
1.770     albertel 6307: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6308: 		return '';
                   6309: 	    }
1.219     albertel 6310: 	    my %returnhash=&userenvironment($udom,$uname,
                   6311: 					    $spacequalifierrest);
                   6312: 	    return $returnhash{$spacequalifierrest};
                   6313: 	}
1.28      www      6314:     } elsif ($realm eq 'system') {
1.48      www      6315: # ----------------------------------------------------------------- system.time
                   6316: 	if ($space eq 'time') {
                   6317: 	    return time;
                   6318:         }
1.696     albertel 6319:     } elsif ($realm eq 'server') {
                   6320: # ----------------------------------------------------------------- system.time
                   6321: 	if ($space eq 'name') {
                   6322: 	    return $ENV{'SERVER_NAME'};
                   6323:         }
1.28      www      6324:     }
1.48      www      6325:     return '';
1.61      www      6326: }
                   6327: 
1.691     raeburn  6328: sub check_group_parms {
                   6329:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6330:     my @groupitems = ();
                   6331:     my $resultitem;
                   6332:     my @levels = ($symbparm,$mapparm,$what);
                   6333:     foreach my $group (@{$groups}) {
                   6334:         foreach my $level (@levels) {
                   6335:              my $item = $courseid.'.['.$group.'].'.$level;
                   6336:              push(@groupitems,$item);
                   6337:         }
                   6338:     }
                   6339:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6340:                             $env{'course.'.$courseid.'.domain'},
                   6341:                                      'course',@groupitems);
                   6342:     return $coursereply;
                   6343: }
                   6344: 
                   6345: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6346:     my ($courseid,@groups) = @_;
                   6347:     @groups = sort(@groups);
1.691     raeburn  6348:     return @groups;
                   6349: }
                   6350: 
1.395     albertel 6351: sub packages_tab_default {
                   6352:     my ($uri,$varname)=@_;
                   6353:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6354: 
                   6355:     my (@extension,@specifics,$do_default);
                   6356:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6357: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6358: 	if ($pack_type eq 'default') {
                   6359: 	    $do_default=1;
                   6360: 	} elsif ($pack_type eq 'extension') {
                   6361: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6362: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6363: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6364: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6365: 	}
                   6366:     }
                   6367:     # first look for a package that matches the requested part id
                   6368:     foreach my $package (@specifics) {
                   6369: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6370: 	next if ($pack_part ne $part);
                   6371: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6372: 	    return $packagetab{"$pack_type&$name&default"};
                   6373: 	}
                   6374:     }
                   6375:     # look for any possible matching non extension_ package
                   6376:     foreach my $package (@specifics) {
                   6377: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6378: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6379: 	    return $packagetab{"$pack_type&$name&default"};
                   6380: 	}
1.585     albertel 6381: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6382: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6383: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6384: 	}
                   6385:     }
1.738     albertel 6386:     # look for any posible extension_ match
                   6387:     foreach my $package (@extension) {
                   6388: 	my ($package,$pack_type)=@{$package};
                   6389: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6390: 	    return $packagetab{"$pack_type&$name&default"};
                   6391: 	}
                   6392: 	if (defined($packagetab{$package."&$name&default"})) {
                   6393: 	    return $packagetab{$package."&$name&default"};
                   6394: 	}
                   6395:     }
                   6396:     # look for a global default setting
                   6397:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6398: 	return $packagetab{"default&$name&default"};
                   6399:     }
1.395     albertel 6400:     return undef;
                   6401: }
                   6402: 
1.334     albertel 6403: sub add_prefix_and_part {
                   6404:     my ($prefix,$part)=@_;
                   6405:     my $keyroot;
                   6406:     if (defined($prefix) && $prefix !~ /^__/) {
                   6407: 	# prefix that has a part already
                   6408: 	$keyroot=$prefix;
                   6409:     } elsif (defined($prefix)) {
                   6410: 	# prefix that is missing a part
                   6411: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6412:     } else {
                   6413: 	# no prefix at all
                   6414: 	if (defined($part)) { $keyroot='_'.$part; }
                   6415:     }
                   6416:     return $keyroot;
                   6417: }
                   6418: 
1.71      www      6419: # ---------------------------------------------------------------- Get metadata
                   6420: 
1.599     albertel 6421: my %metaentry;
1.71      www      6422: sub metadata {
1.176     www      6423:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6424:     $uri=&declutter($uri);
1.288     albertel 6425:     # if it is a non metadata possible uri return quickly
1.529     albertel 6426:     if (($uri eq '') || 
                   6427: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6428: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6429:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6430: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6431: 	return undef;
1.288     albertel 6432:     }
1.73      www      6433:     my $filename=$uri;
                   6434:     $uri=~s/\.meta$//;
1.172     www      6435: #
                   6436: # Is the metadata already cached?
1.177     www      6437: # Look at timestamp of caching
1.172     www      6438: # Everything is cached by the main uri, libraries are never directly cached
                   6439: #
1.428     albertel 6440:     if (!defined($liburi)) {
1.599     albertel 6441: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6442: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6443:     }
                   6444:     {
1.172     www      6445: #
                   6446: # Is this a recursive call for a library?
                   6447: #
1.599     albertel 6448: #	if (! exists($metacache{$uri})) {
                   6449: #	    $metacache{$uri}={};
                   6450: #	}
1.171     www      6451:         if ($liburi) {
                   6452: 	    $liburi=&declutter($liburi);
                   6453:             $filename=$liburi;
1.401     bowersj2 6454:         } else {
1.599     albertel 6455: 	    &devalidate_cache_new('meta',$uri);
                   6456: 	    undef(%metaentry);
1.401     bowersj2 6457: 	}
1.140     www      6458:         my %metathesekeys=();
1.73      www      6459:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6460: 	my $metastring;
1.768     albertel 6461: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6462: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6463: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6464: 	    $metastring=&getfile($file);
1.489     albertel 6465: 	}
1.208     albertel 6466:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6467:         my $token;
1.140     www      6468:         undef %metathesekeys;
1.71      www      6469:         while ($token=$parser->get_token) {
1.339     albertel 6470: 	    if ($token->[0] eq 'S') {
                   6471: 		if (defined($token->[2]->{'package'})) {
1.172     www      6472: #
                   6473: # This is a package - get package info
                   6474: #
1.339     albertel 6475: 		    my $package=$token->[2]->{'package'};
                   6476: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6477: 		    if (defined($token->[2]->{'id'})) { 
                   6478: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6479: 		    }
1.599     albertel 6480: 		    if ($metaentry{':packages'}) {
                   6481: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6482: 		    } else {
1.599     albertel 6483: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6484: 		    }
1.736     albertel 6485: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6486: 			my $part=$keyroot;
                   6487: 			$part=~s/^\_//;
1.736     albertel 6488: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6489: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6490: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6491: 			    # ignore package.tab specified default values
                   6492:                             # here &package_tab_default() will fetch those
                   6493: 			    if ($subp eq 'default') { next; }
1.736     albertel 6494: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6495: 			    my $unikey;
                   6496: 			    if ($pack =~ /_0$/) {
                   6497: 				$unikey='parameter_0_'.$name;
                   6498: 				$part=0;
                   6499: 			    } else {
                   6500: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6501: 			    }
1.339     albertel 6502: 			    if ($subp eq 'display') {
                   6503: 				$value.=' [Part: '.$part.']';
                   6504: 			    }
1.599     albertel 6505: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6506: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6507: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6508: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6509: 			    }
1.599     albertel 6510: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6511: 				$metaentry{':'.$unikey}=
                   6512: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6513: 			    }
1.339     albertel 6514: 			}
                   6515: 		    }
                   6516: 		} else {
1.172     www      6517: #
                   6518: # This is not a package - some other kind of start tag
1.339     albertel 6519: #
                   6520: 		    my $entry=$token->[1];
                   6521: 		    my $unikey;
                   6522: 		    if ($entry eq 'import') {
                   6523: 			$unikey='';
                   6524: 		    } else {
                   6525: 			$unikey=$entry;
                   6526: 		    }
                   6527: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6528: 
                   6529: 		    if (defined($token->[2]->{'id'})) { 
                   6530: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6531: 		    }
1.175     www      6532: 
1.339     albertel 6533: 		    if ($entry eq 'import') {
1.175     www      6534: #
                   6535: # Importing a library here
1.339     albertel 6536: #
                   6537: 			if ($depthcount<20) {
                   6538: 			    my $location=$parser->get_text('/import');
                   6539: 			    my $dir=$filename;
                   6540: 			    $dir=~s|[^/]*$||;
                   6541: 			    $location=&filelocation($dir,$location);
1.736     albertel 6542: 			    my $metadata = 
                   6543: 				&metadata($uri,'keys', $location,$unikey,
                   6544: 					  $depthcount+1);
                   6545: 			    foreach my $meta (split(',',$metadata)) {
                   6546: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6547: 				$metathesekeys{$meta}=1;
1.339     albertel 6548: 			    }
                   6549: 			}
                   6550: 		    } else { 
                   6551: 			
                   6552: 			if (defined($token->[2]->{'name'})) { 
                   6553: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6554: 			}
                   6555: 			$metathesekeys{$unikey}=1;
1.736     albertel 6556: 			foreach my $param (@{$token->[3]}) {
                   6557: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6558: 				$token->[2]->{$param};
1.339     albertel 6559: 			}
                   6560: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6561: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6562: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6563: 		 # only ws inside the tag, and not in default, so use default
                   6564: 		 # as value
1.599     albertel 6565: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6566: 			} else {
1.321     albertel 6567: 		  # either something interesting inside the tag or default
                   6568:                   # uninteresting
1.599     albertel 6569: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6570: 			}
1.172     www      6571: # end of not-a-package not-a-library import
1.339     albertel 6572: 		    }
1.172     www      6573: # end of not-a-package start tag
1.339     albertel 6574: 		}
1.172     www      6575: # the next is the end of "start tag"
1.339     albertel 6576: 	    }
                   6577: 	}
1.483     albertel 6578: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6579: 	$extension = lc($extension);
                   6580: 	if ($extension eq 'htm') { $extension='html'; }
                   6581: 
1.737     albertel 6582: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6583: 	    #no specific packages #how's our extension
                   6584: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6585: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6586: 					 \%metathesekeys);
                   6587: 	}
1.883     albertel 6588: 
                   6589: 	if (!exists($metaentry{':packages'})
                   6590: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6591: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6592: 		#no specific packages well let's get default then
                   6593: 		if ($key!~/^default&/) { next; }
1.488     albertel 6594: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6595: 					     \%metathesekeys);
                   6596: 	    }
                   6597: 	}
1.338     www      6598: # are there custom rights to evaluate
1.599     albertel 6599: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6600: 
1.338     www      6601:     #
                   6602:     # Importing a rights file here
1.339     albertel 6603:     #
                   6604: 	    unless ($depthcount) {
1.599     albertel 6605: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6606: 		my $dir=$filename;
                   6607: 		$dir=~s|[^/]*$||;
                   6608: 		$location=&filelocation($dir,$location);
1.736     albertel 6609: 		my $rights_metadata =
                   6610: 		    &metadata($uri,'keys',$location,'_rights',
                   6611: 			      $depthcount+1);
                   6612: 		foreach my $rights (split(',',$rights_metadata)) {
                   6613: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6614: 		    $metathesekeys{$rights}=1;
1.339     albertel 6615: 		}
                   6616: 	    }
                   6617: 	}
1.737     albertel 6618: 	# uniqifiy package listing
                   6619: 	my %seen;
                   6620: 	my @uniq_packages =
                   6621: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6622: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6623: 
                   6624: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6625: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6626: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6627: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6628: # this is the end of "was not already recently cached
1.71      www      6629:     }
1.599     albertel 6630:     return $metaentry{':'.$what};
1.261     albertel 6631: }
                   6632: 
1.488     albertel 6633: sub metadata_create_package_def {
1.483     albertel 6634:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6635:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6636:     if ($subp eq 'default') { next; }
                   6637:     
1.599     albertel 6638:     if (defined($metaentry{':packages'})) {
                   6639: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6640:     } else {
1.599     albertel 6641: 	$metaentry{':packages'}=$package;
1.483     albertel 6642:     }
                   6643:     my $value=$packagetab{$key};
                   6644:     my $unikey;
                   6645:     $unikey='parameter_0_'.$name;
1.599     albertel 6646:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6647:     $$metathesekeys{$unikey}=1;
1.599     albertel 6648:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6649: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6650:     }
1.599     albertel 6651:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6652: 	$metaentry{':'.$unikey}=
                   6653: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6654:     }
                   6655: }
                   6656: 
1.261     albertel 6657: sub metadata_generate_part0 {
                   6658:     my ($metadata,$metacache,$uri) = @_;
                   6659:     my %allnames;
1.737     albertel 6660:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6661: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6662: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6663: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6664: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6665: 	    $allnames{$name}=$part;
                   6666: 	  }
                   6667: 	}
                   6668:     }
                   6669:     foreach my $name (keys(%allnames)) {
                   6670:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6671:       my $key=":parameter_0_$name";
1.261     albertel 6672:       $$metacache{"$key.part"}='0';
                   6673:       $$metacache{"$key.name"}=$name;
1.428     albertel 6674:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6675: 					   $allnames{$name}.'_'.$name.
                   6676: 					   '.type'};
1.428     albertel 6677:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6678: 			     '.display'};
1.644     www      6679:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6680:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6681:       $$metacache{"$key.display"}=$olddis;
                   6682:     }
1.71      www      6683: }
                   6684: 
1.764     albertel 6685: # ------------------------------------------------------ Devalidate title cache
                   6686: 
                   6687: sub devalidate_title_cache {
                   6688:     my ($url)=@_;
                   6689:     if (!$env{'request.course.id'}) { return; }
                   6690:     my $symb=&symbread($url);
                   6691:     if (!$symb) { return; }
                   6692:     my $key=$env{'request.course.id'}."\0".$symb;
                   6693:     &devalidate_cache_new('title',$key);
                   6694: }
                   6695: 
1.301     www      6696: # ------------------------------------------------- Get the title of a resource
                   6697: 
                   6698: sub gettitle {
                   6699:     my $urlsymb=shift;
                   6700:     my $symb=&symbread($urlsymb);
1.534     albertel 6701:     if ($symb) {
1.620     albertel 6702: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6703: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6704: 	if (defined($cached)) { 
                   6705: 	    return $result;
                   6706: 	}
1.534     albertel 6707: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6708: 	my $title='';
                   6709: 	my %bighash;
1.620     albertel 6710: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6711: 		&GDBM_READER(),0640)) {
                   6712: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6713: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6714: 	    untie %bighash;
                   6715: 	}
                   6716: 	$title=~s/\&colon\;/\:/gs;
                   6717: 	if ($title) {
1.599     albertel 6718: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6719: 	}
                   6720: 	$urlsymb=$url;
                   6721:     }
                   6722:     my $title=&metadata($urlsymb,'title');
                   6723:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6724:     return $title;
1.301     www      6725: }
1.613     albertel 6726: 
1.614     albertel 6727: sub get_slot {
                   6728:     my ($which,$cnum,$cdom)=@_;
                   6729:     if (!$cnum || !$cdom) {
1.790     albertel 6730: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6731: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6732: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6733:     }
1.703     albertel 6734:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6735:     my %slotinfo;
                   6736:     if (exists($remembered{$key})) {
                   6737: 	$slotinfo{$which} = $remembered{$key};
                   6738:     } else {
                   6739: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6740: 	&Apache::lonhomework::showhash(%slotinfo);
                   6741: 	my ($tmp)=keys(%slotinfo);
                   6742: 	if ($tmp=~/^error:/) { return (); }
                   6743: 	$remembered{$key} = $slotinfo{$which};
                   6744:     }
1.616     albertel 6745:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6746: 	return %{$slotinfo{$which}};
                   6747:     }
                   6748:     return $slotinfo{$which};
1.614     albertel 6749: }
1.31      www      6750: # ------------------------------------------------- Update symbolic store links
                   6751: 
                   6752: sub symblist {
                   6753:     my ($mapname,%newhash)=@_;
1.438     www      6754:     $mapname=&deversion(&declutter($mapname));
1.31      www      6755:     my %hash;
1.620     albertel 6756:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6757:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6758:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6759: 	    foreach my $url (keys %newhash) {
                   6760: 		next if ($url eq 'last_known'
                   6761: 			 && $env{'form.no_update_last_known'});
                   6762: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6763: 						    $newhash{$url}->[1],
                   6764: 						    $newhash{$url}->[0]);
1.191     harris41 6765:             }
1.31      www      6766:             if (untie(%hash)) {
                   6767: 		return 'ok';
                   6768:             }
                   6769:         }
                   6770:     }
                   6771:     return 'error';
1.212     www      6772: }
                   6773: 
                   6774: # --------------------------------------------------------------- Verify a symb
                   6775: 
                   6776: sub symbverify {
1.510     www      6777:     my ($symb,$thisurl)=@_;
                   6778:     my $thisfn=$thisurl;
1.439     www      6779:     $thisfn=&declutter($thisfn);
1.215     www      6780: # direct jump to resource in page or to a sequence - will construct own symbs
                   6781:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6782: # check URL part
1.409     www      6783:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6784: 
1.431     www      6785:     unless ($url eq $thisfn) { return 0; }
1.213     www      6786: 
1.216     www      6787:     $symb=&symbclean($symb);
1.510     www      6788:     $thisurl=&deversion($thisurl);
1.439     www      6789:     $thisfn=&deversion($thisfn);
1.213     www      6790: 
                   6791:     my %bighash;
                   6792:     my $okay=0;
1.431     www      6793: 
1.620     albertel 6794:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6795:                             &GDBM_READER(),0640)) {
1.510     www      6796:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6797:         unless ($ids) { 
1.510     www      6798:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6799:         }
                   6800:         if ($ids) {
                   6801: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6802: 	    foreach my $id (split(/\,/,$ids)) {
                   6803: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6804:                if (
                   6805:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6806:    eq $symb) { 
1.620     albertel 6807: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6808: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6809: 		       $okay=1; 
                   6810: 		   }
                   6811: 	       }
1.216     www      6812: 	   }
                   6813:         }
1.213     www      6814: 	untie(%bighash);
                   6815:     }
                   6816:     return $okay;
1.31      www      6817: }
                   6818: 
1.210     www      6819: # --------------------------------------------------------------- Clean-up symb
                   6820: 
                   6821: sub symbclean {
                   6822:     my $symb=shift;
1.568     albertel 6823:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6824: # remove version from map
                   6825:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6826: 
1.210     www      6827: # remove version from URL
                   6828:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6829: 
1.507     www      6830: # remove wrapper
                   6831: 
1.510     www      6832:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6833:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6834:     return $symb;
1.409     www      6835: }
                   6836: 
                   6837: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6838: 
                   6839: sub encode_symb {
                   6840:     my ($map,$resid,$url)=@_;
                   6841:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6842: }
1.409     www      6843: 
                   6844: sub decode_symb {
1.568     albertel 6845:     my $symb=shift;
                   6846:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6847:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6848:     return (&fixversion($map),$resid,&fixversion($url));
                   6849: }
                   6850: 
                   6851: sub fixversion {
                   6852:     my $fn=shift;
1.609     banghart 6853:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6854:     my %bighash;
                   6855:     my $uri=&clutter($fn);
1.620     albertel 6856:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6857: # is this cached?
1.599     albertel 6858:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6859:     if (defined($cached)) { return $result; }
                   6860: # unfortunately not cached, or expired
1.620     albertel 6861:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6862: 	    &GDBM_READER(),0640)) {
                   6863:  	if ($bighash{'version_'.$uri}) {
                   6864:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6865:  	    unless (($version eq 'mostrecent') || 
                   6866: 		    ($version==&getversion($uri))) {
1.440     www      6867:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6868:  	    }
                   6869:  	}
                   6870:  	untie %bighash;
1.413     www      6871:     }
1.599     albertel 6872:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6873: }
                   6874: 
                   6875: sub deversion {
                   6876:     my $url=shift;
                   6877:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6878:     return $url;
1.210     www      6879: }
                   6880: 
1.31      www      6881: # ------------------------------------------------------ Return symb list entry
                   6882: 
                   6883: sub symbread {
1.249     www      6884:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6885:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6886:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6887: # no filename provided? try from environment
1.44      www      6888:     unless ($thisfn) {
1.620     albertel 6889:         if ($env{'request.symb'}) {
                   6890: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6891: 	}
1.620     albertel 6892: 	$thisfn=$env{'request.filename'};
1.44      www      6893:     }
1.569     albertel 6894:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6895: # is that filename actually a symb? Verify, clean, and return
                   6896:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6897: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6898: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6899: 	}
1.242     www      6900:     }
1.44      www      6901:     $thisfn=declutter($thisfn);
1.31      www      6902:     my %hash;
1.37      www      6903:     my %bighash;
                   6904:     my $syval='';
1.620     albertel 6905:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6906:         my $targetfn = $thisfn;
1.609     banghart 6907:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6908:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6909:         }
1.687     albertel 6910: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6911: 	    $targetfn=$1;
                   6912: 	}
1.620     albertel 6913:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6914:                       &GDBM_READER(),0640)) {
1.481     raeburn  6915: 	    $syval=$hash{$targetfn};
1.37      www      6916:             untie(%hash);
                   6917:         }
                   6918: # ---------------------------------------------------------- There was an entry
                   6919:         if ($syval) {
1.601     albertel 6920: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6921: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6922: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6923: 		    #return $env{$cache_str}='';
1.601     albertel 6924: 		#}    
                   6925: 		#$syval.=$1;
                   6926: 	    #}
1.37      www      6927:         } else {
                   6928: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6929:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6930:                             &GDBM_READER(),0640)) {
1.37      www      6931: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6932:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6933:               unless ($ids) { 
                   6934:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6935:               }
                   6936:               unless ($ids) {
                   6937: # alias?
                   6938: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6939:               }
1.37      www      6940:               if ($ids) {
                   6941: # ------------------------------------------------------------------- Has ID(s)
                   6942:                  my @possibilities=split(/\,/,$ids);
1.39      www      6943:                  if ($#possibilities==0) {
                   6944: # ----------------------------------------------- There is only one possibility
1.37      www      6945: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6946: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6947: 						    $resid,$thisfn);
1.249     www      6948:                  } elsif (!$donotrecurse) {
1.39      www      6949: # ------------------------------------------ There is more than one possibility
                   6950:                      my $realpossible=0;
1.800     albertel 6951:                      foreach my $id (@possibilities) {
                   6952: 			 my $file=$bighash{'src_'.$id};
1.39      www      6953:                          if (&allowed('bre',$file)) {
1.800     albertel 6954:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6955:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6956: 				$realpossible++;
1.626     albertel 6957:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6958: 						    $resid,$thisfn);
1.39      www      6959:                             }
                   6960: 			 }
1.191     harris41 6961:                      }
1.39      www      6962: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6963:                  } else {
                   6964:                      $syval='';
1.37      www      6965:                  }
                   6966: 	      }
                   6967:               untie(%bighash)
1.481     raeburn  6968:            }
1.31      www      6969:         }
1.62      www      6970:         if ($syval) {
1.620     albertel 6971: 	    return $env{$cache_str}=$syval;
1.62      www      6972:         }
1.31      www      6973:     }
1.44      www      6974:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6975:     return $env{$cache_str}='';
1.31      www      6976: }
                   6977: 
                   6978: # ---------------------------------------------------------- Return random seed
                   6979: 
1.32      www      6980: sub numval {
                   6981:     my $txt=shift;
                   6982:     $txt=~tr/A-J/0-9/;
                   6983:     $txt=~tr/a-j/0-9/;
                   6984:     $txt=~tr/K-T/0-9/;
                   6985:     $txt=~tr/k-t/0-9/;
                   6986:     $txt=~tr/U-Z/0-5/;
                   6987:     $txt=~tr/u-z/0-5/;
                   6988:     $txt=~s/\D//g;
1.564     albertel 6989:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6990:     return int($txt);
1.368     albertel 6991: }
                   6992: 
1.484     albertel 6993: sub numval2 {
                   6994:     my $txt=shift;
                   6995:     $txt=~tr/A-J/0-9/;
                   6996:     $txt=~tr/a-j/0-9/;
                   6997:     $txt=~tr/K-T/0-9/;
                   6998:     $txt=~tr/k-t/0-9/;
                   6999:     $txt=~tr/U-Z/0-5/;
                   7000:     $txt=~tr/u-z/0-5/;
                   7001:     $txt=~s/\D//g;
                   7002:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7003:     my $total;
                   7004:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7005:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7006:     return int($total);
                   7007: }
                   7008: 
1.575     albertel 7009: sub numval3 {
                   7010:     use integer;
                   7011:     my $txt=shift;
                   7012:     $txt=~tr/A-J/0-9/;
                   7013:     $txt=~tr/a-j/0-9/;
                   7014:     $txt=~tr/K-T/0-9/;
                   7015:     $txt=~tr/k-t/0-9/;
                   7016:     $txt=~tr/U-Z/0-5/;
                   7017:     $txt=~tr/u-z/0-5/;
                   7018:     $txt=~s/\D//g;
                   7019:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7020:     my $total;
                   7021:     foreach my $val (@txts) { $total+=$val; }
                   7022:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7023:     return $total;
                   7024: }
                   7025: 
1.675     albertel 7026: sub digest {
                   7027:     my ($data)=@_;
                   7028:     my $digest=&Digest::MD5::md5($data);
                   7029:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7030:     my ($e,$f);
                   7031:     {
                   7032:         use integer;
                   7033:         $e=($a+$b);
                   7034:         $f=($c+$d);
                   7035:         if ($_64bit) {
                   7036:             $e=(($e<<32)>>32);
                   7037:             $f=(($f<<32)>>32);
                   7038:         }
                   7039:     }
                   7040:     if (wantarray) {
                   7041: 	return ($e,$f);
                   7042:     } else {
                   7043: 	my $g;
                   7044: 	{
                   7045: 	    use integer;
                   7046: 	    $g=($e+$f);
                   7047: 	    if ($_64bit) {
                   7048: 		$g=(($g<<32)>>32);
                   7049: 	    }
                   7050: 	}
                   7051: 	return $g;
                   7052:     }
                   7053: }
                   7054: 
1.368     albertel 7055: sub latest_rnd_algorithm_id {
1.675     albertel 7056:     return '64bit5';
1.366     albertel 7057: }
1.32      www      7058: 
1.503     albertel 7059: sub get_rand_alg {
                   7060:     my ($courseid)=@_;
1.790     albertel 7061:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7062:     if ($courseid) {
1.620     albertel 7063: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7064:     }
                   7065:     return &latest_rnd_algorithm_id();
                   7066: }
                   7067: 
1.562     albertel 7068: sub validCODE {
                   7069:     my ($CODE)=@_;
                   7070:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7071:     return 0;
                   7072: }
                   7073: 
1.491     albertel 7074: sub getCODE {
1.620     albertel 7075:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7076:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7077: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7078: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7079: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7080:     }
                   7081:     return undef;
                   7082: }
                   7083: 
1.31      www      7084: sub rndseed {
1.155     albertel 7085:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7086:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 7087:     if (!$symb) {
1.366     albertel 7088: 	unless ($symb=$wsymb) { return time; }
                   7089:     }
                   7090:     if (!$courseid) { $courseid=$wcourseid; }
                   7091:     if (!$domain) { $domain=$wdomain; }
                   7092:     if (!$username) { $username=$wusername }
1.503     albertel 7093:     my $which=&get_rand_alg();
1.803     albertel 7094: 
1.491     albertel 7095:     if (defined(&getCODE())) {
1.675     albertel 7096: 	if ($which eq '64bit5') {
                   7097: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7098: 	} elsif ($which eq '64bit4') {
1.575     albertel 7099: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7100: 	} else {
                   7101: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7102: 	}
1.675     albertel 7103:     } elsif ($which eq '64bit5') {
                   7104: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7105:     } elsif ($which eq '64bit4') {
                   7106: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7107:     } elsif ($which eq '64bit3') {
                   7108: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7109:     } elsif ($which eq '64bit2') {
                   7110: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7111:     } elsif ($which eq '64bit') {
                   7112: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7113:     }
                   7114:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7115: }
                   7116: 
                   7117: sub rndseed_32bit {
                   7118:     my ($symb,$courseid,$domain,$username)=@_;
                   7119:     {
                   7120: 	use integer;
                   7121: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7122: 	my $symbseed=numval($symb) << 22;
                   7123: 	my $namechck=unpack("%32C*",$username) << 17;
                   7124: 	my $nameseed=numval($username) << 12;
                   7125: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7126: 	my $courseseed=unpack("%32C*",$courseid);
                   7127: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7128: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7129: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7130: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7131: 	return $num;
                   7132:     }
                   7133: }
                   7134: 
                   7135: sub rndseed_64bit {
                   7136:     my ($symb,$courseid,$domain,$username)=@_;
                   7137:     {
                   7138: 	use integer;
                   7139: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7140: 	my $symbseed=numval($symb) << 10;
                   7141: 	my $namechck=unpack("%32S*",$username);
                   7142: 	
                   7143: 	my $nameseed=numval($username) << 21;
                   7144: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7145: 	my $courseseed=unpack("%32S*",$courseid);
                   7146: 	
                   7147: 	my $num1=$symbchck+$symbseed+$namechck;
                   7148: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7149: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7150: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7151: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7152: 	return "$num1,$num2";
1.155     albertel 7153:     }
1.366     albertel 7154: }
                   7155: 
1.443     albertel 7156: sub rndseed_64bit2 {
                   7157:     my ($symb,$courseid,$domain,$username)=@_;
                   7158:     {
                   7159: 	use integer;
                   7160: 	# strings need to be an even # of cahracters long, it it is odd the
                   7161:         # last characters gets thrown away
                   7162: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7163: 	my $symbseed=numval($symb) << 10;
                   7164: 	my $namechck=unpack("%32S*",$username.' ');
                   7165: 	
                   7166: 	my $nameseed=numval($username) << 21;
1.501     albertel 7167: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7168: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7169: 	
                   7170: 	my $num1=$symbchck+$symbseed+$namechck;
                   7171: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7172: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7173: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7174: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7175: 	return "$num1,$num2";
                   7176:     }
                   7177: }
                   7178: 
                   7179: sub rndseed_64bit3 {
                   7180:     my ($symb,$courseid,$domain,$username)=@_;
                   7181:     {
                   7182: 	use integer;
                   7183: 	# strings need to be an even # of cahracters long, it it is odd the
                   7184:         # last characters gets thrown away
                   7185: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7186: 	my $symbseed=numval2($symb) << 10;
                   7187: 	my $namechck=unpack("%32S*",$username.' ');
                   7188: 	
                   7189: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7190: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7191: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7192: 	
                   7193: 	my $num1=$symbchck+$symbseed+$namechck;
                   7194: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7195: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7196: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7197: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7198: 	
1.503     albertel 7199: 	return "$num1:$num2";
1.443     albertel 7200:     }
                   7201: }
                   7202: 
1.575     albertel 7203: sub rndseed_64bit4 {
                   7204:     my ($symb,$courseid,$domain,$username)=@_;
                   7205:     {
                   7206: 	use integer;
                   7207: 	# strings need to be an even # of cahracters long, it it is odd the
                   7208:         # last characters gets thrown away
                   7209: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7210: 	my $symbseed=numval3($symb) << 10;
                   7211: 	my $namechck=unpack("%32S*",$username.' ');
                   7212: 	
                   7213: 	my $nameseed=numval3($username) << 21;
                   7214: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7215: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7216: 	
                   7217: 	my $num1=$symbchck+$symbseed+$namechck;
                   7218: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7219: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7220: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7221: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7222: 	
                   7223: 	return "$num1:$num2";
                   7224:     }
                   7225: }
                   7226: 
1.675     albertel 7227: sub rndseed_64bit5 {
                   7228:     my ($symb,$courseid,$domain,$username)=@_;
                   7229:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7230:     return "$num1:$num2";
                   7231: }
                   7232: 
1.366     albertel 7233: sub rndseed_CODE_64bit {
                   7234:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7235:     {
1.366     albertel 7236: 	use integer;
1.443     albertel 7237: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7238: 	my $symbseed=numval2($symb);
1.491     albertel 7239: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7240: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7241: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7242: 	my $num1=$symbseed+$CODEchck;
                   7243: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7244: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7245: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7246: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7247: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7248: 	return "$num1:$num2";
1.366     albertel 7249:     }
                   7250: }
                   7251: 
1.575     albertel 7252: sub rndseed_CODE_64bit4 {
                   7253:     my ($symb,$courseid,$domain,$username)=@_;
                   7254:     {
                   7255: 	use integer;
                   7256: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7257: 	my $symbseed=numval3($symb);
                   7258: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7259: 	my $CODEseed=numval3(&getCODE());
                   7260: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7261: 	my $num1=$symbseed+$CODEchck;
                   7262: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7263: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7264: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7265: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7266: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7267: 	return "$num1:$num2";
                   7268:     }
                   7269: }
                   7270: 
1.675     albertel 7271: sub rndseed_CODE_64bit5 {
                   7272:     my ($symb,$courseid,$domain,$username)=@_;
                   7273:     my $code = &getCODE();
                   7274:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7275:     return "$num1:$num2";
                   7276: }
                   7277: 
1.366     albertel 7278: sub setup_random_from_rndseed {
                   7279:     my ($rndseed)=@_;
1.503     albertel 7280:     if ($rndseed =~/([,:])/) {
                   7281: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7282: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7283:     } else {
                   7284: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7285:     }
1.36      albertel 7286: }
                   7287: 
1.474     albertel 7288: sub latest_receipt_algorithm_id {
1.835     albertel 7289:     return 'receipt3';
1.474     albertel 7290: }
                   7291: 
1.480     www      7292: sub recunique {
                   7293:     my $fucourseid=shift;
                   7294:     my $unique;
1.835     albertel 7295:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7296: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7297: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7298:     } else {
                   7299: 	$unique=$perlvar{'lonReceipt'};
                   7300:     }
                   7301:     return unpack("%32C*",$unique);
                   7302: }
                   7303: 
                   7304: sub recprefix {
                   7305:     my $fucourseid=shift;
                   7306:     my $prefix;
1.835     albertel 7307:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7308: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7309: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7310:     } else {
                   7311: 	$prefix=$perlvar{'lonHostID'};
                   7312:     }
                   7313:     return unpack("%32C*",$prefix);
                   7314: }
                   7315: 
1.76      www      7316: sub ireceipt {
1.474     albertel 7317:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7318: 
                   7319:     my $return =&recprefix($fucourseid).'-';
                   7320: 
                   7321:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7322: 	$env{'request.state'} eq 'construct') {
                   7323: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7324: 	return $return;
                   7325:     }
                   7326: 
1.76      www      7327:     my $cuname=unpack("%32C*",$funame);
                   7328:     my $cudom=unpack("%32C*",$fudom);
                   7329:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7330:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7331:     my $cunique=&recunique($fucourseid);
1.474     albertel 7332:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7333:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7334: 
1.790     albertel 7335: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7336: 			       
                   7337: 	$return.= ($cunique%$cuname+
                   7338: 		   $cunique%$cudom+
                   7339: 		   $cusymb%$cuname+
                   7340: 		   $cusymb%$cudom+
                   7341: 		   $cucourseid%$cuname+
                   7342: 		   $cucourseid%$cudom+
                   7343: 		   $cpart%$cuname+
                   7344: 		   $cpart%$cudom);
                   7345:     } else {
                   7346: 	$return.= ($cunique%$cuname+
                   7347: 		   $cunique%$cudom+
                   7348: 		   $cusymb%$cuname+
                   7349: 		   $cusymb%$cudom+
                   7350: 		   $cucourseid%$cuname+
                   7351: 		   $cucourseid%$cudom);
                   7352:     }
                   7353:     return $return;
1.76      www      7354: }
                   7355: 
                   7356: sub receipt {
1.474     albertel 7357:     my ($part)=@_;
1.790     albertel 7358:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7359:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7360: }
1.260     ng       7361: 
1.790     albertel 7362: sub whichuser {
                   7363:     my ($passedsymb)=@_;
                   7364:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7365:     if (defined($env{'form.grade_symb'})) {
                   7366: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7367: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7368: 	if (!$allowed &&
                   7369: 	    exists($env{'request.course.sec'}) &&
                   7370: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7371: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7372: 			      '/'.$env{'request.course.sec'});
                   7373: 	}
                   7374: 	if ($allowed) {
                   7375: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7376: 	    $courseid=$tmp_courseid;
                   7377: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7378: 	    ($name)=&get_env_multiple('form.grade_username');
                   7379: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7380: 	}
                   7381:     }
                   7382:     if (!$passedsymb) {
                   7383: 	$symb=&symbread();
                   7384:     } else {
                   7385: 	$symb=$passedsymb;
                   7386:     }
                   7387:     $courseid=$env{'request.course.id'};
                   7388:     $domain=$env{'user.domain'};
                   7389:     $name=$env{'user.name'};
                   7390:     if ($name eq 'public' && $domain eq 'public') {
                   7391: 	if (!defined($env{'form.username'})) {
                   7392: 	    $env{'form.username'}.=time.rand(10000000);
                   7393: 	}
                   7394: 	$name.=$env{'form.username'};
                   7395:     }
                   7396:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7397: 
                   7398: }
                   7399: 
1.36      albertel 7400: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7401: # returns either the contents of the file or 
                   7402: # -1 if the file doesn't exist
1.481     raeburn  7403: #
                   7404: # if the target is a file that was uploaded via DOCS, 
                   7405: # a check will be made to see if a current copy exists on the local server,
                   7406: # if it does this will be served, otherwise a copy will be retrieved from
                   7407: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7408: # the local server.   
1.472     albertel 7409: 
1.36      albertel 7410: sub getfile {
1.538     albertel 7411:     my ($file) = @_;
1.609     banghart 7412:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7413:     &repcopy($file);
                   7414:     return &readfile($file);
                   7415: }
                   7416: 
                   7417: sub repcopy_userfile {
                   7418:     my ($file)=@_;
1.609     banghart 7419:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7420:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7421:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7422: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7423:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7424:     if (-e "$file") {
1.828     www      7425: # we already have a local copy, check it out
1.538     albertel 7426: 	my @fileinfo = stat($file);
1.828     www      7427: 	my $rtncode;
                   7428: 	my $info;
1.538     albertel 7429: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7430: 	if ($lwpresp ne 'ok') {
1.828     www      7431: # there is no such file anymore, even though we had a local copy
1.482     albertel 7432: 	    if ($rtncode eq '404') {
1.538     albertel 7433: 		unlink($file);
1.482     albertel 7434: 	    }
                   7435: 	    return -1;
                   7436: 	}
                   7437: 	if ($info < $fileinfo[9]) {
1.828     www      7438: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7439: 	    return 'ok';
1.828     www      7440: 	} else {
                   7441: # the file is outdated, get rid of it
                   7442: 	    unlink($file);
1.482     albertel 7443: 	}
1.828     www      7444:     }
                   7445: # one way or the other, at this point, we don't have the file
                   7446: # construct the correct path for the file
                   7447:     my @parts = ($cdom,$cnum); 
                   7448:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7449: 	push @parts, split(/\//,$1);
                   7450:     }
                   7451:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7452:     foreach my $part (@parts) {
                   7453: 	$path .= '/'.$part;
                   7454: 	if (!-e $path) {
                   7455: 	    mkdir($path,0770);
1.482     albertel 7456: 	}
                   7457:     }
1.828     www      7458: # now the path exists for sure
                   7459: # get a user agent
                   7460:     my $ua=new LWP::UserAgent;
                   7461:     my $transferfile=$file.'.in.transfer';
                   7462: # FIXME: this should flock
                   7463:     if (-e $transferfile) { return 'ok'; }
                   7464:     my $request;
                   7465:     $uri=~s/^\///;
1.838     albertel 7466:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7467:     my $response=$ua->request($request,$transferfile);
                   7468: # did it work?
                   7469:     if ($response->is_error()) {
                   7470: 	unlink($transferfile);
                   7471: 	&logthis("Userfile repcopy failed for $uri");
                   7472: 	return -1;
                   7473:     }
                   7474: # worked, rename the transfer file
                   7475:     rename($transferfile,$file);
1.607     raeburn  7476:     return 'ok';
1.481     raeburn  7477: }
                   7478: 
1.517     albertel 7479: sub tokenwrapper {
                   7480:     my $uri=shift;
1.552     albertel 7481:     $uri=~s|^http\://([^/]+)||;
                   7482:     $uri=~s|^/||;
1.620     albertel 7483:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7484:     my $token=$1;
1.552     albertel 7485:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7486:     if ($udom && $uname && $file) {
                   7487: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7488:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7489:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7490:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7491:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7492:     } else {
                   7493:         return '/adm/notfound.html';
                   7494:     }
                   7495: }
                   7496: 
1.828     www      7497: # call with reqtype HEAD: get last modification time
                   7498: # call with reqtype GET: get the file contents
                   7499: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7500: #
1.481     raeburn  7501: sub getuploaded {
                   7502:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7503:     $uri=~s/^\///;
1.838     albertel 7504:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7505:     my $ua=new LWP::UserAgent;
                   7506:     my $request=new HTTP::Request($reqtype,$uri);
                   7507:     my $response=$ua->request($request);
                   7508:     $$rtncode = $response->code;
1.482     albertel 7509:     if (! $response->is_success()) {
                   7510: 	return 'failed';
                   7511:     }      
                   7512:     if ($reqtype eq 'HEAD') {
1.486     www      7513: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7514:     } elsif ($reqtype eq 'GET') {
                   7515: 	$$info = $response->content;
1.472     albertel 7516:     }
1.482     albertel 7517:     return 'ok';
1.36      albertel 7518: }
                   7519: 
1.481     raeburn  7520: sub readfile {
                   7521:     my $file = shift;
                   7522:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7523:     my $fh;
                   7524:     open($fh,"<$file");
                   7525:     my $a='';
1.800     albertel 7526:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7527:     return $a;
                   7528: }
                   7529: 
1.36      albertel 7530: sub filelocation {
1.590     banghart 7531:     my ($dir,$file) = @_;
                   7532:     my $location;
                   7533:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7534: 
                   7535:     if ($file =~ m-^/adm/-) {
                   7536: 	$file=~s-^/adm/wrapper/-/-;
                   7537: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7538:     }
1.882     albertel 7539: 
1.590     banghart 7540:     if ($file=~m:^/~:) { # is a contruction space reference
                   7541:         $location = $file;
                   7542:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7543:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7544: 	# is a correct contruction space reference
                   7545:         $location = $file;
1.609     banghart 7546:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7547:         my ($udom,$uname,$filename)=
1.811     albertel 7548:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7549:         my $home=&homeserver($uname,$udom);
                   7550:         my $is_me=0;
                   7551:         my @ids=&current_machine_ids();
                   7552:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7553:         if ($is_me) {
1.740     www      7554:   	    $location=&propath($udom,$uname).
1.590     banghart 7555:   	      '/userfiles/'.$filename;
                   7556:         } else {
                   7557:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7558:   	      $udom.'/'.$uname.'/'.$filename;
                   7559:         }
1.882     albertel 7560:     } elsif ($file =~ m-^/adm/-) {
                   7561: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7562:     } else {
                   7563:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7564:         $file=~s:^/res/:/:;
                   7565:         if ( !( $file =~ m:^/:) ) {
                   7566:             $location = $dir. '/'.$file;
                   7567:         } else {
                   7568:             $location = '/home/httpd/html/res'.$file;
                   7569:         }
1.59      albertel 7570:     }
1.590     banghart 7571:     $location=~s://+:/:g; # remove duplicate /
                   7572:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7573:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7574:     return $location;
1.46      www      7575: }
1.36      albertel 7576: 
1.46      www      7577: sub hreflocation {
                   7578:     my ($dir,$file)=@_;
1.460     albertel 7579:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7580: 	$file=filelocation($dir,$file);
1.700     albertel 7581:     } elsif ($file=~m-^/adm/-) {
                   7582: 	$file=~s-^/adm/wrapper/-/-;
                   7583: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7584:     }
                   7585:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7586: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7587:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7588: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7589:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7590: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7591: 	    -/uploaded/$1/$2/-x;
1.46      www      7592:     }
1.462     albertel 7593:     return $file;
1.465     albertel 7594: }
                   7595: 
                   7596: sub current_machine_domains {
1.853     albertel 7597:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7598: }
                   7599: 
                   7600: sub machine_domains {
                   7601:     my ($hostname) = @_;
1.465     albertel 7602:     my @domains;
1.838     albertel 7603:     my %hostname = &all_hostnames();
1.465     albertel 7604:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7605: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7606: 	if ($hostname eq $name) {
1.844     albertel 7607: 	    push(@domains,&host_domain($id));
1.465     albertel 7608: 	}
                   7609:     }
                   7610:     return @domains;
                   7611: }
                   7612: 
                   7613: sub current_machine_ids {
1.853     albertel 7614:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7615: }
                   7616: 
                   7617: sub machine_ids {
                   7618:     my ($hostname) = @_;
                   7619:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7620:     my @ids;
1.888     albertel 7621:     my %name_to_host = &all_names();
1.889     albertel 7622:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7623: 	return @{ $name_to_host{$hostname} };
                   7624:     }
                   7625:     return;
1.31      www      7626: }
                   7627: 
1.824     raeburn  7628: sub additional_machine_domains {
                   7629:     my @domains;
                   7630:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7631:     while( my $line = <$fh>) {
                   7632:         $line =~ s/\s//g;
                   7633:         push(@domains,$line);
                   7634:     }
                   7635:     return @domains;
                   7636: }
                   7637: 
                   7638: sub default_login_domain {
                   7639:     my $domain = $perlvar{'lonDefDomain'};
                   7640:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7641:     foreach my $posdom (&current_machine_domains(),
                   7642:                         &additional_machine_domains()) {
                   7643:         if (lc($posdom) eq lc($testdomain)) {
                   7644:             $domain=$posdom;
                   7645:             last;
                   7646:         }
                   7647:     }
                   7648:     return $domain;
                   7649: }
                   7650: 
1.31      www      7651: # ------------------------------------------------------------- Declutters URLs
                   7652: 
                   7653: sub declutter {
                   7654:     my $thisfn=shift;
1.569     albertel 7655:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7656:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7657:     $thisfn=~s/^\///;
1.697     albertel 7658:     $thisfn=~s|^adm/wrapper/||;
                   7659:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7660:     $thisfn=~s/^res\///;
1.235     www      7661:     $thisfn=~s/\?.+$//;
1.268     www      7662:     return $thisfn;
                   7663: }
                   7664: 
                   7665: # ------------------------------------------------------------- Clutter up URLs
                   7666: 
                   7667: sub clutter {
                   7668:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7669:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7670: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7671:        $thisfn='/res'.$thisfn; 
                   7672:     }
1.694     albertel 7673:     if ($thisfn !~m|/adm|) {
1.695     albertel 7674: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7675: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7676: 	} else {
                   7677: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7678: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7679: 	    if ($embstyle eq 'ssi'
                   7680: 		|| ($embstyle eq 'hdn')
                   7681: 		|| ($embstyle eq 'rat')
                   7682: 		|| ($embstyle eq 'prv')
                   7683: 		|| ($embstyle eq 'ign')) {
                   7684: 		#do nothing with these
                   7685: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7686: 		|| ($embstyle eq 'emb')
                   7687: 		|| ($embstyle eq 'wrp')) {
                   7688: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7689: 	    } elsif ($embstyle eq 'unk'
                   7690: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7691: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7692: 	    } else {
1.718     www      7693: #		&logthis("Got a blank emb style");
1.695     albertel 7694: 	    }
1.694     albertel 7695: 	}
                   7696:     }
1.31      www      7697:     return $thisfn;
1.12      www      7698: }
                   7699: 
1.787     albertel 7700: sub clutter_with_no_wrapper {
                   7701:     my $uri = &clutter(shift);
                   7702:     if ($uri =~ m-^/adm/-) {
                   7703: 	$uri =~ s-^/adm/wrapper/-/-;
                   7704: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7705:     }
                   7706:     return $uri;
                   7707: }
                   7708: 
1.557     albertel 7709: sub freeze_escape {
                   7710:     my ($value)=@_;
                   7711:     if (ref($value)) {
                   7712: 	$value=&nfreeze($value);
                   7713: 	return '__FROZEN__'.&escape($value);
                   7714:     }
                   7715:     return &escape($value);
                   7716: }
                   7717: 
1.11      www      7718: 
1.557     albertel 7719: sub thaw_unescape {
                   7720:     my ($value)=@_;
                   7721:     if ($value =~ /^__FROZEN__/) {
                   7722: 	substr($value,0,10,undef);
                   7723: 	$value=&unescape($value);
                   7724: 	return &thaw($value);
                   7725:     }
                   7726:     return &unescape($value);
                   7727: }
                   7728: 
1.436     albertel 7729: sub correct_line_ends {
                   7730:     my ($result)=@_;
                   7731:     $$result =~s/\r\n/\n/mg;
                   7732:     $$result =~s/\r/\n/mg;
1.415     albertel 7733: }
1.1       albertel 7734: # ================================================================ Main Program
                   7735: 
1.184     www      7736: sub goodbye {
1.204     albertel 7737:    &logthis("Starting Shut down");
1.443     albertel 7738: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7739:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7740: #converted
1.599     albertel 7741: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7742:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7743: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7744: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7745: #1.1 only
1.870     albertel 7746: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7747: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7748: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7749: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7750:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7751:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7752:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7753:    &flushcourselogs();
                   7754:    &logthis("Shutting down");
                   7755: }
                   7756: 
1.852     albertel 7757: sub get_dns {
1.869     albertel 7758:     my ($url,$func,$ignore_cache) = @_;
                   7759:     if (!$ignore_cache) {
                   7760: 	my ($content,$cached)=
                   7761: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7762: 	if ($cached) {
                   7763: 	    &$func($content);
                   7764: 	    return;
                   7765: 	}
                   7766:     }
                   7767: 
                   7768:     my %alldns;
1.852     albertel 7769:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7770:     foreach my $dns (<$config>) {
                   7771: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7772: 	$alldns{$1} = 1;
                   7773:     }
                   7774:     while (%alldns) {
                   7775: 	my ($dns) = keys(%alldns);
                   7776: 	delete($alldns{$dns});
1.852     albertel 7777: 	my $ua=new LWP::UserAgent;
                   7778: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7779: 	my $response=$ua->request($request);
                   7780: 	next if ($response->is_error());
                   7781: 	my @content = split("\n",$response->content);
1.869     albertel 7782: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7783: 	&$func(\@content);
1.869     albertel 7784: 	return;
1.852     albertel 7785:     }
                   7786:     close($config);
1.871     albertel 7787:     my $which = (split('/',$url))[3];
                   7788:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7789:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7790:     my @content = <$config>;
                   7791:     &$func(\@content);
                   7792:     return;
1.852     albertel 7793: }
1.327     albertel 7794: # ------------------------------------------------------------ Read domain file
                   7795: {
1.852     albertel 7796:     my $loaded;
1.846     albertel 7797:     my %domain;
                   7798: 
1.852     albertel 7799:     sub parse_domain_tab {
                   7800: 	my ($lines) = @_;
                   7801: 	foreach my $line (@$lines) {
                   7802: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7803: 
1.846     albertel 7804: 	    chomp($line);
1.852     albertel 7805: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7806: 	    my %this_domain;
                   7807: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7808: 			       'lang_def', 'city', 'longi', 'lati',
                   7809: 			       'primary') {
                   7810: 		$this_domain{$field} = shift(@elements);
                   7811: 	    }
                   7812: 	    $domain{$name} = \%this_domain;
1.852     albertel 7813: 	}
                   7814:     }
1.864     albertel 7815: 
                   7816:     sub reset_domain_info {
                   7817: 	undef($loaded);
                   7818: 	undef(%domain);
                   7819:     }
                   7820: 
1.852     albertel 7821:     sub load_domain_tab {
1.869     albertel 7822: 	my ($ignore_cache) = @_;
                   7823: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7824: 	my $fh;
                   7825: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7826: 	    my @lines = <$fh>;
                   7827: 	    &parse_domain_tab(\@lines);
1.448     albertel 7828: 	}
1.852     albertel 7829: 	close($fh);
                   7830: 	$loaded = 1;
1.327     albertel 7831:     }
1.846     albertel 7832: 
                   7833:     sub domain {
1.852     albertel 7834: 	&load_domain_tab() if (!$loaded);
                   7835: 
1.846     albertel 7836: 	my ($name,$what) = @_;
                   7837: 	return if ( !exists($domain{$name}) );
                   7838: 
                   7839: 	if (!$what) {
                   7840: 	    return $domain{$name}{'description'};
                   7841: 	}
                   7842: 	return $domain{$name}{$what};
                   7843:     }
1.327     albertel 7844: }
                   7845: 
                   7846: 
1.1       albertel 7847: # ------------------------------------------------------------- Read hosts file
                   7848: {
1.838     albertel 7849:     my %hostname;
1.844     albertel 7850:     my %hostdom;
1.845     albertel 7851:     my %libserv;
1.852     albertel 7852:     my $loaded;
1.888     albertel 7853:     my %name_to_host;
1.852     albertel 7854: 
                   7855:     sub parse_hosts_tab {
                   7856: 	my ($file) = @_;
                   7857: 	foreach my $configline (@$file) {
                   7858: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7859: 	    next if ($configline =~ /^\^/);
                   7860: 	    chomp($configline);
                   7861: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7862: 	    $name=~s/\s//g;
                   7863: 	    if ($id && $domain && $role && $name) {
                   7864: 		$hostname{$id}=$name;
1.888     albertel 7865: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 7866: 		$hostdom{$id}=$domain;
                   7867: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   7868: 	    }
                   7869: 	}
                   7870:     }
1.864     albertel 7871:     
                   7872:     sub reset_hosts_info {
                   7873: 	&reset_domain_info();
                   7874: 	&reset_hosts_ip_info();
                   7875: 	undef(%hostname);
                   7876: 	undef(%hostdom);
                   7877: 	undef(%libserv);
                   7878: 	undef($loaded);
                   7879:     }
1.1       albertel 7880: 
1.852     albertel 7881:     sub load_hosts_tab {
1.869     albertel 7882: 	my ($ignore_cache) = @_;
                   7883: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 7884: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7885: 	my @config = <$config>;
                   7886: 	&parse_hosts_tab(\@config);
                   7887: 	close($config);
                   7888: 	$loaded=1;
1.1       albertel 7889:     }
1.852     albertel 7890: 
1.838     albertel 7891:     sub hostname {
1.852     albertel 7892: 	&load_hosts_tab() if (!$loaded);
                   7893: 
1.838     albertel 7894: 	my ($lonid) = @_;
                   7895: 	return $hostname{$lonid};
                   7896:     }
1.845     albertel 7897: 
1.838     albertel 7898:     sub all_hostnames {
1.852     albertel 7899: 	&load_hosts_tab() if (!$loaded);
                   7900: 
1.838     albertel 7901: 	return %hostname;
                   7902:     }
1.845     albertel 7903: 
1.888     albertel 7904:     sub all_names {
                   7905: 	&load_hosts_tab() if (!$loaded);
                   7906: 
                   7907: 	return %name_to_host;
                   7908:     }
                   7909: 
1.845     albertel 7910:     sub is_library {
1.852     albertel 7911: 	&load_hosts_tab() if (!$loaded);
                   7912: 
1.845     albertel 7913: 	return exists($libserv{$_[0]});
                   7914:     }
                   7915: 
                   7916:     sub all_library {
1.852     albertel 7917: 	&load_hosts_tab() if (!$loaded);
                   7918: 
1.845     albertel 7919: 	return %libserv;
                   7920:     }
                   7921: 
1.841     albertel 7922:     sub get_servers {
1.852     albertel 7923: 	&load_hosts_tab() if (!$loaded);
                   7924: 
1.841     albertel 7925: 	my ($domain,$type) = @_;
                   7926: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7927: 	                                          : %hostname;
                   7928: 	my %result;
1.842     albertel 7929: 	if (ref($domain) eq 'ARRAY') {
                   7930: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7931: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7932: 		    $result{$host} = $hostname;
                   7933: 		}
                   7934: 	    }
                   7935: 	} else {
                   7936: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7937: 		if ($hostdom{$host} eq $domain) {
                   7938: 		    $result{$host} = $hostname;
                   7939: 		}
1.841     albertel 7940: 	    }
                   7941: 	}
                   7942: 	return %result;
                   7943:     }
1.845     albertel 7944: 
1.844     albertel 7945:     sub host_domain {
1.852     albertel 7946: 	&load_hosts_tab() if (!$loaded);
                   7947: 
1.844     albertel 7948: 	my ($lonid) = @_;
                   7949: 	return $hostdom{$lonid};
                   7950:     }
                   7951: 
1.841     albertel 7952:     sub all_domains {
1.852     albertel 7953: 	&load_hosts_tab() if (!$loaded);
                   7954: 
1.841     albertel 7955: 	my %seen;
                   7956: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7957: 	return @uniq;
                   7958:     }
1.1       albertel 7959: }
                   7960: 
1.847     albertel 7961: { 
                   7962:     my %iphost;
1.856     albertel 7963:     my %name_to_ip;
                   7964:     my %lonid_to_ip;
1.869     albertel 7965: 
                   7966:     my %valid_ip;
                   7967:     sub valid_ip {
                   7968: 	my ($ip) = @_;
                   7969: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
                   7970: 	    return 1;	
                   7971: 	}
                   7972: 	my $name = gethostbyip($ip);
                   7973: 	my $lonid = &hostname($name);
                   7974: 	if (defined($lonid)) {
                   7975: 	    $valid_ip{$ip} = $lonid;
                   7976: 	    return 1;
                   7977: 	}
                   7978: 	my %iphosts = &get_iphost();
                   7979: 	if (ref($iphost{$ip})) {
                   7980: 	    return 1;	
                   7981: 	}
                   7982:     }
                   7983: 
1.847     albertel 7984:     sub get_hosts_from_ip {
                   7985: 	my ($ip) = @_;
                   7986: 	my %iphosts = &get_iphost();
                   7987: 	if (ref($iphosts{$ip})) {
                   7988: 	    return @{$iphosts{$ip}};
                   7989: 	}
                   7990: 	return;
1.839     albertel 7991:     }
1.864     albertel 7992:     
                   7993:     sub reset_hosts_ip_info {
                   7994: 	undef(%iphost);
                   7995: 	undef(%name_to_ip);
                   7996: 	undef(%lonid_to_ip);
                   7997:     }
1.856     albertel 7998: 
                   7999:     sub get_host_ip {
                   8000: 	my ($lonid) = @_;
                   8001: 	if (exists($lonid_to_ip{$lonid})) {
                   8002: 	    return $lonid_to_ip{$lonid};
                   8003: 	}
                   8004: 	my $name=&hostname($lonid);
                   8005:    	my $ip = gethostbyname($name);
                   8006: 	return if (!$ip || length($ip) ne 4);
                   8007: 	$ip=inet_ntoa($ip);
                   8008: 	$name_to_ip{$name}   = $ip;
                   8009: 	$lonid_to_ip{$lonid} = $ip;
                   8010: 	return $ip;
                   8011:     }
1.847     albertel 8012:     
                   8013:     sub get_iphost {
1.869     albertel 8014: 	my ($ignore_cache) = @_;
                   8015: 	if (!$ignore_cache) {
                   8016: 	    if (%iphost) {
                   8017: 		return %iphost;
                   8018: 	    }
                   8019: 	    my ($ip_info,$cached)=
                   8020: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8021: 	    if ($cached) {
                   8022: 		%iphost      = %{$ip_info->[0]};
                   8023: 		%name_to_ip  = %{$ip_info->[1]};
                   8024: 		%lonid_to_ip = %{$ip_info->[2]};
                   8025: 		return %iphost;
                   8026: 	    }
                   8027: 	}
1.888     albertel 8028: 	my %name_to_host = &all_names();
                   8029: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8030: 	    my $ip;
                   8031: 	    if (!exists($name_to_ip{$name})) {
                   8032: 		$ip = gethostbyname($name);
                   8033: 		if (!$ip || length($ip) ne 4) {
1.888     albertel 8034: 		    &logthis("Skipping name $name no IP found");
1.847     albertel 8035: 		    next;
                   8036: 		}
                   8037: 		$ip=inet_ntoa($ip);
                   8038: 		$name_to_ip{$name} = $ip;
                   8039: 	    } else {
                   8040: 		$ip = $name_to_ip{$name};
1.653     albertel 8041: 	    }
1.888     albertel 8042: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8043: 		$lonid_to_ip{$id} = $ip;
                   8044: 	    }
                   8045: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8046: 	}
1.869     albertel 8047: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8048: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   8049: 				      24*60*60);
                   8050: 
1.847     albertel 8051: 	return %iphost;
1.598     albertel 8052:     }
                   8053: }
                   8054: 
1.862     albertel 8055: BEGIN {
                   8056: 
                   8057: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8058:     unless ($readit) {
                   8059: {
                   8060:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8061:     %perlvar = (%perlvar,%{$configvars});
                   8062: }
                   8063: 
                   8064: 
1.1       albertel 8065: # ------------------------------------------------------ Read spare server file
                   8066: {
1.448     albertel 8067:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8068: 
                   8069:     while (my $configline=<$config>) {
                   8070:        chomp($configline);
1.284     matthew  8071:        if ($configline) {
1.784     albertel 8072: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8073: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8074: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8075:        }
                   8076:     }
1.448     albertel 8077:     close($config);
1.1       albertel 8078: }
1.11      www      8079: # ------------------------------------------------------------ Read permissions
                   8080: {
1.448     albertel 8081:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8082: 
                   8083:     while (my $configline=<$config>) {
1.448     albertel 8084: 	chomp($configline);
                   8085: 	if ($configline) {
                   8086: 	    my ($role,$perm)=split(/ /,$configline);
                   8087: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8088: 	}
1.11      www      8089:     }
1.448     albertel 8090:     close($config);
1.11      www      8091: }
                   8092: 
                   8093: # -------------------------------------------- Read plain texts for permissions
                   8094: {
1.448     albertel 8095:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8096: 
                   8097:     while (my $configline=<$config>) {
1.448     albertel 8098: 	chomp($configline);
                   8099: 	if ($configline) {
1.742     raeburn  8100: 	    my ($short,@plain)=split(/:/,$configline);
                   8101:             %{$prp{$short}} = ();
                   8102: 	    if (@plain > 0) {
                   8103:                 $prp{$short}{'std'} = $plain[0];
                   8104:                 for (my $i=1; $i<@plain; $i++) {
                   8105:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8106:                 }
                   8107:             }
1.448     albertel 8108: 	}
1.135     www      8109:     }
1.448     albertel 8110:     close($config);
1.135     www      8111: }
                   8112: 
                   8113: # ---------------------------------------------------------- Read package table
                   8114: {
1.448     albertel 8115:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8116: 
                   8117:     while (my $configline=<$config>) {
1.483     albertel 8118: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8119: 	chomp($configline);
                   8120: 	my ($short,$plain)=split(/:/,$configline);
                   8121: 	my ($pack,$name)=split(/\&/,$short);
                   8122: 	if ($plain ne '') {
                   8123: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8124: 	    $packagetab{$short}=$plain; 
                   8125: 	}
1.11      www      8126:     }
1.448     albertel 8127:     close($config);
1.329     matthew  8128: }
                   8129: 
                   8130: # ------------- set up temporary directory
                   8131: {
                   8132:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8133: 
1.11      www      8134: }
                   8135: 
1.794     albertel 8136: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8137: 				'compress_threshold'=> 20_000,
                   8138:  			        });
1.185     www      8139: 
1.281     www      8140: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8141: $dumpcount=0;
1.22      www      8142: 
1.163     harris41 8143: &logtouch();
1.672     albertel 8144: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8145: $readit=1;
1.564     albertel 8146:     {
                   8147: 	use integer;
                   8148: 	my $test=(2**32)+1;
1.568     albertel 8149: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8150: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8151:     }
1.195     www      8152: }
1.1       albertel 8153: }
1.179     www      8154: 
1.1       albertel 8155: 1;
1.191     harris41 8156: __END__
                   8157: 
1.243     albertel 8158: =pod
                   8159: 
1.191     harris41 8160: =head1 NAME
                   8161: 
1.243     albertel 8162: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8163: 
                   8164: =head1 SYNOPSIS
                   8165: 
1.243     albertel 8166: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8167: 
                   8168:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8169: 
1.243     albertel 8170: Common parameters:
                   8171: 
                   8172: =over 4
                   8173: 
                   8174: =item *
                   8175: 
                   8176: $uname : an internal username (if $cname expecting a course Id specifically)
                   8177: 
                   8178: =item *
                   8179: 
                   8180: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8181: 
                   8182: =item *
                   8183: 
                   8184: $symb : a resource instance identifier
                   8185: 
                   8186: =item *
                   8187: 
                   8188: $namespace : the name of a .db file that contains the data needed or
                   8189: being set.
                   8190: 
                   8191: =back
                   8192: 
1.394     bowersj2 8193: =head1 OVERVIEW
1.191     harris41 8194: 
1.394     bowersj2 8195: lonnet provides subroutines which interact with the
                   8196: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8197: about classes, users, and resources.
1.243     albertel 8198: 
                   8199: For many of these objects you can also use this to store data about
                   8200: them or modify them in various ways.
1.191     harris41 8201: 
1.394     bowersj2 8202: =head2 Symbs
1.191     harris41 8203: 
1.394     bowersj2 8204: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8205: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8206: map, the resource number of the resource in the map, and the URL of
                   8207: the resource itself. The latter is somewhat redundant, but might help
                   8208: if maps change.
                   8209: 
                   8210: An example is
                   8211: 
                   8212:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8213: 
                   8214: The respective map entry is
                   8215: 
                   8216:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8217:   title="Problem 2">
                   8218:  </resource>
                   8219: 
                   8220: Symbs are used by the random number generator, as well as to store and
                   8221: restore data specific to a certain instance of for example a problem.
                   8222: 
                   8223: =head2 Storing And Retrieving Data
                   8224: 
                   8225: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8226: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8227: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8228: is is the non-critical message twin of cstore. These functions are for
                   8229: handlers to store a perl hash to a user's permanent data space in an
                   8230: easy manner, and to retrieve it again on another call. It is expected
                   8231: that a handler would use this once at the beginning to retrieve data,
                   8232: and then again once at the end to send only the new data back.
                   8233: 
                   8234: The data is stored in the user's data directory on the user's
                   8235: homeserver under the ID of the course.
                   8236: 
                   8237: The hash that is returned by restore will have all of the previous
                   8238: value for all of the elements of the hash.
                   8239: 
                   8240: Example:
                   8241: 
                   8242:  #creating a hash
                   8243:  my %hash;
                   8244:  $hash{'foo'}='bar';
                   8245: 
                   8246:  #storing it
                   8247:  &Apache::lonnet::cstore(\%hash);
                   8248: 
                   8249:  #changing a value
                   8250:  $hash{'foo'}='notbar';
                   8251: 
                   8252:  #adding a new value
                   8253:  $hash{'bar'}='foo';
                   8254:  &Apache::lonnet::cstore(\%hash);
                   8255: 
                   8256:  #retrieving the hash
                   8257:  my %history=&Apache::lonnet::restore();
                   8258: 
                   8259:  #print the hash
                   8260:  foreach my $key (sort(keys(%history))) {
                   8261:    print("\%history{$key} = $history{$key}");
                   8262:  }
                   8263: 
                   8264: Will print out:
1.191     harris41 8265: 
1.394     bowersj2 8266:  %history{1:foo} = bar
                   8267:  %history{1:keys} = foo:timestamp
                   8268:  %history{1:timestamp} = 990455579
                   8269:  %history{2:bar} = foo
                   8270:  %history{2:foo} = notbar
                   8271:  %history{2:keys} = foo:bar:timestamp
                   8272:  %history{2:timestamp} = 990455580
                   8273:  %history{bar} = foo
                   8274:  %history{foo} = notbar
                   8275:  %history{timestamp} = 990455580
                   8276:  %history{version} = 2
                   8277: 
                   8278: Note that the special hash entries C<keys>, C<version> and
                   8279: C<timestamp> were added to the hash. C<version> will be equal to the
                   8280: total number of versions of the data that have been stored. The
                   8281: C<timestamp> attribute will be the UNIX time the hash was
                   8282: stored. C<keys> is available in every historical section to list which
                   8283: keys were added or changed at a specific historical revision of a
                   8284: hash.
                   8285: 
                   8286: B<Warning>: do not store the hash that restore returns directly. This
                   8287: will cause a mess since it will restore the historical keys as if the
                   8288: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8289: 
1.394     bowersj2 8290: Calling convention:
1.191     harris41 8291: 
1.394     bowersj2 8292:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8293:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8294: 
1.394     bowersj2 8295: For more detailed information, see lonnet specific documentation.
1.191     harris41 8296: 
1.394     bowersj2 8297: =head1 RETURN MESSAGES
1.191     harris41 8298: 
1.394     bowersj2 8299: =over 4
1.191     harris41 8300: 
1.394     bowersj2 8301: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8302: 
1.394     bowersj2 8303: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8304: when the connection is brought back up
1.191     harris41 8305: 
1.394     bowersj2 8306: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8307: for later delivery
1.191     harris41 8308: 
1.394     bowersj2 8309: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8310: 
1.394     bowersj2 8311: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8312: that was requested
1.191     harris41 8313: 
1.243     albertel 8314: =back
1.191     harris41 8315: 
1.243     albertel 8316: =head1 PUBLIC SUBROUTINES
1.191     harris41 8317: 
1.243     albertel 8318: =head2 Session Environment Functions
1.191     harris41 8319: 
1.243     albertel 8320: =over 4
1.191     harris41 8321: 
1.394     bowersj2 8322: =item * 
                   8323: X<appenv()>
                   8324: B<appenv(%hash)>: the value of %hash is written to
                   8325: the user envirnoment file, and will be restored for each access this
1.620     albertel 8326: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8327: process
1.191     harris41 8328: 
                   8329: =item *
1.394     bowersj2 8330: X<delenv()>
                   8331: B<delenv($regexp)>: removes all items from the session
                   8332: environment file that matches the regular expression in $regexp. The
1.620     albertel 8333: values are also delted from the current processes %env.
1.191     harris41 8334: 
1.795     albertel 8335: =item * get_env_multiple($name) 
                   8336: 
                   8337: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8338: values may be defined and end up as an array ref.
                   8339: 
                   8340: returns an array of values
                   8341: 
1.243     albertel 8342: =back
                   8343: 
                   8344: =head2 User Information
1.191     harris41 8345: 
1.243     albertel 8346: =over 4
1.191     harris41 8347: 
                   8348: =item *
1.394     bowersj2 8349: X<queryauthenticate()>
                   8350: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8351: authentication scheme
                   8352: 
                   8353: =item *
1.394     bowersj2 8354: X<authenticate()>
                   8355: B<authenticate($uname,$upass,$udom)>: try to
                   8356: authenticate user from domain's lib servers (first use the current
                   8357: one). C<$upass> should be the users password.
1.191     harris41 8358: 
                   8359: =item *
1.394     bowersj2 8360: X<homeserver()>
                   8361: B<homeserver($uname,$udom)>: find the server which has
                   8362: the user's directory and files (there must be only one), this caches
                   8363: the answer, and also caches if there is a borken connection.
1.191     harris41 8364: 
                   8365: =item *
1.394     bowersj2 8366: X<idget()>
                   8367: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8368: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8369: username, and only 1 username per ID in a specific domain) (returns
                   8370: hash: id=>name,id=>name)
1.191     harris41 8371: 
                   8372: =item *
1.394     bowersj2 8373: X<idrget()>
                   8374: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8375: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8376: 
                   8377: =item *
1.394     bowersj2 8378: X<idput()>
                   8379: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8380: 
                   8381: =item *
1.394     bowersj2 8382: X<rolesinit()>
                   8383: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8384: 
                   8385: =item *
1.551     albertel 8386: X<getsection()>
                   8387: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8388: course $cname, return section name/number or '' for "not in course"
                   8389: and '-1' for "no section"
                   8390: 
                   8391: =item *
1.394     bowersj2 8392: X<userenvironment()>
                   8393: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8394: passed in @what from the requested user's environment, returns a hash
                   8395: 
1.858     raeburn  8396: =item * 
                   8397: X<userlog_query()>
1.859     albertel 8398: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8399: activity.log file. %filters defines filters applied when parsing the
                   8400: log file. These can be start or end timestamps, or the type of action
                   8401: - log to look for Login or Logout events, check for Checkin or
                   8402: Checkout, role for role selection. The response is in the form
                   8403: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8404: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8405: 
1.243     albertel 8406: =back
                   8407: 
                   8408: =head2 User Roles
                   8409: 
                   8410: =over 4
                   8411: 
                   8412: =item *
                   8413: 
1.810     raeburn  8414: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8415:  F: full access
                   8416:  U,I,K: authentication modes (cxx only)
                   8417:  '': forbidden
                   8418:  1: user needs to choose course
                   8419:  2: browse allowed
1.766     albertel 8420:  A: passphrase authentication needed
1.243     albertel 8421: 
                   8422: =item *
                   8423: 
                   8424: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8425: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8426: and course level
                   8427: 
                   8428: =item *
                   8429: 
                   8430: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8431: explanation of a user role term
                   8432: 
1.832     raeburn  8433: =item *
                   8434: 
1.858     raeburn  8435: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8436: All arguments are optional. Returns a hash of a roles, either for
                   8437: co-author/assistant author roles for a user's Construction Space
                   8438: (default), or if $context is 'user', roles for the user himself,
                   8439: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8440: and value is set to colon-separated start and end times for the role.
                   8441: If no username and domain are specified, will default to current
                   8442: user/domain. Types, roles, and roledoms are references to arrays,
                   8443: of role statuses (active, future or previous), roles 
                   8444: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8445: to restrict the list of roles reported. If no array ref is 
                   8446: provided for types, will default to return only active roles.
1.834     albertel 8447: 
1.243     albertel 8448: =back
                   8449: 
                   8450: =head2 User Modification
                   8451: 
                   8452: =over 4
                   8453: 
                   8454: =item *
                   8455: 
                   8456: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8457: user for the level given by URL.  Optional start and end dates (leave empty
                   8458: string or zero for "no date")
1.191     harris41 8459: 
                   8460: =item *
                   8461: 
1.243     albertel 8462: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8463: change a users, password, possible return values are: ok,
                   8464: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8465: refused
1.191     harris41 8466: 
                   8467: =item *
                   8468: 
1.243     albertel 8469: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8470: 
                   8471: =item *
                   8472: 
1.243     albertel 8473: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8474: modify user
1.191     harris41 8475: 
                   8476: =item *
                   8477: 
1.286     matthew  8478: modifystudent
                   8479: 
                   8480: modify a students enrollment and identification information.
                   8481: The course id is resolved based on the current users environment.  
                   8482: This means the envoking user must be a course coordinator or otherwise
                   8483: associated with a course.
                   8484: 
1.297     matthew  8485: This call is essentially a wrapper for lonnet::modifyuser and
                   8486: lonnet::modify_student_enrollment
1.286     matthew  8487: 
                   8488: Inputs: 
                   8489: 
                   8490: =over 4
                   8491: 
                   8492: =item B<$udom> Students loncapa domain
                   8493: 
                   8494: =item B<$uname> Students loncapa login name
                   8495: 
                   8496: =item B<$uid> Students id/student number
                   8497: 
                   8498: =item B<$umode> Students authentication mode
                   8499: 
                   8500: =item B<$upass> Students password
                   8501: 
                   8502: =item B<$first> Students first name
                   8503: 
                   8504: =item B<$middle> Students middle name
                   8505: 
                   8506: =item B<$last> Students last name
                   8507: 
                   8508: =item B<$gene> Students generation
                   8509: 
                   8510: =item B<$usec> Students section in course
                   8511: 
                   8512: =item B<$end> Unix time of the roles expiration
                   8513: 
                   8514: =item B<$start> Unix time of the roles start date
                   8515: 
                   8516: =item B<$forceid> If defined, allow $uid to be changed
                   8517: 
                   8518: =item B<$desiredhome> server to use as home server for student
                   8519: 
                   8520: =back
1.297     matthew  8521: 
                   8522: =item *
                   8523: 
                   8524: modify_student_enrollment
                   8525: 
                   8526: Change a students enrollment status in a class.  The environment variable
                   8527: 'role.request.course' must be defined for this function to proceed.
                   8528: 
                   8529: Inputs:
                   8530: 
                   8531: =over 4
                   8532: 
                   8533: =item $udom, students domain
                   8534: 
                   8535: =item $uname, students name
                   8536: 
                   8537: =item $uid, students user id
                   8538: 
                   8539: =item $first, students first name
                   8540: 
                   8541: =item $middle
                   8542: 
                   8543: =item $last
                   8544: 
                   8545: =item $gene
                   8546: 
                   8547: =item $usec
                   8548: 
                   8549: =item $end
                   8550: 
                   8551: =item $start
                   8552: 
                   8553: =back
                   8554: 
1.191     harris41 8555: 
                   8556: =item *
                   8557: 
1.243     albertel 8558: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8559: custom role; give a custom role to a user for the level given by URL.  Specify
                   8560: name and domain of role author, and role name
1.191     harris41 8561: 
                   8562: =item *
                   8563: 
1.243     albertel 8564: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8565: 
                   8566: =item *
                   8567: 
1.243     albertel 8568: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8569: 
                   8570: =back
                   8571: 
                   8572: =head2 Course Infomation
                   8573: 
                   8574: =over 4
1.191     harris41 8575: 
                   8576: =item *
                   8577: 
1.631     albertel 8578: coursedescription($courseid) : returns a hash of information about the
                   8579: specified course id, including all environment settings for the
                   8580: course, the description of the course will be in the hash under the
                   8581: key 'description'
1.191     harris41 8582: 
                   8583: =item *
                   8584: 
1.624     albertel 8585: resdata($name,$domain,$type,@which) : request for current parameter
                   8586: setting for a specific $type, where $type is either 'course' or 'user',
                   8587: @what should be a list of parameters to ask about. This routine caches
                   8588: answers for 5 minutes.
1.243     albertel 8589: 
1.877     foxr     8590: =item *
                   8591: 
                   8592: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8593: data base, returning a hash that is keyed by the resource name and has
                   8594: values that are the resource value.  I believe that the timestamps and
                   8595: versions are also returned.
                   8596: 
                   8597: 
1.243     albertel 8598: =back
                   8599: 
                   8600: =head2 Course Modification
                   8601: 
                   8602: =over 4
1.191     harris41 8603: 
                   8604: =item *
                   8605: 
1.243     albertel 8606: writecoursepref($courseid,%prefs) : write preferences (environment
                   8607: database) for a course
1.191     harris41 8608: 
                   8609: =item *
                   8610: 
1.243     albertel 8611: createcourse($udom,$description,$url) : make/modify course
                   8612: 
                   8613: =back
                   8614: 
                   8615: =head2 Resource Subroutines
                   8616: 
                   8617: =over 4
1.191     harris41 8618: 
                   8619: =item *
                   8620: 
1.243     albertel 8621: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8622: 
                   8623: =item *
                   8624: 
1.243     albertel 8625: repcopy($filename) : subscribes to the requested file, and attempts to
                   8626: replicate from the owning library server, Might return
1.607     raeburn  8627: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8628: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8629: resource. Expects the local filesystem pathname
                   8630: (/home/httpd/html/res/....)
                   8631: 
                   8632: =back
                   8633: 
                   8634: =head2 Resource Information
                   8635: 
                   8636: =over 4
1.191     harris41 8637: 
                   8638: =item *
                   8639: 
1.243     albertel 8640: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8641: a vairety of different possible values, $varname should be a request
                   8642: string, and the other parameters can be used to specify who and what
                   8643: one is asking about.
                   8644: 
                   8645: Possible values for $varname are environment.lastname (or other item
                   8646: from the envirnment hash), user.name (or someother aspect about the
                   8647: user), resource.0.maxtries (or some other part and parameter of a
                   8648: resource)
1.204     albertel 8649: 
                   8650: =item *
                   8651: 
1.243     albertel 8652: directcondval($number) : get current value of a condition; reads from a state
                   8653: string
1.204     albertel 8654: 
                   8655: =item *
                   8656: 
1.243     albertel 8657: condval($condidx) : value of condition index based on state
1.204     albertel 8658: 
                   8659: =item *
                   8660: 
1.243     albertel 8661: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8662: resource's metadata, $what should be either a specific key, or either
                   8663: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8664: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8665: 
                   8666: this function automatically caches all requests
1.191     harris41 8667: 
                   8668: =item *
                   8669: 
1.243     albertel 8670: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8671: network of library servers; returns file handle of where SQL and regex results
                   8672: will be stored for query
1.191     harris41 8673: 
                   8674: =item *
                   8675: 
1.243     albertel 8676: symbread($filename) : return symbolic list entry (filename argument optional);
                   8677: returns the data handle
1.191     harris41 8678: 
                   8679: =item *
                   8680: 
1.243     albertel 8681: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8682: a possible symb for the URL in $thisfn, and if is an encryypted
                   8683: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8684: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8685: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8686: 
1.191     harris41 8687: 
                   8688: =item *
                   8689: 
1.243     albertel 8690: symbclean($symb) : removes versions numbers from a symb, returns the
                   8691: cleaned symb
1.191     harris41 8692: 
                   8693: =item *
                   8694: 
1.243     albertel 8695: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8696: course map, user must be in a course for it to work.
1.191     harris41 8697: 
                   8698: =item *
                   8699: 
1.243     albertel 8700: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8701: 
                   8702: =item *
                   8703: 
1.243     albertel 8704: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8705: a random seed, all arguments are optional, if they aren't sent it uses the
                   8706: environment to derive them. Note: if symb isn't sent and it can't get one
                   8707: from &symbread it will use the current time as its return value
1.191     harris41 8708: 
                   8709: =item *
                   8710: 
1.243     albertel 8711: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8712: unfakeable, receipt
1.191     harris41 8713: 
                   8714: =item *
                   8715: 
1.620     albertel 8716: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8717: 
                   8718: =item *
                   8719: 
1.243     albertel 8720: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8721: 
                   8722: =item *
                   8723: 
1.243     albertel 8724: 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 8725: 
                   8726: =item *
                   8727: 
1.243     albertel 8728: 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 8729: 
                   8730: =item *
                   8731: 
1.243     albertel 8732: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8733: 
                   8734: =item *
                   8735: 
1.243     albertel 8736: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8737: forcing spreadsheet to reevaluate the resource scores next time.
                   8738: 
                   8739: =back
                   8740: 
                   8741: =head2 Storing/Retreiving Data
                   8742: 
                   8743: =over 4
1.191     harris41 8744: 
                   8745: =item *
                   8746: 
1.243     albertel 8747: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8748: for this url; hashref needs to be given and should be a \%hashname; the
                   8749: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8750: be derived from the env
1.191     harris41 8751: 
                   8752: =item *
                   8753: 
1.243     albertel 8754: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8755: uses critical subroutine
1.191     harris41 8756: 
                   8757: =item *
                   8758: 
1.243     albertel 8759: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8760: all args are optional
1.191     harris41 8761: 
                   8762: =item *
                   8763: 
1.717     albertel 8764: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8765: dumps the complete (or key matching regexp) namespace into a hash
                   8766: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8767: normally &store()ed into
                   8768: 
                   8769: $range should be either an integer '100' (give me the first 100
                   8770:                                            matching records)
                   8771:               or be  two integers sperated by a - with no spaces
                   8772:                  '30-50' (give me the 30th through the 50th matching
                   8773:                           records)
                   8774: 
                   8775: 
                   8776: =item *
                   8777: 
                   8778: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8779: replaces a &store() version of data with a replacement set of data
                   8780: for a particular resource in a namespace passed in the $storehash hash 
                   8781: reference
                   8782: 
                   8783: =item *
                   8784: 
1.243     albertel 8785: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8786: works very similar to store/cstore, but all data is stored in a
                   8787: temporary location and can be reset using tmpreset, $storehash should
                   8788: be a hash reference, returns nothing on success
1.191     harris41 8789: 
                   8790: =item *
                   8791: 
1.243     albertel 8792: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8793: similar to restore, but all data is stored in a temporary location and
                   8794: can be reset using tmpreset. Returns a hash of values on success,
                   8795: error string otherwise.
1.191     harris41 8796: 
                   8797: =item *
                   8798: 
1.243     albertel 8799: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8800: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8801: 
                   8802: =item *
                   8803: 
1.243     albertel 8804: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8805: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8806: 
                   8807: =item *
                   8808: 
1.243     albertel 8809: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8810: namesp ($udom and $uname are optional)
1.191     harris41 8811: 
                   8812: =item *
                   8813: 
1.702     albertel 8814: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8815: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8816: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8817: 
1.702     albertel 8818: $range should be either an integer '100' (give me the first 100
                   8819:                                            matching records)
                   8820:               or be  two integers sperated by a - with no spaces
                   8821:                  '30-50' (give me the 30th through the 50th matching
                   8822:                           records)
1.449     matthew  8823: =item *
                   8824: 
                   8825: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8826: $store can be a scalar, an array reference, or if the amount to be 
                   8827: incremented is > 1, a hash reference.
                   8828: 
                   8829: ($udom and $uname are optional)
1.191     harris41 8830: 
                   8831: =item *
                   8832: 
1.243     albertel 8833: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8834: ($udom and $uname are optional)
1.191     harris41 8835: 
                   8836: =item *
                   8837: 
1.243     albertel 8838: cput($namespace,$storehash,$udom,$uname) : critical put
                   8839: ($udom and $uname are optional)
1.191     harris41 8840: 
                   8841: =item *
                   8842: 
1.748     albertel 8843: newput($namespace,$storehash,$udom,$uname) :
                   8844: 
                   8845: Attempts to store the items in the $storehash, but only if they don't
                   8846: currently exist, if this succeeds you can be certain that you have 
                   8847: successfully created a new key value pair in the $namespace db.
                   8848: 
                   8849: 
                   8850: Args:
                   8851:  $namespace: name of database to store values to
                   8852:  $storehash: hashref to store to the db
                   8853:  $udom: (optional) domain of user containing the db
                   8854:  $uname: (optional) name of user caontaining the db
                   8855: 
                   8856: Returns:
                   8857:  'ok' -> succeeded in storing all keys of $storehash
                   8858:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8859:                         least <key> already existed in the db (other
                   8860:                         requested keys may also already exist)
                   8861:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8862:  'con_lost' -> unable to contact request server
                   8863:  'refused' -> action was not allowed by remote machine
                   8864: 
                   8865: 
                   8866: =item *
                   8867: 
1.243     albertel 8868: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8869: reference filled in from namesp (encrypts the return communication)
                   8870: ($udom and $uname are optional)
1.191     harris41 8871: 
                   8872: =item *
                   8873: 
1.243     albertel 8874: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8875: critical subroutine
                   8876: 
1.806     raeburn  8877: =item *
                   8878: 
1.860     raeburn  8879: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   8880: array reference filled in from namespace found in domain level on either
                   8881: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  8882: 
                   8883: =item *
                   8884: 
1.860     raeburn  8885: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   8886: domain level either on specified domain server ($uhome) or primary domain 
                   8887: server ($udom and $uhome are optional)
1.806     raeburn  8888: 
1.243     albertel 8889: =back
                   8890: 
                   8891: =head2 Network Status Functions
                   8892: 
                   8893: =over 4
1.191     harris41 8894: 
                   8895: =item *
                   8896: 
                   8897: dirlist($uri) : return directory list based on URI
                   8898: 
                   8899: =item *
                   8900: 
1.243     albertel 8901: spareserver() : find server with least workload from spare.tab
                   8902: 
                   8903: =back
                   8904: 
                   8905: =head2 Apache Request
                   8906: 
                   8907: =over 4
1.191     harris41 8908: 
                   8909: =item *
                   8910: 
1.243     albertel 8911: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8912: localhost, posts hash
                   8913: 
                   8914: =back
                   8915: 
                   8916: =head2 Data to String to Data
                   8917: 
                   8918: =over 4
1.191     harris41 8919: 
                   8920: =item *
                   8921: 
1.243     albertel 8922: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8923: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8924: 
                   8925: =item *
                   8926: 
1.243     albertel 8927: hashref2str($hashref) : convert a hashref into a string complete with
                   8928: escaping and '=' and '&' separators, supports elements that are
                   8929: arrayrefs and hashrefs
1.191     harris41 8930: 
                   8931: =item *
                   8932: 
1.243     albertel 8933: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8934: with escaping and '&' separators, supports elements that are arrayrefs
                   8935: and hashrefs
1.191     harris41 8936: 
                   8937: =item *
                   8938: 
1.243     albertel 8939: str2hash($string) : convert string to hash using unescaping and
                   8940: splitting on '=' and '&', supports elements that are arrayrefs and
                   8941: hashrefs
1.191     harris41 8942: 
                   8943: =item *
                   8944: 
1.243     albertel 8945: str2array($string) : convert string to hash using unescaping and
                   8946: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8947: 
                   8948: =back
                   8949: 
                   8950: =head2 Logging Routines
                   8951: 
                   8952: =over 4
                   8953: 
                   8954: These routines allow one to make log messages in the lonnet.log and
                   8955: lonnet.perm logfiles.
1.191     harris41 8956: 
                   8957: =item *
                   8958: 
1.243     albertel 8959: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8960: 
                   8961: =item *
                   8962: 
1.243     albertel 8963: logthis() : append message to the normal lonnet.log file, it gets
                   8964: preiodically rolled over and deleted.
1.191     harris41 8965: 
                   8966: =item *
                   8967: 
1.243     albertel 8968: logperm() : append a permanent message to lonnet.perm.log, this log
                   8969: file never gets deleted by any automated portion of the system, only
                   8970: messages of critical importance should go in here.
                   8971: 
                   8972: =back
                   8973: 
                   8974: =head2 General File Helper Routines
                   8975: 
                   8976: =over 4
1.191     harris41 8977: 
                   8978: =item *
                   8979: 
1.481     raeburn  8980: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8981: (a) files in /uploaded
                   8982:   (i) If a local copy of the file exists - 
                   8983:       compares modification date of local copy with last-modified date for 
                   8984:       definitive version stored on home server for course. If local copy is 
                   8985:       stale, requests a new version from the home server and stores it. 
                   8986:       If the original has been removed from the home server, then local copy 
                   8987:       is unlinked.
                   8988:   (ii) If local copy does not exist -
                   8989:       requests the file from the home server and stores it. 
                   8990:   
                   8991:   If $caller is 'uploadrep':  
                   8992:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8993:     for request for files originally uploaded via DOCS. 
                   8994:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8995:   
                   8996:   Otherwise:
                   8997:      This indicates a call from the content generation phase of the request.
                   8998:      -  returns the entire contents of the file or -1.
                   8999:      
                   9000: (b) files in /res
                   9001:    - returns the entire contents of a file or -1; 
                   9002:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9003: 
1.712     albertel 9004: 
                   9005: =item *
                   9006: 
                   9007: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9008:                   reference
                   9009: 
                   9010: returns either a stat() list of data about the file or an empty list
                   9011: if the file doesn't exist or couldn't find out about it (connection
                   9012: problems or user unknown)
                   9013: 
1.191     harris41 9014: =item *
                   9015: 
1.243     albertel 9016: filelocation($dir,$file) : returns file system location of a file
                   9017: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9018: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9019: and a file of ../bob will become /a/bob)
1.191     harris41 9020: 
                   9021: =item *
                   9022: 
                   9023: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9024: filelocation except for hrefs
                   9025: 
                   9026: =item *
                   9027: 
                   9028: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9029: 
1.243     albertel 9030: =back
                   9031: 
1.608     albertel 9032: =head2 Usererfile file routines (/uploaded*)
                   9033: 
                   9034: =over 4
                   9035: 
                   9036: =item *
                   9037: 
                   9038: userfileupload(): main rotine for putting a file in a user or course's
                   9039:                   filespace, arguments are,
                   9040: 
1.620     albertel 9041:  formname - required - this is the name of the element in $env where the
1.608     albertel 9042:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9043:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9044:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9045:  coursedoc - if true, store the file in the course of the active role
                   9046:              of the current user
                   9047:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9048:          if undefined, it will be placed in "unknown"
                   9049: 
                   9050:  (This routine calls clean_filename() to remove any dangerous
                   9051:  characters from the filename, and then calls finuserfileupload() to
                   9052:  complete the transaction)
                   9053: 
                   9054:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9055:  and /adm/notfound.html if unsuccessful
                   9056: 
                   9057: =item *
                   9058: 
                   9059: clean_filename(): routine for cleaing a filename up for storage in
                   9060:                  userfile space, argument is:
                   9061: 
                   9062:  filename - proposed filename
                   9063: 
                   9064: returns: the new clean filename
                   9065: 
                   9066: =item *
                   9067: 
                   9068: finishuserfileupload(): routine that creaes and sends the file to
                   9069: userspace, probably shouldn't be called directly
                   9070: 
                   9071:   docuname: username or courseid of destination for the file
                   9072:   docudom: domain of user/course of destination for the file
                   9073:   formname: same as for userfileupload()
                   9074:   fname: filename (inculding subdirectories) for the file
                   9075: 
                   9076:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9077:  and /adm/notfound.html if unsuccessful
                   9078: 
                   9079: =item *
                   9080: 
                   9081: renameuserfile(): renames an existing userfile to a new name
                   9082: 
                   9083:   Args:
                   9084:    docuname: username or courseid of destination for the file
                   9085:    docudom: domain of user/course of destination for the file
                   9086:    old: current file name (including any subdirs under userfiles)
                   9087:    new: desired file name (including any subdirs under userfiles)
                   9088: 
                   9089: =item *
                   9090: 
                   9091: mkdiruserfile(): creates a directory is a userfiles dir
                   9092: 
                   9093:   Args:
                   9094:    docuname: username or courseid of destination for the file
                   9095:    docudom: domain of user/course of destination for the file
                   9096:    dir: dir to create (including any subdirs under userfiles)
                   9097: 
                   9098: =item *
                   9099: 
                   9100: removeuserfile(): removes a file that exists in userfiles
                   9101: 
                   9102:   Args:
                   9103:    docuname: username or courseid of destination for the file
                   9104:    docudom: domain of user/course of destination for the file
                   9105:    fname: filname to delete (including any subdirs under userfiles)
                   9106: 
                   9107: =item *
                   9108: 
                   9109: removeuploadedurl(): convience function for removeuserfile()
                   9110: 
                   9111:   Args:
                   9112:    url:  a full /uploaded/... url to delete
                   9113: 
1.747     albertel 9114: =item * 
                   9115: 
                   9116: get_portfile_permissions():
                   9117:   Args:
                   9118:     domain: domain of user or course contain the portfolio files
                   9119:     user: name of user or num of course contain the portfolio files
                   9120:   Returns:
                   9121:     hashref of a dump of the proper file_permissions.db
                   9122:    
                   9123: 
                   9124: =item * 
                   9125: 
                   9126: get_access_controls():
                   9127: 
                   9128: Args:
                   9129:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9130:   group: (optional) the group you want the files associated with
                   9131:   file: (optional) the file you want access info on
                   9132: 
                   9133: Returns:
1.749     raeburn  9134:     a hash (keys are file names) of hashes containing
                   9135:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9136:         values are XML containing access control settings (see below) 
1.747     albertel 9137: 
                   9138: Internal notes:
                   9139: 
1.749     raeburn  9140:  access controls are stored in file_permissions.db as key=value pairs.
                   9141:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9142:         where scope -> public,guest,course,group,domains or users.
                   9143:               end -> UNIX time for end of access (0 -> no end date)
                   9144:               start -> UNIX time for start of access
                   9145: 
                   9146:     value -> XML description of access control
                   9147:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9148:             <start></start>
                   9149:             <end></end>
                   9150: 
                   9151:             <password></password>  for scope type = guest
                   9152: 
                   9153:             <domain></domain>     for scope type = course or group
                   9154:             <number></number>
                   9155:             <roles id="">
                   9156:              <role></role>
                   9157:              <access></access>
                   9158:              <section></section>
                   9159:              <group></group>
                   9160:             </roles>
                   9161: 
                   9162:             <dom></dom>         for scope type = domains
                   9163: 
                   9164:             <users>             for scope type = users
                   9165:              <user>
                   9166:               <uname></uname>
                   9167:               <udom></udom>
                   9168:              </user>
                   9169:             </users>
                   9170:            </scope> 
                   9171:               
                   9172:  Access data is also aggregated for each file in an additional key=value pair:
                   9173:  key -> path to file/file_name\0accesscontrol 
                   9174:  value -> reference to hash
                   9175:           hash contains key = value pairs
                   9176:           where key = uniqueID:scope_end_start
                   9177:                 value = UNIX time record was last updated
                   9178: 
                   9179:           Used to improve speed of look-ups of access controls for each file.  
                   9180:  
                   9181:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9182: 
                   9183: modify_access_controls():
                   9184: 
                   9185: Modifies access controls for a portfolio file
                   9186: Args
                   9187: 1. file name
                   9188: 2. reference to hash of required changes,
                   9189: 3. domain
                   9190: 4. username
                   9191:   where domain,username are the domain of the portfolio owner 
                   9192:   (either a user or a course) 
                   9193: 
                   9194: Returns:
                   9195: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9196: 2. result of deletions ('ok' or 'error', with error message).
                   9197: 3. reference to hash of any new or updated access controls.
                   9198: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9199:    key = integer (inbound ID)
                   9200:    value = uniqueID  
1.747     albertel 9201: 
1.608     albertel 9202: =back
                   9203: 
1.243     albertel 9204: =head2 HTTP Helper Routines
                   9205: 
                   9206: =over 4
                   9207: 
1.191     harris41 9208: =item *
                   9209: 
                   9210: escape() : unpack non-word characters into CGI-compatible hex codes
                   9211: 
                   9212: =item *
                   9213: 
                   9214: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9215: 
1.243     albertel 9216: =back
                   9217: 
                   9218: =head1 PRIVATE SUBROUTINES
                   9219: 
                   9220: =head2 Underlying communication routines (Shouldn't call)
                   9221: 
                   9222: =over 4
                   9223: 
                   9224: =item *
                   9225: 
                   9226: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9227: 
                   9228: =item *
                   9229: 
                   9230: reply() : uses subreply to send a message to remote machine, logs all failures
                   9231: 
                   9232: =item *
                   9233: 
                   9234: critical() : passes a critical message to another server; if cannot
                   9235: get through then place message in connection buffer directory and
                   9236: returns con_delayed, if incapable of saving message, returns
                   9237: con_failed
                   9238: 
                   9239: =item *
                   9240: 
                   9241: reconlonc() : tries to reconnect lonc client processes.
                   9242: 
                   9243: =back
                   9244: 
                   9245: =head2 Resource Access Logging
                   9246: 
                   9247: =over 4
                   9248: 
                   9249: =item *
                   9250: 
                   9251: flushcourselogs() : flush (save) buffer logs and access logs
                   9252: 
                   9253: =item *
                   9254: 
                   9255: courselog($what) : save message for course in hash
                   9256: 
                   9257: =item *
                   9258: 
                   9259: courseacclog($what) : save message for course using &courselog().  Perform
                   9260: special processing for specific resource types (problems, exams, quizzes, etc).
                   9261: 
1.191     harris41 9262: =item *
                   9263: 
                   9264: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9265: as a PerlChildExitHandler
1.243     albertel 9266: 
                   9267: =back
                   9268: 
                   9269: =head2 Other
                   9270: 
                   9271: =over 4
                   9272: 
                   9273: =item *
                   9274: 
                   9275: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9276: 
                   9277: =back
                   9278: 
                   9279: =cut
1.877     foxr     9280: 

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