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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.910.2.2! albertel    4: # $Id: lonnet.pm,v 1.910.2.1 2007/09/25 00:26:20 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: }
1.910.2.2! albertel  585: 
        !           586: # --------------------------- ask offload servers if user already has a session
        !           587: sub find_existing_session {
        !           588:     my ($udom,$uname) = @_;
        !           589:     foreach my $try_server (@{ $spareid{'primary'} },
        !           590: 			    @{ $spareid{'default'} }) {
        !           591: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
        !           592:     }
        !           593:     return;
        !           594: }
        !           595: 
        !           596: # -------------------------------- ask if server already has a session for user
        !           597: sub has_user_session {
        !           598:     my ($lonid,$udom,$uname) = @_;
        !           599:     my $result = &reply(join(':','userhassession',
        !           600: 			     map {&escape($_)} ($udom,$uname)),$lonid);
        !           601:     return 1 if ($result eq 'ok');
        !           602: 
        !           603:     return 0;
        !           604: }
        !           605: 
1.202     matthew   606: # --------------------------------------------- Try to change a user's password
                    607: 
                    608: sub changepass {
1.799     raeburn   609:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   610:     $currentpass = &escape($currentpass);
                    611:     $newpass     = &escape($newpass);
1.799     raeburn   612:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   613: 		       $server);
                    614:     if (! $answer) {
                    615: 	&logthis("No reply on password change request to $server ".
                    616: 		 "by $uname in domain $udom.");
                    617:     } elsif ($answer =~ "^ok") {
                    618:         &logthis("$uname in $udom successfully changed their password ".
                    619: 		 "on $server.");
                    620:     } elsif ($answer =~ "^pwchange_failure") {
                    621: 	&logthis("$uname in $udom was unable to change their password ".
                    622: 		 "on $server.  The action was blocked by either lcpasswd ".
                    623: 		 "or pwchange");
                    624:     } elsif ($answer =~ "^non_authorized") {
                    625:         &logthis("$uname in $udom did not get their password correct when ".
                    626: 		 "attempting to change it on $server.");
                    627:     } elsif ($answer =~ "^auth_mode_error") {
                    628:         &logthis("$uname in $udom attempted to change their password despite ".
                    629: 		 "not being locally or internally authenticated on $server.");
                    630:     } elsif ($answer =~ "^unknown_user") {
                    631:         &logthis("$uname in $udom attempted to change their password ".
                    632: 		 "on $server but were unable to because $server is not ".
                    633: 		 "their home server.");
                    634:     } elsif ($answer =~ "^refused") {
                    635: 	&logthis("$server refused to change $uname in $udom password because ".
                    636: 		 "it was sent an unencrypted request to change the password.");
                    637:     }
                    638:     return $answer;
1.1       albertel  639: }
                    640: 
1.169     harris41  641: # ----------------------- Try to determine user's current authentication scheme
                    642: 
                    643: sub queryauthenticate {
                    644:     my ($uname,$udom)=@_;
1.456     albertel  645:     my $uhome=&homeserver($uname,$udom);
                    646:     if (!$uhome) {
                    647: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    648: 	return 'no_host';
                    649:     }
                    650:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    651:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    652: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  653:     }
1.456     albertel  654:     return $answer;
1.169     harris41  655: }
                    656: 
1.1       albertel  657: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       658: 
1.1       albertel  659: sub authenticate {
                    660:     my ($uname,$upass,$udom)=@_;
1.807     albertel  661:     $upass=&escape($upass);
                    662:     $uname= &LONCAPA::clean_username($uname);
1.836     www       663:     my $uhome=&homeserver($uname,$udom,1);
                    664:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    665: # Maybe the machine was offline and only re-appeared again recently?
                    666:         &reconlonc();
                    667: # One more
                    668: 	my $uhome=&homeserver($uname,$udom,1);
                    669: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    670: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    671: 	}
1.471     albertel  672: 	return 'no_host';
1.1       albertel  673:     }
1.471     albertel  674:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    675:     if ($answer eq 'authorized') {
                    676: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    677: 	return $uhome; 
                    678:     }
                    679:     if ($answer eq 'non_authorized') {
                    680: 	&logthis("User $uname at $udom rejected by $uhome");
                    681: 	return 'no_host'; 
1.9       www       682:     }
1.471     albertel  683:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  684:     return 'no_host';
                    685: }
                    686: 
                    687: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       688: 
1.599     albertel  689: my %homecache;
1.1       albertel  690: sub homeserver {
1.230     stredwic  691:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  692:     my $index="$uname:$udom";
1.426     albertel  693: 
1.599     albertel  694:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  695: 
                    696:     my %servers = &get_servers($udom,'library');
                    697:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  698:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  699: 		 exists($badServerCache{$tryserver}));
1.841     albertel  700: 
                    701: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    702: 	if ($answer eq 'found') {
                    703: 	    delete($badServerCache{$tryserver}); 
                    704: 	    return $homecache{$index}=$tryserver;
                    705: 	} elsif ($answer eq 'no_host') {
                    706: 	    $badServerCache{$tryserver}=1;
                    707: 	}
1.1       albertel  708:     }    
                    709:     return 'no_host';
1.70      www       710: }
                    711: 
                    712: # ------------------------------------- Find the usernames behind a list of IDs
                    713: 
                    714: sub idget {
                    715:     my ($udom,@ids)=@_;
                    716:     my %returnhash=();
                    717:     
1.841     albertel  718:     my %servers = &get_servers($udom,'library');
                    719:     foreach my $tryserver (keys(%servers)) {
                    720: 	my $idlist=join('&',@ids);
                    721: 	$idlist=~tr/A-Z/a-z/; 
                    722: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    723: 	my @answer=();
                    724: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    725: 	    @answer=split(/\&/,$reply);
                    726: 	}                    ;
                    727: 	my $i;
                    728: 	for ($i=0;$i<=$#ids;$i++) {
                    729: 	    if ($answer[$i]) {
                    730: 		$returnhash{$ids[$i]}=$answer[$i];
                    731: 	    } 
                    732: 	}
                    733:     } 
1.70      www       734:     return %returnhash;
                    735: }
                    736: 
                    737: # ------------------------------------- Find the IDs behind a list of usernames
                    738: 
                    739: sub idrget {
                    740:     my ($udom,@unames)=@_;
                    741:     my %returnhash=();
1.800     albertel  742:     foreach my $uname (@unames) {
                    743:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  744:     }
1.70      www       745:     return %returnhash;
                    746: }
                    747: 
                    748: # ------------------------------- Store away a list of names and associated IDs
                    749: 
                    750: sub idput {
                    751:     my ($udom,%ids)=@_;
                    752:     my %servers=();
1.800     albertel  753:     foreach my $uname (keys(%ids)) {
                    754: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    755:         my $uhom=&homeserver($uname,$udom);
1.70      www       756:         if ($uhom ne 'no_host') {
1.800     albertel  757:             my $id=&escape($ids{$uname});
1.70      www       758:             $id=~tr/A-Z/a-z/;
1.800     albertel  759:             my $esc_unam=&escape($uname);
1.70      www       760: 	    if ($servers{$uhom}) {
1.800     albertel  761: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       762:             } else {
1.800     albertel  763:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       764:             }
                    765:         }
1.191     harris41  766:     }
1.800     albertel  767:     foreach my $server (keys(%servers)) {
                    768:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  769:     }
1.344     www       770: }
                    771: 
1.806     raeburn   772: # ------------------------------------------- get items from domain db files   
                    773: 
                    774: sub get_dom {
1.860     raeburn   775:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   776:     my $items='';
                    777:     foreach my $item (@$storearr) {
                    778:         $items.=&escape($item).'&';
                    779:     }
                    780:     $items=~s/\&$//;
1.860     raeburn   781:     if (!$udom) {
                    782:         $udom=$env{'user.domain'};
                    783:         if (defined(&domain($udom,'primary'))) {
                    784:             $uhome=&domain($udom,'primary');
                    785:         } else {
1.874     albertel  786:             undef($uhome);
1.860     raeburn   787:         }
                    788:     } else {
                    789:         if (!$uhome) {
                    790:             if (defined(&domain($udom,'primary'))) {
                    791:                 $uhome=&domain($udom,'primary');
                    792:             }
                    793:         }
                    794:     }
                    795:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   796:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   797:         my %returnhash;
1.875     albertel  798:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   799:             return %returnhash;
                    800:         }
1.806     raeburn   801:         my @pairs=split(/\&/,$rep);
                    802:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    803:             return @pairs;
                    804:         }
                    805:         my $i=0;
                    806:         foreach my $item (@$storearr) {
                    807:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    808:             $i++;
                    809:         }
                    810:         return %returnhash;
                    811:     } else {
1.880     banghart  812:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   813:     }
                    814: }
                    815: 
                    816: # -------------------------------------------- put items in domain db files 
                    817: 
                    818: sub put_dom {
1.860     raeburn   819:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    820:     if (!$udom) {
                    821:         $udom=$env{'user.domain'};
                    822:         if (defined(&domain($udom,'primary'))) {
                    823:             $uhome=&domain($udom,'primary');
                    824:         } else {
1.874     albertel  825:             undef($uhome);
1.860     raeburn   826:         }
                    827:     } else {
                    828:         if (!$uhome) {
                    829:             if (defined(&domain($udom,'primary'))) {
                    830:                 $uhome=&domain($udom,'primary');
                    831:             }
                    832:         }
                    833:     } 
                    834:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   835:         my $items='';
                    836:         foreach my $item (keys(%$storehash)) {
                    837:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    838:         }
                    839:         $items=~s/\&$//;
                    840:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    841:     } else {
1.860     raeburn   842:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   843:     }
                    844: }
                    845: 
1.837     raeburn   846: sub retrieve_inst_usertypes {
                    847:     my ($udom) = @_;
                    848:     my (%returnhash,@order);
1.846     albertel  849:     if (defined(&domain($udom,'primary'))) {
                    850:         my $uhome=&domain($udom,'primary');
1.837     raeburn   851:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    852:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    853:         my @pairs=split(/\&/,$hashitems);
                    854:         foreach my $item (@pairs) {
                    855:             my ($key,$value)=split(/=/,$item,2);
                    856:             $key = &unescape($key);
                    857:             next if ($key =~ /^error: 2 /);
                    858:             $returnhash{$key}=&thaw_unescape($value);
                    859:         }
                    860:         my @esc_order = split(/\&/,$orderitems);
                    861:         foreach my $item (@esc_order) {
                    862:             push(@order,&unescape($item));
                    863:         }
                    864:     } else {
                    865:         &logthis("get_dom failed - no primary domain server for $udom");
                    866:     }
                    867:     return (\%returnhash,\@order);
                    868: }
                    869: 
1.868     raeburn   870: sub is_domainimage {
                    871:     my ($url) = @_;
                    872:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    873:         if (&domain($1) ne '') {
                    874:             return '1';
                    875:         }
                    876:     }
                    877:     return;
                    878: }
                    879: 
1.899     raeburn   880: sub inst_directory_query {
                    881:     my ($srch) = @_;
                    882:     my $udom = $srch->{'srchdomain'};
                    883:     my %results;
                    884:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   885:     my $outcome;
1.899     raeburn   886:     if ($homeserver ne '') {
1.904     albertel  887: 	my $queryid=&reply("querysend:instdirsearch:".
                    888: 			   &escape($srch->{'srchby'}).':'.
                    889: 			   &escape($srch->{'srchterm'}).':'.
                    890: 			   &escape($srch->{'srchtype'}),$homeserver);
                    891: 	my $host=&hostname($homeserver);
                    892: 	if ($queryid !~/^\Q$host\E\_/) {
                    893: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    894: 	    return;
                    895: 	}
                    896: 	my $response = &get_query_reply($queryid);
                    897: 	my $maxtries = 5;
                    898: 	my $tries = 1;
                    899: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    900: 	    $response = &get_query_reply($queryid);
                    901: 	    $tries ++;
                    902: 	}
                    903: 
                    904:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn   905:             if ($response eq 'unavailable') {
                    906:                 $outcome = $response;
                    907:             } else {
                    908:                 $outcome = 'ok';
                    909:                 my @matches = split(/\n/,$response);
                    910:                 foreach my $match (@matches) {
                    911:                     my ($key,$value) = split(/=/,$match);
                    912:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                    913:                 }
1.899     raeburn   914:             }
                    915:         }
                    916:     }
1.909     raeburn   917:     return ($outcome,%results);
1.899     raeburn   918: }
                    919: 
                    920: sub usersearch {
                    921:     my ($srch) = @_;
                    922:     my $dom = $srch->{'srchdomain'};
                    923:     my %results;
                    924:     my %libserv = &all_library();
                    925:     my $query = 'usersearch';
                    926:     foreach my $tryserver (keys(%libserv)) {
                    927:         if (&host_domain($tryserver) eq $dom) {
                    928:             my $host=&hostname($tryserver);
                    929:             my $queryid=
                    930:                 &reply("querysend:".&escape($query).':'.&escape($dom).':'.
                    931:                        &escape($srch->{'srchby'}).'%%'.
                    932:                        &escape($srch->{'srchtype'}).':'.
                    933:                        &escape($srch->{'srchterm'}),$tryserver);
                    934:             if ($queryid !~/^\Q$host\E\_/) {
                    935:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   936:                 next;
1.899     raeburn   937:             }
                    938:             my $reply = &get_query_reply($queryid);
                    939:             my $maxtries = 1;
                    940:             my $tries = 1;
                    941:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    942:                 $reply = &get_query_reply($queryid);
                    943:                 $tries ++;
                    944:             }
                    945:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    946:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    947:             } else {
1.900     albertel  948:                 my @matches = split(/&/,$reply);
1.899     raeburn   949:                 foreach my $match (@matches) {
                    950:                     my @items = split(/:/,$match);
                    951:                     my ($uname,$udom,%userhash);
                    952:                     foreach my $entry (@items) {
                    953:                         my ($key,$value) = split(/=/,$entry);
                    954:                         $key = &unescape($key);
                    955:                         $value = &unescape($value);
                    956:                         $userhash{$key} = $value;
                    957:                         if ($key eq 'username') {
                    958:                             $uname = $value;
                    959:                         } elsif ($key eq 'domain') {
                    960:                             $udom = $value;
                    961:                         } 
                    962:                     }
                    963:                     $results{$uname.':'.$udom} = \%userhash;
                    964:                 }
                    965:             }
                    966:         }
                    967:     }
                    968:     return %results;
                    969: }
                    970: 
1.344     www       971: # --------------------------------------------------- Assign a key to a student
                    972: 
                    973: sub assign_access_key {
1.364     www       974: #
                    975: # a valid key looks like uname:udom#comments
                    976: # comments are being appended
                    977: #
1.498     www       978:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    979:     $kdom=
1.620     albertel  980:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       981:     $knum=
1.620     albertel  982:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       983:     $cdom=
1.620     albertel  984:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       985:     $cnum=
1.620     albertel  986:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    987:     $udom=$env{'user.name'} unless (defined($udom));
                    988:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       989:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       990:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  991:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       992:                                                   # assigned to this person
                    993:                                                   # - this should not happen,
1.345     www       994:                                                   # unless something went wrong
                    995:                                                   # the first time around
                    996: # ready to assign
1.364     www       997:         $logentry=$1.'; '.$logentry;
1.496     www       998:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       999:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1000: # key now belongs to user
1.346     www      1001: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1002:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                   1003:                 &appenv('environment.'.$envkey => $ckey);
                   1004:                 return 'ok';
                   1005:             } else {
                   1006:                 return 
                   1007:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1008: 	    }
                   1009:         } else {
                   1010:             return 'error: Could not assign key, try again later.';
                   1011:         }
1.364     www      1012:     } elsif (!$existing{$ckey}) {
1.345     www      1013: # the key does not exist
                   1014: 	return 'error: The key does not exist';
                   1015:     } else {
                   1016: # the key is somebody else's
                   1017: 	return 'error: The key is already in use';
                   1018:     }
1.344     www      1019: }
                   1020: 
1.364     www      1021: # ------------------------------------------ put an additional comment on a key
                   1022: 
                   1023: sub comment_access_key {
                   1024: #
                   1025: # a valid key looks like uname:udom#comments
                   1026: # comments are being appended
                   1027: #
                   1028:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1029:     $cdom=
1.620     albertel 1030:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1031:     $cnum=
1.620     albertel 1032:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1033:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1034:     if ($existing{$ckey}) {
                   1035:         $existing{$ckey}.='; '.$logentry;
                   1036: # ready to assign
1.367     www      1037:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1038:                                                  $cdom,$cnum) eq 'ok') {
                   1039: 	    return 'ok';
                   1040:         } else {
                   1041: 	    return 'error: Count not store comment.';
                   1042:         }
                   1043:     } else {
                   1044: # the key does not exist
                   1045: 	return 'error: The key does not exist';
                   1046:     }
                   1047: }
                   1048: 
1.344     www      1049: # ------------------------------------------------------ Generate a set of keys
                   1050: 
                   1051: sub generate_access_keys {
1.364     www      1052:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1053:     $cdom=
1.620     albertel 1054:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1055:     $cnum=
1.620     albertel 1056:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1057:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1058:     unless (($cdom) && ($cnum)) { return 0; }
                   1059:     if ($number>10000) { return 0; }
                   1060:     sleep(2); # make sure don't get same seed twice
                   1061:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1062:     my $total=0;
                   1063:     for (my $i=1;$i<=$number;$i++) {
                   1064:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1065:                   sprintf("%lx",int(100000*rand)).'-'.
                   1066:                   sprintf("%lx",int(100000*rand));
                   1067:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1068:        $newkey=~s/0/h/g; # and also 0 and O
                   1069:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1070:        if ($existing{$newkey}) {
                   1071:            $i--;
                   1072:        } else {
1.364     www      1073: 	  if (&put('accesskeys',
                   1074:               { $newkey => '# generated '.localtime().
1.620     albertel 1075:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1076:                            '; '.$logentry },
                   1077: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1078:               $total++;
                   1079: 	  }
                   1080:        }
                   1081:     }
1.620     albertel 1082:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1083:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1084:     return $total;
                   1085: }
                   1086: 
                   1087: # ------------------------------------------------------- Validate an accesskey
                   1088: 
                   1089: sub validate_access_key {
                   1090:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1091:     $cdom=
1.620     albertel 1092:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1093:     $cnum=
1.620     albertel 1094:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1095:     $udom=$env{'user.domain'} unless (defined($udom));
                   1096:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1097:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1098:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1099: }
                   1100: 
                   1101: # ------------------------------------- Find the section of student in a course
1.652     albertel 1102: sub devalidate_getsection_cache {
                   1103:     my ($udom,$unam,$courseid)=@_;
                   1104:     my $hashid="$udom:$unam:$courseid";
                   1105:     &devalidate_cache_new('getsection',$hashid);
                   1106: }
1.298     matthew  1107: 
1.815     albertel 1108: sub courseid_to_courseurl {
                   1109:     my ($courseid) = @_;
                   1110:     #already url style courseid
                   1111:     return $courseid if ($courseid =~ m{^/});
                   1112: 
                   1113:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1114: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1115: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1116: 	return "/$cdom/$cnum";
                   1117:     }
                   1118: 
                   1119:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1120:     if (exists($courseinfo{'num'})) {
                   1121: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1122:     }
                   1123: 
                   1124:     return undef;
                   1125: }
                   1126: 
1.298     matthew  1127: sub getsection {
                   1128:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1129:     my $cachetime=1800;
1.551     albertel 1130: 
                   1131:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1132:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1133:     if (defined($cached)) { return $result; }
                   1134: 
1.298     matthew  1135:     my %Pending; 
                   1136:     my %Expired;
                   1137:     #
                   1138:     # Each role can either have not started yet (pending), be active, 
                   1139:     #    or have expired.
                   1140:     #
                   1141:     # If there is an active role, we are done.
                   1142:     #
                   1143:     # If there is more than one role which has not started yet, 
                   1144:     #     choose the one which will start sooner
                   1145:     # If there is one role which has not started yet, return it.
                   1146:     #
                   1147:     # If there is more than one expired role, choose the one which ended last.
                   1148:     # If there is a role which has expired, return it.
                   1149:     #
1.815     albertel 1150:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1151:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1152:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1153:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1154:         my $section=$1;
                   1155:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1156:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1157:         my $now=time;
1.548     albertel 1158:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1159:             $Expired{$end}=$section;
                   1160:             next;
                   1161:         }
1.548     albertel 1162:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1163:             $Pending{$start}=$section;
                   1164:             next;
                   1165:         }
1.599     albertel 1166:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1167:     }
                   1168:     #
                   1169:     # Presumedly there will be few matching roles from the above
                   1170:     # loop and the sorting time will be negligible.
                   1171:     if (scalar(keys(%Pending))) {
                   1172:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1173:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1174:     } 
                   1175:     if (scalar(keys(%Expired))) {
                   1176:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1177:         my $time = pop(@sorted);
1.599     albertel 1178:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1179:     }
1.599     albertel 1180:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1181: }
1.70      www      1182: 
1.599     albertel 1183: sub save_cache {
                   1184:     &purge_remembered();
1.722     albertel 1185:     #&Apache::loncommon::validate_page();
1.620     albertel 1186:     undef(%env);
1.780     albertel 1187:     undef($env_loaded);
1.599     albertel 1188: }
1.452     albertel 1189: 
1.599     albertel 1190: my $to_remember=-1;
                   1191: my %remembered;
                   1192: my %accessed;
                   1193: my $kicks=0;
                   1194: my $hits=0;
1.849     albertel 1195: sub make_key {
                   1196:     my ($name,$id) = @_;
1.872     albertel 1197:     if (length($id) > 65 
                   1198: 	&& length(&escape($id)) > 200) {
                   1199: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1200:     }
1.849     albertel 1201:     return &escape($name.':'.$id);
                   1202: }
                   1203: 
1.599     albertel 1204: sub devalidate_cache_new {
                   1205:     my ($name,$id,$debug) = @_;
                   1206:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1207:     $id=&make_key($name,$id);
1.599     albertel 1208:     $memcache->delete($id);
                   1209:     delete($remembered{$id});
                   1210:     delete($accessed{$id});
                   1211: }
                   1212: 
                   1213: sub is_cached_new {
                   1214:     my ($name,$id,$debug) = @_;
1.849     albertel 1215:     $id=&make_key($name,$id);
1.599     albertel 1216:     if (exists($remembered{$id})) {
                   1217: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1218: 	$accessed{$id}=[&gettimeofday()];
                   1219: 	$hits++;
                   1220: 	return ($remembered{$id},1);
                   1221:     }
                   1222:     my $value = $memcache->get($id);
                   1223:     if (!(defined($value))) {
                   1224: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1225: 	return (undef,undef);
1.416     albertel 1226:     }
1.599     albertel 1227:     if ($value eq '__undef__') {
                   1228: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1229: 	$value=undef;
                   1230:     }
                   1231:     &make_room($id,$value,$debug);
                   1232:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1233:     return ($value,1);
                   1234: }
                   1235: 
                   1236: sub do_cache_new {
                   1237:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1238:     $id=&make_key($name,$id);
1.599     albertel 1239:     my $setvalue=$value;
                   1240:     if (!defined($setvalue)) {
                   1241: 	$setvalue='__undef__';
                   1242:     }
1.623     albertel 1243:     if (!defined($time) ) {
                   1244: 	$time=600;
                   1245:     }
1.599     albertel 1246:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1247:     my $result = $memcache->set($id,$setvalue,$time);
                   1248:     if (! $result) {
1.872     albertel 1249: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1250: 	$memcache->disconnect_all();
1.872     albertel 1251:     }
1.600     albertel 1252:     # need to make a copy of $value
                   1253:     #&make_room($id,$value,$debug);
1.599     albertel 1254:     return $value;
                   1255: }
                   1256: 
                   1257: sub make_room {
                   1258:     my ($id,$value,$debug)=@_;
                   1259:     $remembered{$id}=$value;
                   1260:     if ($to_remember<0) { return; }
                   1261:     $accessed{$id}=[&gettimeofday()];
                   1262:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1263:     my $to_kick;
                   1264:     my $max_time=0;
                   1265:     foreach my $other (keys(%accessed)) {
                   1266: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1267: 	    $to_kick=$other;
                   1268: 	    $max_time=&tv_interval($accessed{$other});
                   1269: 	}
                   1270:     }
                   1271:     delete($remembered{$to_kick});
                   1272:     delete($accessed{$to_kick});
                   1273:     $kicks++;
                   1274:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1275:     return;
                   1276: }
                   1277: 
1.599     albertel 1278: sub purge_remembered {
1.604     albertel 1279:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1280:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1281:     undef(%remembered);
                   1282:     undef(%accessed);
1.428     albertel 1283: }
1.70      www      1284: # ------------------------------------- Read an entry from a user's environment
                   1285: 
                   1286: sub userenvironment {
                   1287:     my ($udom,$unam,@what)=@_;
                   1288:     my %returnhash=();
                   1289:     my @answer=split(/\&/,
                   1290:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1291:                       &homeserver($unam,$udom)));
                   1292:     my $i;
                   1293:     for ($i=0;$i<=$#what;$i++) {
                   1294: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1295:     }
                   1296:     return %returnhash;
1.1       albertel 1297: }
                   1298: 
1.617     albertel 1299: # ---------------------------------------------------------- Get a studentphoto
                   1300: sub studentphoto {
                   1301:     my ($udom,$unam,$ext) = @_;
                   1302:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1303:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1304:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1305:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1306:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1307:             } else {
                   1308:                 my ($result,$perm_reqd)=
1.707     albertel 1309: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1310:                 if ($result eq 'ok') {
                   1311:                     if (!($perm_reqd eq 'yes')) {
                   1312:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1313:                     }
                   1314:                 }
                   1315:             }
                   1316:         }
                   1317:     } else {
                   1318:         my ($result,$perm_reqd) = 
1.707     albertel 1319: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1320:         if ($result eq 'ok') {
                   1321:             if (!($perm_reqd eq 'yes')) {
                   1322:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1323:             }
                   1324:         }
                   1325:     }
                   1326:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1327: }
                   1328: 
                   1329: sub retrievestudentphoto {
                   1330:     my ($udom,$unam,$ext,$type) = @_;
                   1331:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1332:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1333:     if ($ret eq 'ok') {
                   1334:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1335:         if ($type eq 'thumbnail') {
                   1336:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1337:         }
                   1338:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1339:         return $tokenurl;
                   1340:     } else {
                   1341:         if ($type eq 'thumbnail') {
                   1342:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1343:         } else { 
                   1344:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1345:         }
1.617     albertel 1346:     }
                   1347: }
                   1348: 
1.263     www      1349: # -------------------------------------------------------------------- New chat
                   1350: 
                   1351: sub chatsend {
1.724     raeburn  1352:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1353:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1354:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1355:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1356:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1357: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1358: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1359: }
                   1360: 
                   1361: # ------------------------------------------ Find current version of a resource
                   1362: 
                   1363: sub getversion {
                   1364:     my $fname=&clutter(shift);
                   1365:     unless ($fname=~/^\/res\//) { return -1; }
                   1366:     return &currentversion(&filelocation('',$fname));
                   1367: }
                   1368: 
                   1369: sub currentversion {
                   1370:     my $fname=shift;
1.599     albertel 1371:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1372:     if (defined($cached)) { return $result; }
1.292     www      1373:     my $author=$fname;
                   1374:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1375:     my ($udom,$uname)=split(/\//,$author);
                   1376:     my $home=homeserver($uname,$udom);
                   1377:     if ($home eq 'no_host') { 
                   1378:         return -1; 
                   1379:     }
                   1380:     my $answer=reply("currentversion:$fname",$home);
                   1381:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1382: 	return -1;
                   1383:     }
1.599     albertel 1384:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1385: }
                   1386: 
1.1       albertel 1387: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1388: 
1.1       albertel 1389: sub subscribe {
                   1390:     my $fname=shift;
1.761     raeburn  1391:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1392:     $fname=~s/[\n\r]//g;
1.1       albertel 1393:     my $author=$fname;
                   1394:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1395:     my ($udom,$uname)=split(/\//,$author);
                   1396:     my $home=homeserver($uname,$udom);
1.335     albertel 1397:     if ($home eq 'no_host') {
                   1398:         return 'not_found';
1.1       albertel 1399:     }
                   1400:     my $answer=reply("sub:$fname",$home);
1.64      www      1401:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1402: 	$answer.=' by '.$home;
                   1403:     }
1.1       albertel 1404:     return $answer;
                   1405: }
                   1406:     
1.8       www      1407: # -------------------------------------------------------------- Replicate file
                   1408: 
                   1409: sub repcopy {
                   1410:     my $filename=shift;
1.23      www      1411:     $filename=~s/\/+/\//g;
1.607     raeburn  1412:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1413:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1414:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1415: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1416: 	return &repcopy_userfile($filename);
                   1417:     }
1.532     albertel 1418:     $filename=~s/[\n\r]//g;
1.8       www      1419:     my $transname="$filename.in.transfer";
1.828     www      1420: # FIXME: this should flock
1.607     raeburn  1421:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1422:     my $remoteurl=subscribe($filename);
1.64      www      1423:     if ($remoteurl =~ /^con_lost by/) {
                   1424: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1425:            return 'unavailable';
1.8       www      1426:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1427: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1428: 	   return 'not_found';
1.64      www      1429:     } elsif ($remoteurl =~ /^rejected by/) {
                   1430: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1431:            return 'forbidden';
1.20      www      1432:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1433:            return 'ok';
1.8       www      1434:     } else {
1.290     www      1435:         my $author=$filename;
                   1436:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1437:         my ($udom,$uname)=split(/\//,$author);
                   1438:         my $home=homeserver($uname,$udom);
                   1439:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1440:            my @parts=split(/\//,$filename);
                   1441:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1442:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1443:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1444: 	       return 'bad_request';
1.8       www      1445:            }
                   1446:            my $count;
                   1447:            for ($count=5;$count<$#parts;$count++) {
                   1448:                $path.="/$parts[$count]";
                   1449:                if ((-e $path)!=1) {
                   1450: 		   mkdir($path,0777);
                   1451:                }
                   1452:            }
                   1453:            my $ua=new LWP::UserAgent;
                   1454:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1455:            my $response=$ua->request($request,$transname);
                   1456:            if ($response->is_error()) {
                   1457: 	       unlink($transname);
                   1458:                my $message=$response->status_line;
1.672     albertel 1459:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1460:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1461:                return 'unavailable';
1.8       www      1462:            } else {
1.16      www      1463: 	       if ($remoteurl!~/\.meta$/) {
                   1464:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1465:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1466:                   if ($mresponse->is_error()) {
                   1467: 		      unlink($filename.'.meta');
                   1468:                       &logthis(
1.672     albertel 1469:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1470:                   }
                   1471: 	       }
1.8       www      1472:                rename($transname,$filename);
1.607     raeburn  1473:                return 'ok';
1.8       www      1474:            }
1.290     www      1475:        }
1.8       www      1476:     }
1.330     www      1477: }
                   1478: 
                   1479: # ------------------------------------------------ Get server side include body
                   1480: sub ssi_body {
1.381     albertel 1481:     my ($filelink,%form)=@_;
1.606     matthew  1482:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1483:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1484:     }
1.330     www      1485:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1486:                                      &ssi($filelink,%form));
1.778     albertel 1487:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1488:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1489:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1490:     return $output;
1.8       www      1491: }
                   1492: 
1.15      www      1493: # --------------------------------------------------------- Server Side Include
                   1494: 
1.782     albertel 1495: sub absolute_url {
                   1496:     my ($host_name) = @_;
                   1497:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1498:     if ($host_name eq '') {
                   1499: 	$host_name = $ENV{'SERVER_NAME'};
                   1500:     }
                   1501:     return $protocol.$host_name;
                   1502: }
                   1503: 
1.15      www      1504: sub ssi {
                   1505: 
1.23      www      1506:     my ($fn,%form)=@_;
1.15      www      1507: 
                   1508:     my $ua=new LWP::UserAgent;
1.23      www      1509:     
                   1510:     my $request;
1.711     albertel 1511: 
                   1512:     $form{'no_update_last_known'}=1;
1.895     albertel 1513:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1514:     if (%form) {
1.782     albertel 1515:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1516:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1517:     } else {
1.782     albertel 1518:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1519:     }
                   1520: 
1.15      www      1521:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1522:     my $response=$ua->request($request);
                   1523: 
1.324     www      1524:     return $response->content;
                   1525: }
                   1526: 
                   1527: sub externalssi {
                   1528:     my ($url)=@_;
                   1529:     my $ua=new LWP::UserAgent;
                   1530:     my $request=new HTTP::Request('GET',$url);
                   1531:     my $response=$ua->request($request);
1.15      www      1532:     return $response->content;
                   1533: }
1.254     www      1534: 
1.492     albertel 1535: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1536: 
                   1537: sub allowuploaded {
                   1538:     my ($srcurl,$url)=@_;
                   1539:     $url=&clutter(&declutter($url));
                   1540:     my $dir=$url;
                   1541:     $dir=~s/\/[^\/]+$//;
                   1542:     my %httpref=();
                   1543:     my $httpurl=&hreflocation('',$url);
                   1544:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1545:     &Apache::lonnet::appenv(%httpref);
1.254     www      1546: }
1.477     raeburn  1547: 
1.478     albertel 1548: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1549: # input: action, courseID, current domain, intended
1.637     raeburn  1550: #        path to file, source of file, instruction to parse file for objects,
                   1551: #        ref to hash for embedded objects,
                   1552: #        ref to hash for codebase of java objects.
                   1553: #
1.485     raeburn  1554: # output: url to file (if action was uploaddoc), 
                   1555: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1556: #
1.478     albertel 1557: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1558: # course.
1.477     raeburn  1559: #
1.478     albertel 1560: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1561: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1562: #          course's home server.
1.477     raeburn  1563: #
1.478     albertel 1564: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1565: #          be copied from $source (current location) to 
                   1566: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1567: #         and will then be copied to
                   1568: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1569: #         course's home server.
1.485     raeburn  1570: #
1.481     raeburn  1571: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1572: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1573: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1574: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1575: #         in course's home server.
1.637     raeburn  1576: #
1.477     raeburn  1577: 
                   1578: sub process_coursefile {
1.638     albertel 1579:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1580:     my $fetchresult;
1.638     albertel 1581:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1582:     if ($action eq 'propagate') {
1.638     albertel 1583:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1584: 			     $home);
1.481     raeburn  1585:     } else {
1.477     raeburn  1586:         my $fpath = '';
                   1587:         my $fname = $file;
1.478     albertel 1588:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1589:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1590:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1591:         if ($action eq 'copy') {
                   1592:             if ($source eq '') {
                   1593:                 $fetchresult = 'no source file';
                   1594:                 return $fetchresult;
                   1595:             } else {
                   1596:                 my $destination = $filepath.'/'.$fname;
                   1597:                 rename($source,$destination);
                   1598:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1599:                                  $home);
1.481     raeburn  1600:             }
                   1601:         } elsif ($action eq 'uploaddoc') {
                   1602:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1603:             print $fh $env{'form.'.$source};
1.481     raeburn  1604:             close($fh);
1.637     raeburn  1605:             if ($parser eq 'parse') {
                   1606:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1607:                 unless ($parse_result eq 'ok') {
                   1608:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1609:                 }
                   1610:             }
1.477     raeburn  1611:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1612:                                  $home);
1.481     raeburn  1613:             if ($fetchresult eq 'ok') {
                   1614:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1615:             } else {
                   1616:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1617:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1618:                 return '/adm/notfound.html';
                   1619:             }
1.477     raeburn  1620:         }
                   1621:     }
1.485     raeburn  1622:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1623:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1624:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1625:     }
                   1626:     return $fetchresult;
                   1627: }
                   1628: 
1.637     raeburn  1629: sub build_filepath {
                   1630:     my ($fpath) = @_;
                   1631:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1632:     unless ($fpath eq '') {
                   1633:         my @parts=split('/',$fpath);
                   1634:         foreach my $part (@parts) {
                   1635:             $filepath.= '/'.$part;
                   1636:             if ((-e $filepath)!=1) {
                   1637:                 mkdir($filepath,0777);
                   1638:             }
                   1639:         }
                   1640:     }
                   1641:     return $filepath;
                   1642: }
                   1643: 
                   1644: sub store_edited_file {
1.638     albertel 1645:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1646:     my $file = $primary_url;
                   1647:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1648:     my $fpath = '';
                   1649:     my $fname = $file;
                   1650:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1651:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1652:     my $filepath = &build_filepath($fpath);
                   1653:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1654:     print $fh $content;
                   1655:     close($fh);
1.638     albertel 1656:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1657:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1658: 			  $home);
1.637     raeburn  1659:     if ($$fetchresult eq 'ok') {
                   1660:         return '/uploaded/'.$fpath.'/'.$fname;
                   1661:     } else {
1.638     albertel 1662:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1663: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1664:         return '/adm/notfound.html';
                   1665:     }
                   1666: }
                   1667: 
1.531     albertel 1668: sub clean_filename {
1.831     albertel 1669:     my ($fname,$args)=@_;
1.315     www      1670: # Replace Windows backslashes by forward slashes
1.257     www      1671:     $fname=~s/\\/\//g;
1.831     albertel 1672:     if (!$args->{'keep_path'}) {
                   1673:         # Get rid of everything but the actual filename
                   1674: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1675:     }
1.315     www      1676: # Replace spaces by underscores
                   1677:     $fname=~s/\s+/\_/g;
                   1678: # Replace all other weird characters by nothing
1.831     albertel 1679:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1680: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1681: # numbers
                   1682:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1683:     return $fname;
                   1684: }
                   1685: 
1.608     albertel 1686: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1687: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1688: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1689: #        $coursedoc - if true up to the current course
                   1690: #                     if false
                   1691: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1692: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1693: #        $allfiles - reference to hash for embedded objects
                   1694: #        $codebase - reference to hash for codebase of java objects
                   1695: #        $desuname - username for permanent storage of uploaded file
                   1696: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1697: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1698: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1699: # 
1.686     albertel 1700: # output: url of file in userspace, or error: <message> 
                   1701: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1702: 
                   1703: 
1.531     albertel 1704: sub userfileupload {
1.860     raeburn  1705:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1706:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1707:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1708:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1709:     $fname=&clean_filename($fname);
1.315     www      1710: # See if there is anything left
1.257     www      1711:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1712:     chop($env{'form.'.$formname});
1.523     raeburn  1713:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1714:         my $now = time;
                   1715:         my $filepath = 'tmp/helprequests/'.$now;
                   1716:         my @parts=split(/\//,$filepath);
                   1717:         my $fullpath = $perlvar{'lonDaemons'};
                   1718:         for (my $i=0;$i<@parts;$i++) {
                   1719:             $fullpath .= '/'.$parts[$i];
                   1720:             if ((-e $fullpath)!=1) {
                   1721:                 mkdir($fullpath,0777);
                   1722:             }
                   1723:         }
                   1724:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1725:         print $fh $env{'form.'.$formname};
1.523     raeburn  1726:         close($fh);
1.741     raeburn  1727:         return $fullpath.'/'.$fname;
                   1728:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1729:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1730:                        '_'.$env{'user.domain'}.'/pending';
                   1731:         my @parts=split(/\//,$filepath);
                   1732:         my $fullpath = $perlvar{'lonDaemons'};
                   1733:         for (my $i=0;$i<@parts;$i++) {
                   1734:             $fullpath .= '/'.$parts[$i];
                   1735:             if ((-e $fullpath)!=1) {
                   1736:                 mkdir($fullpath,0777);
                   1737:             }
                   1738:         }
                   1739:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1740:         print $fh $env{'form.'.$formname};
                   1741:         close($fh);
                   1742:         return $fullpath.'/'.$fname;
1.523     raeburn  1743:     }
1.719     banghart 1744:     
1.258     www      1745: # Create the directory if not present
1.493     albertel 1746:     $fname="$subdir/$fname";
1.259     www      1747:     if ($coursedoc) {
1.638     albertel 1748: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1749: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1750:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1751:             return &finishuserfileupload($docuname,$docudom,
                   1752: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1753: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1754:         } else {
1.620     albertel 1755:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1756:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1757: 				       $fname,$formname,$parser,
                   1758: 				       $allfiles,$codebase);
1.481     raeburn  1759:         }
1.719     banghart 1760:     } elsif (defined($destuname)) {
                   1761:         my $docuname=$destuname;
                   1762:         my $docudom=$destudom;
1.860     raeburn  1763: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1764: 				     $parser,$allfiles,$codebase,
                   1765:                                      $thumbwidth,$thumbheight);
1.719     banghart 1766:         
1.259     www      1767:     } else {
1.638     albertel 1768:         my $docuname=$env{'user.name'};
                   1769:         my $docudom=$env{'user.domain'};
1.714     raeburn  1770:         if (exists($env{'form.group'})) {
                   1771:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1772:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1773:         }
1.860     raeburn  1774: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1775: 				     $parser,$allfiles,$codebase,
                   1776:                                      $thumbwidth,$thumbheight);
1.259     www      1777:     }
1.271     www      1778: }
                   1779: 
                   1780: sub finishuserfileupload {
1.860     raeburn  1781:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1782:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1783:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1784:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1785:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1786:     $file=$fname;
                   1787:     if ($fname=~m|/|) {
                   1788:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1789: 	$path.=$fnamepath.'/';
                   1790:     }
1.259     www      1791:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1792:     my $count;
                   1793:     for ($count=4;$count<=$#parts;$count++) {
                   1794:         $filepath.="/$parts[$count]";
                   1795:         if ((-e $filepath)!=1) {
                   1796: 	    mkdir($filepath,0777);
                   1797:         }
                   1798:     }
                   1799: # Save the file
                   1800:     {
1.701     albertel 1801: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1802: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1803: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1804: 	    return '/adm/notfound.html';
                   1805: 	}
                   1806: 	if (!print FH ($env{'form.'.$formname})) {
                   1807: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1808: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1809: 	    return '/adm/notfound.html';
                   1810: 	}
1.570     albertel 1811: 	close(FH);
1.258     www      1812:     }
1.637     raeburn  1813:     if ($parser eq 'parse') {
1.638     albertel 1814:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1815: 						   $codebase);
1.637     raeburn  1816:         unless ($parse_result eq 'ok') {
1.638     albertel 1817:             &logthis('Failed to parse '.$filepath.$file.
                   1818: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1819:         }
                   1820:     }
1.860     raeburn  1821:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1822:         my $input = $filepath.'/'.$file;
                   1823:         my $output = $filepath.'/'.'tn-'.$file;
                   1824:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1825:         system("convert -sample $thumbsize $input $output");
                   1826:         if (-e $filepath.'/'.'tn-'.$file) {
                   1827:             $fetchthumb  = 1; 
                   1828:         }
                   1829:     }
1.858     raeburn  1830:  
1.259     www      1831: # Notify homeserver to grep it
                   1832: #
1.638     albertel 1833:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1834:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1835:     if ($fetchresult eq 'ok') {
1.860     raeburn  1836:         if ($fetchthumb) {
                   1837:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1838:             if ($thumbresult ne 'ok') {
                   1839:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1840:                          $docuhome.': '.$thumbresult);
                   1841:             }
                   1842:         }
1.259     www      1843: #
1.258     www      1844: # Return the URL to it
1.494     albertel 1845:         return '/uploaded/'.$path.$file;
1.263     www      1846:     } else {
1.494     albertel 1847:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1848: 		 ': '.$fetchresult);
1.263     www      1849:         return '/adm/notfound.html';
1.858     raeburn  1850:     }
1.493     albertel 1851: }
                   1852: 
1.637     raeburn  1853: sub extract_embedded_items {
1.648     raeburn  1854:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1855:     my @state = ();
                   1856:     my %javafiles = (
                   1857:                       codebase => '',
                   1858:                       code => '',
                   1859:                       archive => ''
                   1860:                     );
                   1861:     my %mediafiles = (
                   1862:                       src => '',
                   1863:                       movie => '',
                   1864:                      );
1.648     raeburn  1865:     my $p;
                   1866:     if ($content) {
                   1867:         $p = HTML::LCParser->new($content);
                   1868:     } else {
                   1869:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1870:     }
1.641     albertel 1871:     while (my $t=$p->get_token()) {
1.640     albertel 1872: 	if ($t->[0] eq 'S') {
                   1873: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1874: 	    push(@state, $tagname);
1.648     raeburn  1875:             if (lc($tagname) eq 'allow') {
                   1876:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1877:             }
1.640     albertel 1878: 	    if (lc($tagname) eq 'img') {
                   1879: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1880: 	    }
1.886     albertel 1881: 	    if (lc($tagname) eq 'a') {
                   1882: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1883: 	    }
1.645     raeburn  1884:             if (lc($tagname) eq 'script') {
                   1885:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1886:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1887:                 } else {
                   1888:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1889:                 }
                   1890:             }
                   1891:             if (lc($tagname) eq 'link') {
                   1892:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1893:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1894:                 }
                   1895:             }
1.640     albertel 1896: 	    if (lc($tagname) eq 'object' ||
                   1897: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1898: 		foreach my $item (keys(%javafiles)) {
                   1899: 		    $javafiles{$item} = '';
                   1900: 		}
                   1901: 	    }
                   1902: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1903: 		my $name = lc($attr->{'name'});
                   1904: 		foreach my $item (keys(%javafiles)) {
                   1905: 		    if ($name eq $item) {
                   1906: 			$javafiles{$item} = $attr->{'value'};
                   1907: 			last;
                   1908: 		    }
                   1909: 		}
                   1910: 		foreach my $item (keys(%mediafiles)) {
                   1911: 		    if ($name eq $item) {
                   1912: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1913: 			last;
                   1914: 		    }
                   1915: 		}
                   1916: 	    }
                   1917: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1918: 		foreach my $item (keys(%javafiles)) {
                   1919: 		    if ($attr->{$item}) {
                   1920: 			$javafiles{$item} = $attr->{$item};
                   1921: 			last;
                   1922: 		    }
                   1923: 		}
                   1924: 		foreach my $item (keys(%mediafiles)) {
                   1925: 		    if ($attr->{$item}) {
                   1926: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1927: 			last;
                   1928: 		    }
                   1929: 		}
                   1930: 	    }
                   1931: 	} elsif ($t->[0] eq 'E') {
                   1932: 	    my ($tagname) = ($t->[1]);
                   1933: 	    if ($javafiles{'codebase'} ne '') {
                   1934: 		$javafiles{'codebase'} .= '/';
                   1935: 	    }  
                   1936: 	    if (lc($tagname) eq 'applet' ||
                   1937: 		lc($tagname) eq 'object' ||
                   1938: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1939: 		) {
                   1940: 		foreach my $item (keys(%javafiles)) {
                   1941: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1942: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1943: 			&add_filetype($allfiles,$file,$item);
                   1944: 		    }
                   1945: 		}
                   1946: 	    } 
                   1947: 	    pop @state;
                   1948: 	}
                   1949:     }
1.637     raeburn  1950:     return 'ok';
                   1951: }
                   1952: 
1.639     albertel 1953: sub add_filetype {
                   1954:     my ($allfiles,$file,$type)=@_;
                   1955:     if (exists($allfiles->{$file})) {
                   1956: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1957: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1958: 	}
                   1959:     } else {
                   1960: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1961:     }
                   1962: }
                   1963: 
1.493     albertel 1964: sub removeuploadedurl {
                   1965:     my ($url)=@_;
                   1966:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1967:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1968: }
                   1969: 
                   1970: sub removeuserfile {
                   1971:     my ($docuname,$docudom,$fname)=@_;
                   1972:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1973:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1974:     if ($result eq 'ok') {
                   1975:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1976:             my $metafile = $fname.'.meta';
                   1977:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1978: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1979:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1980:             my $sqlresult = 
1.823     albertel 1981:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1982:                                         'portfolio_metadata',$group,
                   1983:                                         'delete');
1.798     raeburn  1984:         }
                   1985:     }
                   1986:     return $result;
1.257     www      1987: }
1.15      www      1988: 
1.530     albertel 1989: sub mkdiruserfile {
                   1990:     my ($docuname,$docudom,$dir)=@_;
                   1991:     my $home=&homeserver($docuname,$docudom);
                   1992:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1993: }
                   1994: 
1.531     albertel 1995: sub renameuserfile {
                   1996:     my ($docuname,$docudom,$old,$new)=@_;
                   1997:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1998:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1999:                         &escape("$old").':'.&escape("$new"),$home);
                   2000:     if ($result eq 'ok') {
                   2001:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2002:             my $oldmeta = $old.'.meta';
                   2003:             my $newmeta = $new.'.meta';
                   2004:             my $metaresult = 
                   2005:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2006: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2007:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2008:             my $sqlresult = 
1.823     albertel 2009:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2010:                                         'portfolio_metadata',$group,
                   2011:                                         'delete');
1.798     raeburn  2012:         }
                   2013:     }
                   2014:     return $result;
1.531     albertel 2015: }
                   2016: 
1.14      www      2017: # ------------------------------------------------------------------------- Log
                   2018: 
                   2019: sub log {
                   2020:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2021:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2022: }
                   2023: 
                   2024: # ------------------------------------------------------------------ Course Log
1.352     www      2025: #
                   2026: # This routine flushes several buffers of non-mission-critical nature
                   2027: #
1.157     www      2028: 
                   2029: sub flushcourselogs {
1.352     www      2030:     &logthis('Flushing log buffers');
                   2031: #
                   2032: # course logs
                   2033: # This is a log of all transactions in a course, which can be used
                   2034: # for data mining purposes
                   2035: #
                   2036: # It also collects the courseid database, which lists last transaction
                   2037: # times and course titles for all courseids
                   2038: #
                   2039:     my %courseidbuffer=();
1.800     albertel 2040:     foreach my $crsid (keys %courselogs) {
1.352     www      2041:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2042: 		          &escape($courselogs{$crsid}),
                   2043: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2044: 	    delete $courselogs{$crsid};
                   2045:         } else {
                   2046:             &logthis('Failed to flush log buffer for '.$crsid);
                   2047:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2048:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2049:                         " exceeded maximum size, deleting.</font>");
                   2050:                delete $courselogs{$crsid};
                   2051:             }
1.352     www      2052:         }
                   2053:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2054:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2055: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2056:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2057:         } else {
                   2058:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2059: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2060:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2061:         }
1.191     harris41 2062:     }
1.352     www      2063: #
                   2064: # Write course id database (reverse lookup) to homeserver of courses 
                   2065: # Is used in pickcourse
                   2066: #
1.840     albertel 2067:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2068:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2069: 		     $crs_home);
1.352     www      2070:     }
                   2071: #
                   2072: # File accesses
                   2073: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2074: #
1.449     matthew  2075:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2076:         if ($entry =~ /___count$/) {
                   2077:             my ($dom,$name);
1.807     albertel 2078:             ($dom,$name,undef)=
1.811     albertel 2079: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2080:             if (! defined($dom) || $dom eq '' || 
                   2081:                 ! defined($name) || $name eq '') {
1.620     albertel 2082:                 my $cid = $env{'request.course.id'};
                   2083:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2084:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2085:             }
1.450     matthew  2086:             my $value = $accesshash{$entry};
                   2087:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2088:             my %temphash=($url => $value);
1.449     matthew  2089:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2090:             if ($result eq 'ok') {
                   2091:                 delete $accesshash{$entry};
                   2092:             } elsif ($result eq 'unknown_cmd') {
                   2093:                 # Target server has old code running on it.
1.450     matthew  2094:                 my %temphash=($entry => $value);
1.449     matthew  2095:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2096:                     delete $accesshash{$entry};
                   2097:                 }
                   2098:             }
                   2099:         } else {
1.811     albertel 2100:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2101:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2102:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2103:                 delete $accesshash{$entry};
                   2104:             }
1.185     www      2105:         }
1.191     harris41 2106:     }
1.352     www      2107: #
                   2108: # Roles
                   2109: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2110: #
1.800     albertel 2111:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2112:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2113: 	    split(/\:/,$entry);
                   2114:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2115:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2116:                 $rudom,$runame) eq 'ok') {
                   2117: 	    delete $userrolehash{$entry};
                   2118:         }
                   2119:     }
1.662     raeburn  2120: #
                   2121: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2122: #
                   2123:     my %domrolebuffer = ();
                   2124:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2125:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2126:         if ($domrolebuffer{$rudom}) {
                   2127:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2128:                       '='.&escape($domainrolehash{$entry});
                   2129:         } else {
                   2130:             $domrolebuffer{$rudom}.=&escape($entry).
                   2131:                       '='.&escape($domainrolehash{$entry});
                   2132:         }
                   2133:         delete $domainrolehash{$entry};
                   2134:     }
                   2135:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2136: 	my %servers = &get_servers($dom,'library');
                   2137: 	foreach my $tryserver (keys(%servers)) {
                   2138: 	    unless (&reply('domroleput:'.$dom.':'.
                   2139: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2140: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2141: 	    }
1.662     raeburn  2142:         }
                   2143:     }
1.186     www      2144:     $dumpcount++;
1.157     www      2145: }
                   2146: 
                   2147: sub courselog {
                   2148:     my $what=shift;
1.158     www      2149:     $what=time.':'.$what;
1.620     albertel 2150:     unless ($env{'request.course.id'}) { return ''; }
                   2151:     $coursedombuf{$env{'request.course.id'}}=
                   2152:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2153:     $coursenumbuf{$env{'request.course.id'}}=
                   2154:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2155:     $coursehombuf{$env{'request.course.id'}}=
                   2156:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2157:     $coursedescrbuf{$env{'request.course.id'}}=
                   2158:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2159:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2160:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2161:     $courseownerbuf{$env{'request.course.id'}}=
                   2162:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2163:     $coursetypebuf{$env{'request.course.id'}}=
                   2164:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2165:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2166: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2167:     } else {
1.620     albertel 2168: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2169:     }
1.620     albertel 2170:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2171: 	&flushcourselogs();
                   2172:     }
1.158     www      2173: }
                   2174: 
                   2175: sub courseacclog {
                   2176:     my $fnsymb=shift;
1.620     albertel 2177:     unless ($env{'request.course.id'}) { return ''; }
                   2178:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2179:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2180:         $what.=':POST';
1.583     matthew  2181:         # FIXME: Probably ought to escape things....
1.800     albertel 2182: 	foreach my $key (keys(%env)) {
                   2183:             if ($key=~/^form\.(.*)/) {
                   2184: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2185:             }
1.191     harris41 2186:         }
1.583     matthew  2187:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2188:         # FIXME: We should not be depending on a form parameter that someone
                   2189:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2190:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2191:             $what.= ':POST';
                   2192:             # FIXME: Probably ought to escape things....
                   2193:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2194:                                  'crsdiscuss') {
1.620     albertel 2195:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2196:             }
                   2197:         }
1.158     www      2198:     }
                   2199:     &courselog($what);
1.149     www      2200: }
                   2201: 
1.185     www      2202: sub countacc {
                   2203:     my $url=&declutter(shift);
1.458     matthew  2204:     return if (! defined($url) || $url eq '');
1.620     albertel 2205:     unless ($env{'request.course.id'}) { return ''; }
                   2206:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2207:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2208:     $accesshash{$key}++;
1.185     www      2209: }
1.349     www      2210: 
1.361     www      2211: sub linklog {
                   2212:     my ($from,$to)=@_;
                   2213:     $from=&declutter($from);
                   2214:     $to=&declutter($to);
                   2215:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2216:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2217: }
                   2218:   
1.349     www      2219: sub userrolelog {
                   2220:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2221:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2222:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2223:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2224:         ($trole=~/^ta/)) {
1.350     www      2225:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2226:        $userrolehash
                   2227:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2228:                     =$tend.':'.$tstart;
1.662     raeburn  2229:     }
1.898     albertel 2230:     if (($env{'request.role'} =~ /dc\./) &&
                   2231: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2232: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2233: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2234:        $userrolehash
                   2235:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2236:                     =$tend.':'.$tstart;
                   2237:     }
1.662     raeburn  2238:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2239:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2240:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2241:         ($trole=~/^sc/)) {
                   2242:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2243:        $domainrolehash
                   2244:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2245:                     = $tend.':'.$tstart;
                   2246:     }
1.351     www      2247: }
                   2248: 
                   2249: sub get_course_adv_roles {
                   2250:     my $cid=shift;
1.620     albertel 2251:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2252:     my %coursehash=&coursedescription($cid);
1.470     www      2253:     my %nothide=();
1.800     albertel 2254:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2255: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2256:     }
1.351     www      2257:     my %returnhash=();
                   2258:     my %dumphash=
                   2259:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2260:     my $now=time;
1.800     albertel 2261:     foreach my $entry (keys %dumphash) {
                   2262: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2263:         if (($tstart) && ($tstart<0)) { next; }
                   2264:         if (($tend) && ($tend<$now)) { next; }
                   2265:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2266:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2267: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2268: 	if ((&privileged($username,$domain)) && 
                   2269: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2270: 	if ($role eq 'cr') { next; }
1.351     www      2271:         my $key=&plaintext($role);
                   2272:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2273:         if ($returnhash{$key}) {
                   2274: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2275:         } else {
                   2276:             $returnhash{$key}=$username.':'.$domain;
                   2277:         }
1.400     www      2278:      }
                   2279:     return %returnhash;
                   2280: }
                   2281: 
                   2282: sub get_my_roles {
1.858     raeburn  2283:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2284:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2285:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2286:     my %dumphash;
                   2287:     if ($context eq 'userroles') { 
                   2288:         %dumphash = &dump('roles',$udom,$uname);
                   2289:     } else {
                   2290:         %dumphash=
1.400     www      2291:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2292:     }
1.400     www      2293:     my %returnhash=();
                   2294:     my $now=time;
1.800     albertel 2295:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2296:         my ($role,$tend,$tstart);
                   2297:         if ($context eq 'userroles') {
                   2298: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2299:         } else {
                   2300:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2301:         }
1.400     www      2302:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2303:         my $status = 'active';
                   2304:         if (($tend) && ($tend<$now)) {
                   2305:             $status = 'previous';
                   2306:         } 
                   2307:         if (($tstart) && ($now<$tstart)) {
                   2308:             $status = 'future';
                   2309:         }
                   2310:         if (ref($types) eq 'ARRAY') {
                   2311:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2312:                 next;
                   2313:             } 
                   2314:         } else {
                   2315:             if ($status ne 'active') {
                   2316:                 next;
                   2317:             }
                   2318:         }
1.867     raeburn  2319:         my ($rolecode,$username,$domain,$section,$area);
                   2320:         if ($context eq 'userroles') {
                   2321:             ($area,$rolecode) = split(/_/,$entry);
                   2322:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2323:         } else {
                   2324:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2325:         }
1.832     raeburn  2326:         if (ref($roledoms) eq 'ARRAY') {
                   2327:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2328:                 next;
                   2329:             }
                   2330:         }
                   2331:         if (ref($roles) eq 'ARRAY') {
                   2332:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2333:                 next;
                   2334:             }
1.867     raeburn  2335:         }
1.400     www      2336: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2337:     }
1.373     www      2338:     return %returnhash;
1.399     www      2339: }
                   2340: 
                   2341: # ----------------------------------------------------- Frontpage Announcements
                   2342: #
                   2343: #
                   2344: 
                   2345: sub postannounce {
                   2346:     my ($server,$text)=@_;
1.844     albertel 2347:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2348:     unless ($text=~/\w/) { $text=''; }
                   2349:     return &reply('setannounce:'.&escape($text),$server);
                   2350: }
                   2351: 
                   2352: sub getannounce {
1.448     albertel 2353: 
                   2354:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2355: 	my $announcement='';
1.800     albertel 2356: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2357: 	close($fh);
1.399     www      2358: 	if ($announcement=~/\w/) { 
                   2359: 	    return 
                   2360:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2361:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2362: 	} else {
                   2363: 	    return '';
                   2364: 	}
                   2365:     } else {
                   2366: 	return '';
                   2367:     }
1.351     www      2368: }
1.353     www      2369: 
                   2370: # ---------------------------------------------------------- Course ID routines
                   2371: # Deal with domain's nohist_courseid.db files
                   2372: #
                   2373: 
                   2374: sub courseidput {
                   2375:     my ($domain,$what,$coursehome)=@_;
                   2376:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2377: }
                   2378: 
                   2379: sub courseiddump {
1.791     raeburn  2380:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2381:     my %returnhash=();
1.355     www      2382:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2383:     my %libserv = &all_library();
                   2384:     foreach my $tryserver (keys(%libserv)) {
                   2385:         if ( (  $hostidflag == 1 
                   2386: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2387: 	     || (!defined($hostidflag)) ) {
                   2388: 
                   2389: 	    if ($domfilter eq ''
                   2390: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2391: 	        foreach my $line (
1.844     albertel 2392:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2393: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2394:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2395:                                $tryserver))) {
1.800     albertel 2396: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2397:                     if (($key) && ($value)) {
1.516     raeburn  2398: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2399:                     }
1.353     www      2400:                 }
                   2401:             }
                   2402:         }
                   2403:     }
                   2404:     return %returnhash;
                   2405: }
                   2406: 
1.658     raeburn  2407: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2408: 
                   2409: sub dcmailput {
1.685     raeburn  2410:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2411:     my $status = &Apache::lonnet::critical(
1.740     www      2412:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2413:        &escape($message),$server);
1.662     raeburn  2414:     return $status;
                   2415: }
                   2416: 
1.658     raeburn  2417: sub dcmaildump {
                   2418:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2419:     my %returnhash=();
1.846     albertel 2420: 
                   2421:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2422:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2423:                                                          &escape($enddate).':';
                   2424: 	my @esc_senders=map { &escape($_)} @$senders;
                   2425: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2426: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2427:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2428:             if (($key) && ($value)) {
                   2429:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2430:             }
                   2431:         }
                   2432:     }
                   2433:     return %returnhash;
                   2434: }
1.662     raeburn  2435: # ---------------------------------------------------------- Domain roles
                   2436: 
                   2437: sub get_domain_roles {
                   2438:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2439:     if (undef($startdate) || $startdate eq '') {
                   2440:         $startdate = '.';
                   2441:     }
                   2442:     if (undef($enddate) || $enddate eq '') {
                   2443:         $enddate = '.';
                   2444:     }
                   2445:     my $rolelist = join(':',@{$roles});
                   2446:     my %personnel = ();
1.841     albertel 2447: 
                   2448:     my %servers = &get_servers($dom,'library');
                   2449:     foreach my $tryserver (keys(%servers)) {
                   2450: 	%{$personnel{$tryserver}}=();
                   2451: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2452: 					    &escape($startdate).':'.
                   2453: 					    &escape($enddate).':'.
                   2454: 					    &escape($rolelist), $tryserver))) {
                   2455: 	    my ($key,$value) = split(/\=/,$line,2);
                   2456: 	    if (($key) && ($value)) {
                   2457: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2458: 	    }
                   2459: 	}
1.662     raeburn  2460:     }
                   2461:     return %personnel;
                   2462: }
1.658     raeburn  2463: 
1.149     www      2464: # ----------------------------------------------------------- Check out an item
                   2465: 
1.504     albertel 2466: sub get_first_access {
                   2467:     my ($type,$argsymb)=@_;
1.790     albertel 2468:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2469:     if ($argsymb) { $symb=$argsymb; }
                   2470:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2471:     if ($type eq 'map') {
                   2472: 	$res=&symbread($map);
                   2473:     } else {
                   2474: 	$res=$symb;
                   2475:     }
                   2476:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2477:     return $times{"$courseid\0$res"};
1.504     albertel 2478: }
                   2479: 
                   2480: sub set_first_access {
                   2481:     my ($type)=@_;
1.790     albertel 2482:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2483:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2484:     if ($type eq 'map') {
                   2485: 	$res=&symbread($map);
                   2486:     } else {
                   2487: 	$res=$symb;
                   2488:     }
                   2489:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2490:     if (!$firstaccess) {
1.588     albertel 2491: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2492:     }
                   2493:     return 'already_set';
1.504     albertel 2494: }
                   2495: 
1.149     www      2496: sub checkout {
                   2497:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2498:     my $now=time;
                   2499:     my $lonhost=$perlvar{'lonHostID'};
                   2500:     my $infostr=&escape(
1.234     www      2501:                  'CHECKOUTTOKEN&'.
1.149     www      2502:                  $tuname.'&'.
                   2503:                  $tudom.'&'.
                   2504:                  $tcrsid.'&'.
                   2505:                  $symb.'&'.
                   2506: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2507:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2508:     if ($token=~/^error\:/) { 
1.672     albertel 2509:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2510:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2511:                  "</font>");
                   2512:         return ''; 
                   2513:     }
                   2514: 
1.149     www      2515:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2516:     $token=~tr/a-z/A-Z/;
                   2517: 
1.153     www      2518:     my %infohash=('resource.0.outtoken' => $token,
                   2519:                   'resource.0.checkouttime' => $now,
                   2520:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2521: 
                   2522:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2523:        return '';
1.151     www      2524:     } else {
1.672     albertel 2525:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2526:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2527:                  "</font>");
1.149     www      2528:     }    
                   2529: 
                   2530:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2531:                          &escape('Checkout '.$infostr.' - '.
                   2532:                                                  $token)) ne 'ok') {
                   2533: 	return '';
1.151     www      2534:     } else {
1.672     albertel 2535:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2536:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2537:                  "</font>");
1.149     www      2538:     }
1.151     www      2539:     return $token;
1.149     www      2540: }
                   2541: 
                   2542: # ------------------------------------------------------------ Check in an item
                   2543: 
                   2544: sub checkin {
                   2545:     my $token=shift;
1.150     www      2546:     my $now=time;
                   2547:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2548:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2549:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2550:     $dtoken=~s/\W/\_/g;
1.234     www      2551:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2552:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2553: 
1.154     www      2554:     unless (($tuname) && ($tudom)) {
                   2555:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2556:         return '';
                   2557:     }
                   2558:     
                   2559:     unless (&allowed('mgr',$tcrsid)) {
                   2560:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2561:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2562:         return '';
                   2563:     }
                   2564: 
1.153     www      2565:     my %infohash=('resource.0.intoken' => $token,
                   2566:                   'resource.0.checkintime' => $now,
                   2567:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2568: 
                   2569:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2570:        return '';
                   2571:     }    
                   2572: 
                   2573:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2574:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2575: 	return '';
                   2576:     }
                   2577: 
                   2578:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2579: }
                   2580: 
                   2581: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2582: 
                   2583: sub expirespread {
                   2584:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2585:     my $cid=$env{'request.course.id'}; 
1.110     www      2586:     if ($cid) {
                   2587:        my $now=time;
                   2588:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2589:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2590:                             $env{'course.'.$cid.'.num'}.
1.110     www      2591: 	        	    ':nohist_expirationdates:'.
                   2592:                             &escape($key).'='.$now,
1.620     albertel 2593:                             $env{'course.'.$cid.'.home'})
1.110     www      2594:     }
                   2595:     return 'ok';
1.14      www      2596: }
                   2597: 
1.109     www      2598: # ----------------------------------------------------- Devalidate Spreadsheets
                   2599: 
                   2600: sub devalidate {
1.325     www      2601:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2602:     my $cid=$env{'request.course.id'}; 
1.109     www      2603:     if ($cid) {
1.391     matthew  2604:         # delete the stored spreadsheets for
                   2605:         # - the student level sheet of this user in course's homespace
                   2606:         # - the assessment level sheet for this resource 
                   2607:         #   for this user in user's homespace
1.553     albertel 2608: 	# - current conditional state info
1.325     www      2609: 	my $key=$uname.':'.$udom.':';
1.109     www      2610:         my $status=
1.299     matthew  2611: 	    &del('nohist_calculatedsheets',
1.391     matthew  2612: 		 [$key.'studentcalc:'],
1.620     albertel 2613: 		 $env{'course.'.$cid.'.domain'},
                   2614: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2615: 		.' '.
                   2616: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2617: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2618:         unless ($status eq 'ok ok') {
                   2619:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2620:                     $uname.' at '.$udom.' for '.
1.109     www      2621: 		    $symb.': '.$status);
1.133     albertel 2622:         }
1.553     albertel 2623: 	&delenv('user.state.'.$cid);
1.109     www      2624:     }
                   2625: }
                   2626: 
1.265     albertel 2627: sub get_scalar {
                   2628:     my ($string,$end) = @_;
                   2629:     my $value;
                   2630:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2631: 	$value = $1;
                   2632:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2633: 	$value = $1;
                   2634:     }
                   2635:     return &unescape($value);
                   2636: }
                   2637: 
                   2638: sub array2str {
                   2639:   my (@array) = @_;
                   2640:   my $result=&arrayref2str(\@array);
                   2641:   $result=~s/^__ARRAY_REF__//;
                   2642:   $result=~s/__END_ARRAY_REF__$//;
                   2643:   return $result;
                   2644: }
                   2645: 
1.204     albertel 2646: sub arrayref2str {
                   2647:   my ($arrayref) = @_;
1.265     albertel 2648:   my $result='__ARRAY_REF__';
1.204     albertel 2649:   foreach my $elem (@$arrayref) {
1.265     albertel 2650:     if(ref($elem) eq 'ARRAY') {
                   2651:       $result.=&arrayref2str($elem).'&';
                   2652:     } elsif(ref($elem) eq 'HASH') {
                   2653:       $result.=&hashref2str($elem).'&';
                   2654:     } elsif(ref($elem)) {
                   2655:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2656:     } else {
                   2657:       $result.=&escape($elem).'&';
                   2658:     }
                   2659:   }
                   2660:   $result=~s/\&$//;
1.265     albertel 2661:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2662:   return $result;
                   2663: }
                   2664: 
1.168     albertel 2665: sub hash2str {
1.204     albertel 2666:   my (%hash) = @_;
                   2667:   my $result=&hashref2str(\%hash);
1.265     albertel 2668:   $result=~s/^__HASH_REF__//;
                   2669:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2670:   return $result;
                   2671: }
                   2672: 
                   2673: sub hashref2str {
                   2674:   my ($hashref)=@_;
1.265     albertel 2675:   my $result='__HASH_REF__';
1.800     albertel 2676:   foreach my $key (sort(keys(%$hashref))) {
                   2677:     if (ref($key) eq 'ARRAY') {
                   2678:       $result.=&arrayref2str($key).'=';
                   2679:     } elsif (ref($key) eq 'HASH') {
                   2680:       $result.=&hashref2str($key).'=';
                   2681:     } elsif (ref($key)) {
1.265     albertel 2682:       $result.='=';
1.800     albertel 2683:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2684:     } else {
1.800     albertel 2685: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2686:     }
                   2687: 
1.800     albertel 2688:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2689:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2690:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2691:       $result.=&hashref2str($hashref->{$key}).'&';
                   2692:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2693:        $result.='&';
1.800     albertel 2694:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2695:     } else {
1.800     albertel 2696:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2697:     }
                   2698:   }
1.168     albertel 2699:   $result=~s/\&$//;
1.265     albertel 2700:   $result .= '__END_HASH_REF__';
1.168     albertel 2701:   return $result;
                   2702: }
                   2703: 
                   2704: sub str2hash {
1.265     albertel 2705:     my ($string)=@_;
                   2706:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2707:     return %$hash;
                   2708: }
                   2709: 
                   2710: sub str2hashref {
1.168     albertel 2711:   my ($string) = @_;
1.265     albertel 2712: 
                   2713:   my %hash;
                   2714: 
                   2715:   if($string !~ /^__HASH_REF__/) {
                   2716:       if (! ($string eq '' || !defined($string))) {
                   2717: 	  $hash{'error'}='Not hash reference';
                   2718:       }
                   2719:       return (\%hash, $string);
                   2720:   }
                   2721: 
                   2722:   $string =~ s/^__HASH_REF__//;
                   2723: 
                   2724:   while($string !~ /^__END_HASH_REF__/) {
                   2725:       #key
                   2726:       my $key='';
                   2727:       if($string =~ /^__HASH_REF__/) {
                   2728:           ($key, $string)=&str2hashref($string);
                   2729:           if(defined($key->{'error'})) {
                   2730:               $hash{'error'}='Bad data';
                   2731:               return (\%hash, $string);
                   2732:           }
                   2733:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2734:           ($key, $string)=&str2arrayref($string);
                   2735:           if($key->[0] eq 'Array reference error') {
                   2736:               $hash{'error'}='Bad data';
                   2737:               return (\%hash, $string);
                   2738:           }
                   2739:       } else {
                   2740:           $string =~ s/^(.*?)=//;
1.267     albertel 2741: 	  $key=&unescape($1);
1.265     albertel 2742:       }
                   2743:       $string =~ s/^=//;
                   2744: 
                   2745:       #value
                   2746:       my $value='';
                   2747:       if($string =~ /^__HASH_REF__/) {
                   2748:           ($value, $string)=&str2hashref($string);
                   2749:           if(defined($value->{'error'})) {
                   2750:               $hash{'error'}='Bad data';
                   2751:               return (\%hash, $string);
                   2752:           }
                   2753:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2754:           ($value, $string)=&str2arrayref($string);
                   2755:           if($value->[0] eq 'Array reference error') {
                   2756:               $hash{'error'}='Bad data';
                   2757:               return (\%hash, $string);
                   2758:           }
                   2759:       } else {
                   2760: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2761:       }
                   2762:       $string =~ s/^&//;
                   2763: 
                   2764:       $hash{$key}=$value;
1.204     albertel 2765:   }
1.265     albertel 2766: 
                   2767:   $string =~ s/^__END_HASH_REF__//;
                   2768: 
                   2769:   return (\%hash, $string);
1.204     albertel 2770: }
                   2771: 
                   2772: sub str2array {
1.265     albertel 2773:     my ($string)=@_;
                   2774:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2775:     return @$array;
                   2776: }
                   2777: 
                   2778: sub str2arrayref {
1.204     albertel 2779:   my ($string) = @_;
1.265     albertel 2780:   my @array;
                   2781: 
                   2782:   if($string !~ /^__ARRAY_REF__/) {
                   2783:       if (! ($string eq '' || !defined($string))) {
                   2784: 	  $array[0]='Array reference error';
                   2785:       }
                   2786:       return (\@array, $string);
                   2787:   }
                   2788: 
                   2789:   $string =~ s/^__ARRAY_REF__//;
                   2790: 
                   2791:   while($string !~ /^__END_ARRAY_REF__/) {
                   2792:       my $value='';
                   2793:       if($string =~ /^__HASH_REF__/) {
                   2794:           ($value, $string)=&str2hashref($string);
                   2795:           if(defined($value->{'error'})) {
                   2796:               $array[0] ='Array reference error';
                   2797:               return (\@array, $string);
                   2798:           }
                   2799:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2800:           ($value, $string)=&str2arrayref($string);
                   2801:           if($value->[0] eq 'Array reference error') {
                   2802:               $array[0] ='Array reference error';
                   2803:               return (\@array, $string);
                   2804:           }
                   2805:       } else {
                   2806: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2807:       }
                   2808:       $string =~ s/^&//;
                   2809: 
                   2810:       push(@array, $value);
1.191     harris41 2811:   }
1.265     albertel 2812: 
                   2813:   $string =~ s/^__END_ARRAY_REF__//;
                   2814: 
                   2815:   return (\@array, $string);
1.168     albertel 2816: }
                   2817: 
1.167     albertel 2818: # -------------------------------------------------------------------Temp Store
                   2819: 
1.168     albertel 2820: sub tmpreset {
                   2821:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2822:   if (!$symb) {
                   2823:     $symb=&symbread();
1.620     albertel 2824:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2825:   }
                   2826:   $symb=escape($symb);
                   2827: 
1.620     albertel 2828:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2829:   $namespace=~s/\//\_/g;
                   2830:   $namespace=~s/\W//g;
                   2831: 
1.620     albertel 2832:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2833:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2834:   if ($domain eq 'public' && $stuname eq 'public') {
                   2835:       $stuname=$ENV{'REMOTE_ADDR'};
                   2836:   }
1.168     albertel 2837:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2838:   my %hash;
                   2839:   if (tie(%hash,'GDBM_File',
                   2840: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2841: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2842:     foreach my $key (keys %hash) {
1.180     albertel 2843:       if ($key=~ /:$symb/) {
1.168     albertel 2844: 	delete($hash{$key});
                   2845:       }
                   2846:     }
                   2847:   }
                   2848: }
                   2849: 
1.167     albertel 2850: sub tmpstore {
1.168     albertel 2851:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2852: 
                   2853:   if (!$symb) {
                   2854:     $symb=&symbread();
1.620     albertel 2855:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2856:   }
                   2857:   $symb=escape($symb);
                   2858: 
                   2859:   if (!$namespace) {
                   2860:     # I don't think we would ever want to store this for a course.
                   2861:     # it seems this will only be used if we don't have a course.
1.620     albertel 2862:     #$namespace=$env{'request.course.id'};
1.168     albertel 2863:     #if (!$namespace) {
1.620     albertel 2864:       $namespace=$env{'request.state'};
1.168     albertel 2865:     #}
                   2866:   }
                   2867:   $namespace=~s/\//\_/g;
                   2868:   $namespace=~s/\W//g;
1.620     albertel 2869:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2870:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2871:   if ($domain eq 'public' && $stuname eq 'public') {
                   2872:       $stuname=$ENV{'REMOTE_ADDR'};
                   2873:   }
1.168     albertel 2874:   my $now=time;
                   2875:   my %hash;
                   2876:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2877:   if (tie(%hash,'GDBM_File',
                   2878: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2879: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2880:     $hash{"version:$symb"}++;
                   2881:     my $version=$hash{"version:$symb"};
                   2882:     my $allkeys=''; 
                   2883:     foreach my $key (keys(%$storehash)) {
                   2884:       $allkeys.=$key.':';
1.591     albertel 2885:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2886:     }
                   2887:     $hash{"$version:$symb:timestamp"}=$now;
                   2888:     $allkeys.='timestamp';
                   2889:     $hash{"$version:keys:$symb"}=$allkeys;
                   2890:     if (untie(%hash)) {
                   2891:       return 'ok';
                   2892:     } else {
                   2893:       return "error:$!";
                   2894:     }
                   2895:   } else {
                   2896:     return "error:$!";
                   2897:   }
                   2898: }
1.167     albertel 2899: 
1.168     albertel 2900: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2901: 
1.168     albertel 2902: sub tmprestore {
                   2903:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2904: 
1.168     albertel 2905:   if (!$symb) {
                   2906:     $symb=&symbread();
1.620     albertel 2907:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2908:   }
                   2909:   $symb=escape($symb);
                   2910: 
1.620     albertel 2911:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2912: 
1.620     albertel 2913:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2914:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2915:   if ($domain eq 'public' && $stuname eq 'public') {
                   2916:       $stuname=$ENV{'REMOTE_ADDR'};
                   2917:   }
1.168     albertel 2918:   my %returnhash;
                   2919:   $namespace=~s/\//\_/g;
                   2920:   $namespace=~s/\W//g;
                   2921:   my %hash;
                   2922:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2923:   if (tie(%hash,'GDBM_File',
                   2924: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2925: 	  &GDBM_READER(),0640)) {
1.168     albertel 2926:     my $version=$hash{"version:$symb"};
                   2927:     $returnhash{'version'}=$version;
                   2928:     my $scope;
                   2929:     for ($scope=1;$scope<=$version;$scope++) {
                   2930:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2931:       my @keys=split(/:/,$vkeys);
                   2932:       my $key;
                   2933:       $returnhash{"$scope:keys"}=$vkeys;
                   2934:       foreach $key (@keys) {
1.591     albertel 2935: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2936: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2937:       }
                   2938:     }
1.168     albertel 2939:     if (!(untie(%hash))) {
                   2940:       return "error:$!";
                   2941:     }
                   2942:   } else {
                   2943:     return "error:$!";
                   2944:   }
                   2945:   return %returnhash;
1.167     albertel 2946: }
                   2947: 
1.9       www      2948: # ----------------------------------------------------------------------- Store
                   2949: 
                   2950: sub store {
1.124     www      2951:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2952:     my $home='';
                   2953: 
1.168     albertel 2954:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2955: 
1.213     www      2956:     $symb=&symbclean($symb);
1.122     albertel 2957:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2958: 
1.620     albertel 2959:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2960:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2961: 
                   2962:     &devalidate($symb,$stuname,$domain);
1.109     www      2963: 
                   2964:     $symb=escape($symb);
1.187     www      2965:     if (!$namespace) { 
1.620     albertel 2966:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2967:           return ''; 
                   2968:        } 
                   2969:     }
1.620     albertel 2970:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2971: 
                   2972:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2973:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2974: 
1.12      www      2975:     my $namevalue='';
1.800     albertel 2976:     foreach my $key (keys(%$storehash)) {
                   2977:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2978:     }
1.12      www      2979:     $namevalue=~s/\&$//;
1.187     www      2980:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2981:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2982: }
                   2983: 
1.47      www      2984: # -------------------------------------------------------------- Critical Store
                   2985: 
                   2986: sub cstore {
1.124     www      2987:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2988:     my $home='';
                   2989: 
1.168     albertel 2990:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2991: 
1.213     www      2992:     $symb=&symbclean($symb);
1.122     albertel 2993:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2994: 
1.620     albertel 2995:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2996:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2997: 
                   2998:     &devalidate($symb,$stuname,$domain);
1.109     www      2999: 
                   3000:     $symb=escape($symb);
1.187     www      3001:     if (!$namespace) { 
1.620     albertel 3002:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3003:           return ''; 
                   3004:        } 
                   3005:     }
1.620     albertel 3006:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3007: 
                   3008:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3009:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3010: 
1.47      www      3011:     my $namevalue='';
1.800     albertel 3012:     foreach my $key (keys(%$storehash)) {
                   3013:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3014:     }
1.47      www      3015:     $namevalue=~s/\&$//;
1.187     www      3016:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3017:     return critical
                   3018:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3019: }
                   3020: 
1.9       www      3021: # --------------------------------------------------------------------- Restore
                   3022: 
                   3023: sub restore {
1.124     www      3024:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3025:     my $home='';
                   3026: 
1.168     albertel 3027:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3028: 
1.122     albertel 3029:     if (!$symb) {
                   3030:       unless ($symb=escape(&symbread())) { return ''; }
                   3031:     } else {
1.213     www      3032:       $symb=&escape(&symbclean($symb));
1.122     albertel 3033:     }
1.188     www      3034:     if (!$namespace) { 
1.620     albertel 3035:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3036:           return ''; 
                   3037:        } 
                   3038:     }
1.620     albertel 3039:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3040:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3041:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3042:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3043: 
1.12      www      3044:     my %returnhash=();
1.800     albertel 3045:     foreach my $line (split(/\&/,$answer)) {
                   3046: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3047:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3048:     }
1.75      www      3049:     my $version;
                   3050:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3051:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3052:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3053:        }
1.75      www      3054:     }
1.13      www      3055:     return %returnhash;
1.34      www      3056: }
                   3057: 
                   3058: # ---------------------------------------------------------- Course Description
                   3059: 
                   3060: sub coursedescription {
1.731     albertel 3061:     my ($courseid,$args)=@_;
1.34      www      3062:     $courseid=~s/^\///;
1.49      www      3063:     $courseid=~s/\_/\//g;
1.34      www      3064:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3065:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3066:     my $normalid=$cdomain.'_'.$cnum;
                   3067:     # need to always cache even if we get errors otherwise we keep 
                   3068:     # trying and trying and trying to get the course description.
                   3069:     my %envhash=();
                   3070:     my %returnhash=();
1.731     albertel 3071:     
                   3072:     my $expiretime=600;
                   3073:     if ($env{'request.course.id'} eq $normalid) {
                   3074: 	$expiretime=120;
                   3075:     }
                   3076: 
                   3077:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3078:     if (!$args->{'freshen_cache'}
                   3079: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3080: 	foreach my $key (keys(%env)) {
                   3081: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3082: 	    my ($setting) = $1;
                   3083: 	    $returnhash{$setting} = $env{$key};
                   3084: 	}
                   3085: 	return %returnhash;
                   3086:     }
                   3087: 
                   3088:     # get the data agin
                   3089:     if (!$args->{'one_time'}) {
                   3090: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3091:     }
1.811     albertel 3092: 
1.34      www      3093:     if ($chome ne 'no_host') {
1.302     albertel 3094:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3095:        if (!exists($returnhash{'con_lost'})) {
                   3096:            $returnhash{'home'}= $chome;
                   3097: 	   $returnhash{'domain'} = $cdomain;
                   3098: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3099:            if (!defined($returnhash{'type'})) {
                   3100:                $returnhash{'type'} = 'Course';
                   3101:            }
1.130     albertel 3102:            while (my ($name,$value) = each %returnhash) {
1.53      www      3103:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3104:            }
1.270     www      3105:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3106:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3107: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3108:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3109:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3110:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3111:        }
                   3112:     }
1.731     albertel 3113:     if (!$args->{'one_time'}) {
                   3114: 	&appenv(%envhash);
                   3115:     }
1.302     albertel 3116:     return %returnhash;
1.461     www      3117: }
                   3118: 
                   3119: # -------------------------------------------------See if a user is privileged
                   3120: 
                   3121: sub privileged {
                   3122:     my ($username,$domain)=@_;
                   3123:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3124: 			&homeserver($username,$domain));
                   3125:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3126:     my $now=time;
                   3127:     if ($rolesdump ne '') {
1.800     albertel 3128:         foreach my $entry (split(/&/,$rolesdump)) {
                   3129: 	    if ($entry!~/^rolesdef_/) {
                   3130: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3131: 		$area=~s/\_\w\w$//;
                   3132: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3133: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3134: 		    my $active=1;
                   3135: 		    if ($tend) {
                   3136: 			if ($tend<$now) { $active=0; }
                   3137: 		    }
                   3138: 		    if ($tstart) {
                   3139: 			if ($tstart>$now) { $active=0; }
                   3140: 		    }
                   3141: 		    if ($active) { return 1; }
                   3142: 		}
                   3143: 	    }
                   3144: 	}
                   3145:     }
                   3146:     return 0;
1.9       www      3147: }
1.1       albertel 3148: 
1.103     harris41 3149: # -------------------------------------------------------- Get user privileges
1.11      www      3150: 
                   3151: sub rolesinit {
                   3152:     my ($domain,$username,$authhost)=@_;
                   3153:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3154:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3155:     my %allroles=();
1.678     raeburn  3156:     my %allgroups=();   
1.11      www      3157:     my $now=time;
1.743     albertel 3158:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3159:     my $group_privs;
1.11      www      3160: 
                   3161:     if ($rolesdump ne '') {
1.800     albertel 3162:         foreach my $entry (split(/&/,$rolesdump)) {
                   3163: 	  if ($entry!~/^rolesdef_/) {
                   3164:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3165: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3166:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3167: 	    if ($role=~/^cr/) { 
1.807     albertel 3168: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3169: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3170: 		    ($tend,$tstart)=split('_',$trest);
                   3171: 		} else {
                   3172: 		    $trole=$role;
                   3173: 		}
1.678     raeburn  3174:             } elsif ($role =~ m|^gr/|) {
                   3175:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3176:                 ($trole,$group_privs) = split(/\//,$trole);
                   3177:                 $group_privs = &unescape($group_privs);
1.587     albertel 3178: 	    } else {
                   3179: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3180: 	    }
1.743     albertel 3181: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3182: 					 $username);
                   3183: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3184:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3185:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3186:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3187: 		my $spec=$trole.'.'.$area;
                   3188: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3189: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3190:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3191:                 } elsif ($trole eq 'gr') {
                   3192:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3193: 		} else {
1.567     raeburn  3194:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3195: 		}
1.12      www      3196:             }
1.662     raeburn  3197:           }
1.191     harris41 3198:         }
1.743     albertel 3199:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3200:         $userroles{'user.adv'}    = $adv;
                   3201: 	$userroles{'user.author'} = $author;
1.620     albertel 3202:         $env{'user.adv'}=$adv;
1.11      www      3203:     }
1.743     albertel 3204:     return \%userroles;  
1.11      www      3205: }
                   3206: 
1.567     raeburn  3207: sub set_arearole {
                   3208:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3209: # log the associated role with the area
                   3210:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3211:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3212: }
                   3213: 
                   3214: sub custom_roleprivs {
                   3215:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3216:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3217:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3218:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3219:         my ($rdummy,$roledef)=
                   3220:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3221:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3222:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3223:             if (defined($syspriv)) {
                   3224:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3225:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3226:             }
                   3227:             if ($tdomain ne '') {
                   3228:                 if (defined($dompriv)) {
                   3229:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3230:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3231:                 }
                   3232:                 if (($trest ne '') && (defined($coursepriv))) {
                   3233:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3234:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3235:                 }
                   3236:             }
                   3237:         }
                   3238:     }
                   3239: }
                   3240: 
1.678     raeburn  3241: sub group_roleprivs {
                   3242:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3243:     my $access = 1;
                   3244:     my $now = time;
                   3245:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3246:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3247:     if ($access) {
1.811     albertel 3248:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3249:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3250:     }
                   3251: }
1.567     raeburn  3252: 
                   3253: sub standard_roleprivs {
                   3254:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3255:     if (defined($pr{$trole.':s'})) {
                   3256:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3257:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3258:     }
                   3259:     if ($tdomain ne '') {
                   3260:         if (defined($pr{$trole.':d'})) {
                   3261:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3262:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3263:         }
                   3264:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3265:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3266:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3267:         }
                   3268:     }
                   3269: }
                   3270: 
                   3271: sub set_userprivs {
1.678     raeburn  3272:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3273:     my $author=0;
                   3274:     my $adv=0;
1.678     raeburn  3275:     my %grouproles = ();
                   3276:     if (keys(%{$allgroups}) > 0) {
                   3277:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3278:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3279:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3280:                 $trole = $1;
                   3281:                 $area = $2;
1.681     raeburn  3282:                 $sec = $3;
                   3283:                 $extendedarea = $area.$sec;
                   3284:                 if (exists($$allgroups{$area})) {
                   3285:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3286:                         my $spec = $trole.'.'.$extendedarea;
                   3287:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3288:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3289:                     }
                   3290:                 }
                   3291:             }
                   3292:         }
                   3293:     }
1.800     albertel 3294:     foreach my $group (keys(%grouproles)) {
                   3295:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3296:     }
1.800     albertel 3297:     foreach my $role (keys(%{$allroles})) {
                   3298:         my %thesepriv;
                   3299:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3300:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3301:             if ($item ne '') {
                   3302:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3303:                 if ($restrictions eq '') {
                   3304:                     $thesepriv{$privilege}='F';
                   3305:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3306:                     $thesepriv{$privilege}.=$restrictions;
                   3307:                 }
                   3308:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3309:             }
                   3310:         }
                   3311:         my $thesestr='';
1.800     albertel 3312:         foreach my $priv (keys(%thesepriv)) {
                   3313: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3314: 	}
                   3315:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3316:     }
                   3317:     return ($author,$adv);
                   3318: }
                   3319: 
1.12      www      3320: # --------------------------------------------------------------- get interface
                   3321: 
                   3322: sub get {
1.131     albertel 3323:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3324:    my $items='';
1.800     albertel 3325:    foreach my $item (@$storearr) {
                   3326:        $items.=&escape($item).'&';
1.191     harris41 3327:    }
1.12      www      3328:    $items=~s/\&$//;
1.620     albertel 3329:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3330:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3331:    my $uhome=&homeserver($uname,$udomain);
                   3332: 
1.133     albertel 3333:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3334:    my @pairs=split(/\&/,$rep);
1.273     albertel 3335:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3336:      return @pairs;
                   3337:    }
1.15      www      3338:    my %returnhash=();
1.42      www      3339:    my $i=0;
1.800     albertel 3340:    foreach my $item (@$storearr) {
                   3341:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3342:       $i++;
1.191     harris41 3343:    }
1.15      www      3344:    return %returnhash;
1.27      www      3345: }
                   3346: 
                   3347: # --------------------------------------------------------------- del interface
                   3348: 
                   3349: sub del {
1.133     albertel 3350:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3351:    my $items='';
1.800     albertel 3352:    foreach my $item (@$storearr) {
                   3353:        $items.=&escape($item).'&';
1.191     harris41 3354:    }
1.27      www      3355:    $items=~s/\&$//;
1.620     albertel 3356:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3357:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3358:    my $uhome=&homeserver($uname,$udomain);
                   3359: 
                   3360:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3361: }
                   3362: 
                   3363: # -------------------------------------------------------------- dump interface
                   3364: 
                   3365: sub dump {
1.755     albertel 3366:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3367:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3368:     if (!$uname) { $uname=$env{'user.name'}; }
                   3369:     my $uhome=&homeserver($uname,$udomain);
                   3370:     if ($regexp) {
                   3371: 	$regexp=&escape($regexp);
                   3372:     } else {
                   3373: 	$regexp='.';
                   3374:     }
                   3375:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3376:     my @pairs=split(/\&/,$rep);
                   3377:     my %returnhash=();
                   3378:     foreach my $item (@pairs) {
                   3379: 	my ($key,$value)=split(/=/,$item,2);
                   3380: 	$key = &unescape($key);
                   3381: 	next if ($key =~ /^error: 2 /);
                   3382: 	$returnhash{$key}=&thaw_unescape($value);
                   3383:     }
                   3384:     return %returnhash;
1.407     www      3385: }
                   3386: 
1.717     albertel 3387: # --------------------------------------------------------- dumpstore interface
                   3388: 
                   3389: sub dumpstore {
                   3390:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3391:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3392:    if (!$uname) { $uname=$env{'user.name'}; }
                   3393:    my $uhome=&homeserver($uname,$udomain);
                   3394:    if ($regexp) {
                   3395:        $regexp=&escape($regexp);
                   3396:    } else {
                   3397:        $regexp='.';
                   3398:    }
                   3399:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3400:    my @pairs=split(/\&/,$rep);
                   3401:    my %returnhash=();
                   3402:    foreach my $item (@pairs) {
                   3403:        my ($key,$value)=split(/=/,$item,2);
                   3404:        next if ($key =~ /^error: 2 /);
                   3405:        $returnhash{$key}=&thaw_unescape($value);
                   3406:    }
                   3407:    return %returnhash;
1.717     albertel 3408: }
                   3409: 
1.407     www      3410: # -------------------------------------------------------------- keys interface
                   3411: 
                   3412: sub getkeys {
                   3413:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3414:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3415:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3416:    my $uhome=&homeserver($uname,$udomain);
                   3417:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3418:    my @keyarray=();
1.800     albertel 3419:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3420:       next if ($key =~ /^error: 2 /);
1.800     albertel 3421:       push(@keyarray,&unescape($key));
1.407     www      3422:    }
                   3423:    return @keyarray;
1.318     matthew  3424: }
                   3425: 
1.319     matthew  3426: # --------------------------------------------------------------- currentdump
                   3427: sub currentdump {
1.328     matthew  3428:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3429:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3430:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3431:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3432:    my $uhome = &homeserver($sname,$sdom);
                   3433:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3434:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3435:    #
1.318     matthew  3436:    my %returnhash=();
1.319     matthew  3437:    #
                   3438:    if ($rep eq "unknown_cmd") { 
                   3439:        # an old lond will not know currentdump
                   3440:        # Do a dump and make it look like a currentdump
1.822     albertel 3441:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3442:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3443:        my %hash = @tmp;
                   3444:        @tmp=();
1.424     matthew  3445:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3446:    } else {
                   3447:        my @pairs=split(/\&/,$rep);
1.800     albertel 3448:        foreach my $pair (@pairs) {
                   3449:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3450:            my ($symb,$param) = split(/:/,$key);
                   3451:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3452:                                                         &thaw_unescape($value);
1.319     matthew  3453:        }
1.191     harris41 3454:    }
1.12      www      3455:    return %returnhash;
1.424     matthew  3456: }
                   3457: 
                   3458: sub convert_dump_to_currentdump{
                   3459:     my %hash = %{shift()};
                   3460:     my %returnhash;
                   3461:     # Code ripped from lond, essentially.  The only difference
                   3462:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3463:     # we might run in to problems with parameter names =~ /^v\./
                   3464:     while (my ($key,$value) = each(%hash)) {
                   3465:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3466: 	$symb  = &unescape($symb);
                   3467: 	$param = &unescape($param);
1.424     matthew  3468:         next if ($v eq 'version' || $symb eq 'keys');
                   3469:         next if (exists($returnhash{$symb}) &&
                   3470:                  exists($returnhash{$symb}->{$param}) &&
                   3471:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3472:         $returnhash{$symb}->{$param}=$value;
                   3473:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3474:     }
                   3475:     #
                   3476:     # Remove all of the keys in the hashes which keep track of
                   3477:     # the version of the parameter.
                   3478:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3479:         # use a foreach because we are going to delete from the hash.
                   3480:         foreach my $key (keys(%$param_hash)) {
                   3481:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3482:         }
                   3483:     }
                   3484:     return \%returnhash;
1.12      www      3485: }
                   3486: 
1.627     albertel 3487: # ------------------------------------------------------ critical inc interface
                   3488: 
                   3489: sub cinc {
                   3490:     return &inc(@_,'critical');
                   3491: }
                   3492: 
1.449     matthew  3493: # --------------------------------------------------------------- inc interface
                   3494: 
                   3495: sub inc {
1.627     albertel 3496:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3497:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3498:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3499:     my $uhome=&homeserver($uname,$udomain);
                   3500:     my $items='';
                   3501:     if (! ref($store)) {
                   3502:         # got a single value, so use that instead
                   3503:         $items = &escape($store).'=&';
                   3504:     } elsif (ref($store) eq 'SCALAR') {
                   3505:         $items = &escape($$store).'=&';        
                   3506:     } elsif (ref($store) eq 'ARRAY') {
                   3507:         $items = join('=&',map {&escape($_);} @{$store});
                   3508:     } elsif (ref($store) eq 'HASH') {
                   3509:         while (my($key,$value) = each(%{$store})) {
                   3510:             $items.= &escape($key).'='.&escape($value).'&';
                   3511:         }
                   3512:     }
                   3513:     $items=~s/\&$//;
1.627     albertel 3514:     if ($critical) {
                   3515: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3516:     } else {
                   3517: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3518:     }
1.449     matthew  3519: }
                   3520: 
1.12      www      3521: # --------------------------------------------------------------- put interface
                   3522: 
                   3523: sub put {
1.134     albertel 3524:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3525:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3526:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3527:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3528:    my $items='';
1.800     albertel 3529:    foreach my $item (keys(%$storehash)) {
                   3530:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3531:    }
1.12      www      3532:    $items=~s/\&$//;
1.134     albertel 3533:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3534: }
                   3535: 
1.631     albertel 3536: # ------------------------------------------------------------ newput interface
                   3537: 
                   3538: sub newput {
                   3539:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3540:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3541:    if (!$uname) { $uname=$env{'user.name'}; }
                   3542:    my $uhome=&homeserver($uname,$udomain);
                   3543:    my $items='';
                   3544:    foreach my $key (keys(%$storehash)) {
                   3545:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3546:    }
                   3547:    $items=~s/\&$//;
                   3548:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3549: }
                   3550: 
                   3551: # ---------------------------------------------------------  putstore interface
                   3552: 
1.524     raeburn  3553: sub putstore {
1.715     albertel 3554:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3555:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3556:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3557:    my $uhome=&homeserver($uname,$udomain);
                   3558:    my $items='';
1.715     albertel 3559:    foreach my $key (keys(%$storehash)) {
                   3560:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3561:    }
1.715     albertel 3562:    $items=~s/\&$//;
1.716     albertel 3563:    my $esc_symb=&escape($symb);
                   3564:    my $esc_v=&escape($version);
1.715     albertel 3565:    my $reply =
1.716     albertel 3566:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3567: 	      $uhome);
                   3568:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3569:        # gfall back to way things use to be done
1.715     albertel 3570:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3571: 			    $uname);
1.524     raeburn  3572:    }
1.715     albertel 3573:    return $reply;
                   3574: }
                   3575: 
                   3576: sub old_putstore {
1.716     albertel 3577:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3578:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3579:     if (!$uname) { $uname=$env{'user.name'}; }
                   3580:     my $uhome=&homeserver($uname,$udomain);
                   3581:     my %newstorehash;
1.800     albertel 3582:     foreach my $item (keys(%$storehash)) {
                   3583: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3584: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3585:     }
                   3586:     my $items='';
                   3587:     my %allitems = ();
1.800     albertel 3588:     foreach my $item (keys(%newstorehash)) {
                   3589: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3590: 	    my $key = $1.':keys:'.$2;
                   3591: 	    $allitems{$key} .= $3.':';
                   3592: 	}
1.800     albertel 3593: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3594:     }
1.800     albertel 3595:     foreach my $item (keys(%allitems)) {
                   3596: 	$allitems{$item} =~ s/\:$//;
                   3597: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3598:     }
                   3599:     $items=~s/\&$//;
                   3600:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3601: }
                   3602: 
1.47      www      3603: # ------------------------------------------------------ critical put interface
                   3604: 
                   3605: sub cput {
1.134     albertel 3606:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3607:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3608:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3609:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3610:    my $items='';
1.800     albertel 3611:    foreach my $item (keys(%$storehash)) {
                   3612:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3613:    }
1.47      www      3614:    $items=~s/\&$//;
1.134     albertel 3615:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3616: }
                   3617: 
                   3618: # -------------------------------------------------------------- eget interface
                   3619: 
                   3620: sub eget {
1.133     albertel 3621:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3622:    my $items='';
1.800     albertel 3623:    foreach my $item (@$storearr) {
                   3624:        $items.=&escape($item).'&';
1.191     harris41 3625:    }
1.12      www      3626:    $items=~s/\&$//;
1.620     albertel 3627:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3628:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3629:    my $uhome=&homeserver($uname,$udomain);
                   3630:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3631:    my @pairs=split(/\&/,$rep);
                   3632:    my %returnhash=();
1.42      www      3633:    my $i=0;
1.800     albertel 3634:    foreach my $item (@$storearr) {
                   3635:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3636:       $i++;
1.191     harris41 3637:    }
1.12      www      3638:    return %returnhash;
                   3639: }
                   3640: 
1.667     albertel 3641: # ------------------------------------------------------------ tmpput interface
                   3642: sub tmpput {
1.802     raeburn  3643:     my ($storehash,$server,$context)=@_;
1.667     albertel 3644:     my $items='';
1.800     albertel 3645:     foreach my $item (keys(%$storehash)) {
                   3646: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3647:     }
                   3648:     $items=~s/\&$//;
1.802     raeburn  3649:     if (defined($context)) {
                   3650:         $items .= ':'.&escape($context);
                   3651:     }
1.667     albertel 3652:     return &reply("tmpput:$items",$server);
                   3653: }
                   3654: 
                   3655: # ------------------------------------------------------------ tmpget interface
                   3656: sub tmpget {
1.688     albertel 3657:     my ($token,$server)=@_;
                   3658:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3659:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3660:     my %returnhash;
                   3661:     foreach my $item (split(/\&/,$rep)) {
                   3662: 	my ($key,$value)=split(/=/,$item);
                   3663: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3664:     }
                   3665:     return %returnhash;
                   3666: }
                   3667: 
1.688     albertel 3668: # ------------------------------------------------------------ tmpget interface
                   3669: sub tmpdel {
                   3670:     my ($token,$server)=@_;
                   3671:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3672:     return &reply("tmpdel:$token",$server);
                   3673: }
                   3674: 
1.765     albertel 3675: # -------------------------------------------------- portfolio access checking
                   3676: 
                   3677: sub portfolio_access {
1.766     albertel 3678:     my ($requrl) = @_;
1.765     albertel 3679:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3680:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3681:     if ($result) {
                   3682:         my %setters;
                   3683:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3684:             my ($startblock,$endblock) =
                   3685:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3686:             if ($startblock && $endblock) {
                   3687:                 return 'B';
                   3688:             }
                   3689:         } else {
                   3690:             my ($startblock,$endblock) =
                   3691:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3692:             if ($startblock && $endblock) {
                   3693:                 return 'B';
                   3694:             }
                   3695:         }
                   3696:     }
1.765     albertel 3697:     if ($result eq 'ok') {
1.766     albertel 3698:        return 'F';
1.765     albertel 3699:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3700:        return 'A';
1.765     albertel 3701:     }
1.766     albertel 3702:     return '';
1.765     albertel 3703: }
                   3704: 
                   3705: sub get_portfolio_access {
1.767     albertel 3706:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3707: 
                   3708:     if (!ref($access_hash)) {
                   3709: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3710: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3711: 						   $file_name);
                   3712: 	$access_hash = $access_controls{$file_name};
                   3713:     }
                   3714: 
1.765     albertel 3715:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3716:     my $now = time;
                   3717:     if (ref($access_hash) eq 'HASH') {
                   3718:         foreach my $key (keys(%{$access_hash})) {
                   3719:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3720:             if ($start > $now) {
                   3721:                 next;
                   3722:             }
                   3723:             if ($end && $end<$now) {
                   3724:                 next;
                   3725:             }
                   3726:             if ($scope eq 'public') {
                   3727:                 $public = $key;
                   3728:                 last;
                   3729:             } elsif ($scope eq 'guest') {
                   3730:                 $guest = $key;
                   3731:             } elsif ($scope eq 'domains') {
                   3732:                 push(@domains,$key);
                   3733:             } elsif ($scope eq 'users') {
                   3734:                 push(@users,$key);
                   3735:             } elsif ($scope eq 'course') {
                   3736:                 push(@courses,$key);
                   3737:             } elsif ($scope eq 'group') {
                   3738:                 push(@groups,$key);
                   3739:             }
                   3740:         }
                   3741:         if ($public) {
                   3742:             return 'ok';
                   3743:         }
                   3744:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3745:             if ($guest) {
                   3746:                 return $guest;
                   3747:             }
                   3748:         } else {
                   3749:             if (@domains > 0) {
                   3750:                 foreach my $domkey (@domains) {
                   3751:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3752:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3753:                             return 'ok';
                   3754:                         }
                   3755:                     }
                   3756:                 }
                   3757:             }
                   3758:             if (@users > 0) {
                   3759:                 foreach my $userkey (@users) {
1.865     raeburn  3760:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3761:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3762:                             if (ref($item) eq 'HASH') {
                   3763:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3764:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3765:                                     return 'ok';
                   3766:                                 }
                   3767:                             }
                   3768:                         }
                   3769:                     } 
1.765     albertel 3770:                 }
                   3771:             }
                   3772:             my %roleshash;
                   3773:             my @courses_and_groups = @courses;
                   3774:             push(@courses_and_groups,@groups); 
                   3775:             if (@courses_and_groups > 0) {
                   3776:                 my (%allgroups,%allroles); 
                   3777:                 my ($start,$end,$role,$sec,$group);
                   3778:                 foreach my $envkey (%env) {
1.811     albertel 3779:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3780:                         my $cid = $2.'_'.$3; 
                   3781:                         if ($1 eq 'gr') {
                   3782:                             $group = $4;
                   3783:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3784:                         } else {
                   3785:                             if ($4 eq '') {
                   3786:                                 $sec = 'none';
                   3787:                             } else {
                   3788:                                 $sec = $4;
                   3789:                             }
                   3790:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3791:                         }
1.811     albertel 3792:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3793:                         my $cid = $2.'_'.$3;
                   3794:                         if ($4 eq '') {
                   3795:                             $sec = 'none';
                   3796:                         } else {
                   3797:                             $sec = $4;
                   3798:                         }
                   3799:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3800:                     }
                   3801:                 }
                   3802:                 if (keys(%allroles) == 0) {
                   3803:                     return;
                   3804:                 }
                   3805:                 foreach my $key (@courses_and_groups) {
                   3806:                     my %content = %{$$access_hash{$key}};
                   3807:                     my $cnum = $content{'number'};
                   3808:                     my $cdom = $content{'domain'};
                   3809:                     my $cid = $cdom.'_'.$cnum;
                   3810:                     if (!exists($allroles{$cid})) {
                   3811:                         next;
                   3812:                     }    
                   3813:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3814:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3815:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3816:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3817:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3818:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3819:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3820:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3821:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3822:                                         if (grep/^all$/,@sections) {
                   3823:                                             return 'ok';
                   3824:                                         } else {
                   3825:                                             if (grep/^$sec$/,@sections) {
                   3826:                                                 return 'ok';
                   3827:                                             }
                   3828:                                         }
                   3829:                                     }
                   3830:                                 }
                   3831:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3832:                                     if (grep/^none$/,@groups) {
                   3833:                                         return 'ok';
                   3834:                                     }
                   3835:                                 } else {
                   3836:                                     if (grep/^all$/,@groups) {
                   3837:                                         return 'ok';
                   3838:                                     } 
                   3839:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3840:                                         if (grep/^$group$/,@groups) {
                   3841:                                             return 'ok';
                   3842:                                         }
                   3843:                                     }
                   3844:                                 } 
                   3845:                             }
                   3846:                         }
                   3847:                     }
                   3848:                 }
                   3849:             }
                   3850:             if ($guest) {
                   3851:                 return $guest;
                   3852:             }
                   3853:         }
                   3854:     }
                   3855:     return;
                   3856: }
                   3857: 
                   3858: sub course_group_datechecker {
                   3859:     my ($dates,$now,$status) = @_;
                   3860:     my ($start,$end) = split(/\./,$dates);
                   3861:     if (!$start && !$end) {
                   3862:         return 'ok';
                   3863:     }
                   3864:     if (grep/^active$/,@{$status}) {
                   3865:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3866:             return 'ok';
                   3867:         }
                   3868:     }
                   3869:     if (grep/^previous$/,@{$status}) {
                   3870:         if ($end > $now ) {
                   3871:             return 'ok';
                   3872:         }
                   3873:     }
                   3874:     if (grep/^future$/,@{$status}) {
                   3875:         if ($start > $now) {
                   3876:             return 'ok';
                   3877:         }
                   3878:     }
                   3879:     return; 
                   3880: }
                   3881: 
                   3882: sub parse_portfolio_url {
                   3883:     my ($url) = @_;
                   3884: 
                   3885:     my ($type,$udom,$unum,$group,$file_name);
                   3886:     
1.823     albertel 3887:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3888: 	$type = 1;
                   3889:         $udom = $1;
                   3890:         $unum = $2;
                   3891:         $file_name = $3;
1.823     albertel 3892:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3893: 	$type = 2;
                   3894:         $udom = $1;
                   3895:         $unum = $2;
                   3896:         $group = $3;
                   3897:         $file_name = $3.'/'.$4;
                   3898:     }
                   3899:     if (wantarray) {
                   3900: 	return ($type,$udom,$unum,$file_name,$group);
                   3901:     }
                   3902:     return $type;
                   3903: }
                   3904: 
                   3905: sub is_portfolio_url {
                   3906:     my ($url) = @_;
                   3907:     return scalar(&parse_portfolio_url($url));
                   3908: }
                   3909: 
1.798     raeburn  3910: sub is_portfolio_file {
                   3911:     my ($file) = @_;
1.820     raeburn  3912:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3913:         return 1;
                   3914:     }
                   3915:     return;
                   3916: }
                   3917: 
                   3918: 
1.341     www      3919: # ---------------------------------------------- Custom access rule evaluation
                   3920: 
                   3921: sub customaccess {
                   3922:     my ($priv,$uri)=@_;
1.807     albertel 3923:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3924:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3925:     $udom = &LONCAPA::clean_domain($udom);
                   3926:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3927:     my $access=0;
1.800     albertel 3928:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 3929: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   3930: 	if ($type eq 'user') {
                   3931: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 3932: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 3933: 		if ($tdom) {
                   3934: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   3935: 		}
1.896     albertel 3936: 		if ($tuname) {
                   3937: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 3938: 		}
                   3939: 		$access=($effect eq 'allow');
                   3940: 		last;
                   3941: 	    }
                   3942: 	} else {
                   3943: 	    if ($role) {
                   3944: 		if ($role ne $urole) { next; }
                   3945: 	    }
                   3946: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3947: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   3948: 		if ($tdom) {
                   3949: 		    if ($tdom ne $udom) { next; }
                   3950: 		}
                   3951: 		if ($tcrs) {
                   3952: 		    if ($tcrs ne $ucrs) { next; }
                   3953: 		}
                   3954: 		if ($tsec) {
                   3955: 		    if ($tsec ne $usec) { next; }
                   3956: 		}
                   3957: 		$access=($effect eq 'allow');
                   3958: 		last;
                   3959: 	    }
                   3960: 	    if ($realm eq '' && $role eq '') {
                   3961: 		$access=($effect eq 'allow');
                   3962: 	    }
1.402     bowersj2 3963: 	}
1.341     www      3964:     }
                   3965:     return $access;
                   3966: }
                   3967: 
1.103     harris41 3968: # ------------------------------------------------- Check for a user privilege
1.12      www      3969: 
                   3970: sub allowed {
1.810     raeburn  3971:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3972:     my $ver_orguri=$uri;
1.439     www      3973:     $uri=&deversion($uri);
1.152     www      3974:     my $orguri=$uri;
1.52      www      3975:     $uri=&declutter($uri);
1.809     raeburn  3976: 
1.810     raeburn  3977:     if ($priv eq 'evb') {
                   3978: # Evade communication block restrictions for specified role in a course
                   3979:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3980:             return $1;
                   3981:         } else {
                   3982:             return;
                   3983:         }
                   3984:     }
                   3985: 
1.620     albertel 3986:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3987: # Free bre access to adm and meta resources
1.775     albertel 3988:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3989: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3990: 	&& ($priv eq 'bre')) {
1.14      www      3991: 	return 'F';
1.159     www      3992:     }
                   3993: 
1.545     banghart 3994: # Free bre access to user's own portfolio contents
1.714     raeburn  3995:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3996:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3997: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3998:         my %setters;
                   3999:         my ($startblock,$endblock) = 
                   4000:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4001:         if ($startblock && $endblock) {
                   4002:             return 'B';
                   4003:         } else {
                   4004:             return 'F';
                   4005:         }
1.545     banghart 4006:     }
                   4007: 
1.762     raeburn  4008: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4009:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4010:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4011:         if (exists($env{'request.course.id'})) {
                   4012:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4013:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4014:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4015:                 my $courseprivid=$env{'request.course.id'};
                   4016:                 $courseprivid=~s/\_/\//;
                   4017:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4018:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4019:                     return $1; 
1.762     raeburn  4020:                 } else {
                   4021:                     if ($env{'request.course.sec'}) {
                   4022:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4023:                     }
                   4024:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4025:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4026:                         return $2;
                   4027:                     }
1.714     raeburn  4028:                 }
                   4029:             }
                   4030:         }
                   4031:     }
                   4032: 
1.159     www      4033: # Free bre to public access
                   4034: 
                   4035:     if ($priv eq 'bre') {
1.238     www      4036:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4037: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4038:            return 'F'; 
                   4039:         }
1.238     www      4040:         if ($copyright eq 'priv') {
                   4041:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4042: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4043: 		return '';
                   4044:             }
                   4045:         }
                   4046:         if ($copyright eq 'domain') {
                   4047:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4048: 	    unless (($env{'user.domain'} eq $1) ||
                   4049:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4050: 		return '';
                   4051:             }
1.262     matthew  4052:         }
1.620     albertel 4053:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4054:             # Library role, so allow browsing of resources in this domain.
                   4055:             return 'F';
1.238     www      4056:         }
1.341     www      4057:         if ($copyright eq 'custom') {
                   4058: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4059:         }
1.14      www      4060:     }
1.264     matthew  4061:     # Domain coordinator is trying to create a course
1.620     albertel 4062:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4063:         # uri is the requested domain in this case.
                   4064:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4065:         # a role of dc for the domain in question.
1.620     albertel 4066:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4067:     }
1.29      www      4068: 
1.52      www      4069:     my $thisallowed='';
                   4070:     my $statecond=0;
                   4071:     my $courseprivid='';
                   4072: 
                   4073: # Course
                   4074: 
1.620     albertel 4075:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4076:        $thisallowed.=$1;
                   4077:     }
1.29      www      4078: 
1.52      www      4079: # Domain
                   4080: 
1.620     albertel 4081:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4082:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4083:        $thisallowed.=$1;
                   4084:     }
1.52      www      4085: 
                   4086: # Course: uri itself is a course
1.66      www      4087:     my $courseuri=$uri;
                   4088:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4089:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4090: 
1.620     albertel 4091:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4092:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4093:        $thisallowed.=$1;
                   4094:     }
1.29      www      4095: 
1.665     albertel 4096: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4097: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4098:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4099: 	$thisallowed='';
1.671     raeburn  4100:         my ($match)=&is_on_map($uri);
                   4101:         if ($match) {
                   4102:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4103:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4104:                 $thisallowed.=$1;
                   4105:             }
                   4106:         } else {
1.705     albertel 4107:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4108:             if ($refuri) {
                   4109:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4110:                     $thisallowed='F';
1.671     raeburn  4111:                 } else {
                   4112:                     $refuri=&declutter($refuri);
                   4113:                     my ($match) = &is_on_map($refuri);
                   4114:                     if ($match) {
                   4115:                         $thisallowed='F';
                   4116:                     }
1.669     raeburn  4117:                 }
1.671     raeburn  4118:             }
                   4119:         }
1.314     www      4120:     }
1.492     albertel 4121: 
1.766     albertel 4122:     if ($priv eq 'bre'
                   4123: 	&& $thisallowed ne 'F' 
                   4124: 	&& $thisallowed ne '2'
                   4125: 	&& &is_portfolio_url($uri)) {
                   4126: 	$thisallowed = &portfolio_access($uri);
                   4127:     }
                   4128:     
1.52      www      4129: # Full access at system, domain or course-wide level? Exit.
1.29      www      4130: 
                   4131:     if ($thisallowed=~/F/) {
                   4132: 	return 'F';
                   4133:     }
                   4134: 
1.52      www      4135: # If this is generating or modifying users, exit with special codes
1.29      www      4136: 
1.643     www      4137:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4138: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4139: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4140: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4141: 	    unless ($auname) { return $thisallowed; }
                   4142: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4143: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4144: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4145: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4146: 	}
1.52      www      4147: 	return $thisallowed;
                   4148:     }
                   4149: #
1.103     harris41 4150: # Gathered so far: system, domain and course wide privileges
1.52      www      4151: #
                   4152: # Course: See if uri or referer is an individual resource that is part of 
                   4153: # the course
                   4154: 
1.620     albertel 4155:     if ($env{'request.course.id'}) {
1.232     www      4156: 
1.620     albertel 4157:        $courseprivid=$env{'request.course.id'};
                   4158:        if ($env{'request.course.sec'}) {
                   4159:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4160:        }
                   4161:        $courseprivid=~s/\_/\//;
                   4162:        my $checkreferer=1;
1.232     www      4163:        my ($match,$cond)=&is_on_map($uri);
                   4164:        if ($match) {
                   4165:            $statecond=$cond;
1.620     albertel 4166:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4167:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4168:                $thisallowed.=$1;
                   4169:                $checkreferer=0;
                   4170:            }
1.29      www      4171:        }
1.83      www      4172:        
1.148     www      4173:        if ($checkreferer) {
1.620     albertel 4174: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4175:             unless ($refuri) {
1.800     albertel 4176:                 foreach my $key (keys(%env)) {
                   4177: 		    if ($key=~/^httpref\..*\*/) {
                   4178: 			my $pattern=$key;
1.156     www      4179:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4180:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4181:                         $pattern=~s/\//\\\//g;
1.152     www      4182:                         if ($orguri=~/$pattern/) {
1.800     albertel 4183: 			    $refuri=$env{$key};
1.148     www      4184:                         }
                   4185:                     }
1.191     harris41 4186:                 }
1.148     www      4187:             }
1.232     www      4188: 
1.148     www      4189:          if ($refuri) { 
1.152     www      4190: 	  $refuri=&declutter($refuri);
1.232     www      4191:           my ($match,$cond)=&is_on_map($refuri);
                   4192:             if ($match) {
                   4193:               my $refstatecond=$cond;
1.620     albertel 4194:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4195:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4196:                   $thisallowed.=$1;
1.53      www      4197:                   $uri=$refuri;
                   4198:                   $statecond=$refstatecond;
1.52      www      4199:               }
                   4200:           }
1.148     www      4201:         }
1.29      www      4202:        }
1.52      www      4203:    }
1.29      www      4204: 
1.52      www      4205: #
1.103     harris41 4206: # Gathered now: all privileges that could apply, and condition number
1.52      www      4207: # 
                   4208: #
                   4209: # Full or no access?
                   4210: #
1.29      www      4211: 
1.52      www      4212:     if ($thisallowed=~/F/) {
                   4213: 	return 'F';
                   4214:     }
1.29      www      4215: 
1.52      www      4216:     unless ($thisallowed) {
                   4217:         return '';
                   4218:     }
1.29      www      4219: 
1.52      www      4220: # Restrictions exist, deal with them
                   4221: #
                   4222: #   C:according to course preferences
                   4223: #   R:according to resource settings
                   4224: #   L:unless locked
                   4225: #   X:according to user session state
                   4226: #
                   4227: 
                   4228: # Possibly locked functionality, check all courses
1.54      www      4229: # Locks might take effect only after 10 minutes cache expiration for other
                   4230: # courses, and 2 minutes for current course
1.52      www      4231: 
                   4232:     my $envkey;
                   4233:     if ($thisallowed=~/L/) {
1.620     albertel 4234:         foreach $envkey (keys %env) {
1.54      www      4235:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4236:                my $courseid=$2;
                   4237:                my $roleid=$1.'.'.$2;
1.92      www      4238:                $courseid=~s/^\///;
1.54      www      4239:                my $expiretime=600;
1.620     albertel 4240:                if ($env{'request.role'} eq $roleid) {
1.54      www      4241: 		  $expiretime=120;
                   4242:                }
                   4243: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4244:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4245:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4246: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4247:                }
1.620     albertel 4248:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4249:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4250: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4251:                        &log($env{'user.domain'},$env{'user.name'},
                   4252:                             $env{'user.home'},
1.57      www      4253:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4254:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4255:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4256: 		       return '';
                   4257:                    }
                   4258:                }
1.620     albertel 4259:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4260:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4261: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4262:                        &log($env{'user.domain'},$env{'user.name'},
                   4263:                             $env{'user.home'},
1.57      www      4264:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4265:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4266:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4267: 		       return '';
                   4268:                    }
                   4269:                }
                   4270: 	   }
1.29      www      4271:        }
1.52      www      4272:     }
                   4273:    
                   4274: #
                   4275: # Rest of the restrictions depend on selected course
                   4276: #
                   4277: 
1.620     albertel 4278:     unless ($env{'request.course.id'}) {
1.766     albertel 4279: 	if ($thisallowed eq 'A') {
                   4280: 	    return 'A';
1.814     raeburn  4281:         } elsif ($thisallowed eq 'B') {
                   4282:             return 'B';
1.766     albertel 4283: 	} else {
                   4284: 	    return '1';
                   4285: 	}
1.52      www      4286:     }
1.29      www      4287: 
1.52      www      4288: #
                   4289: # Now user is definitely in a course
                   4290: #
1.53      www      4291: 
                   4292: 
                   4293: # Course preferences
                   4294: 
                   4295:    if ($thisallowed=~/C/) {
1.620     albertel 4296:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4297:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4298:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4299: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4300: 	   if ($priv ne 'pch') { 
                   4301: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4302: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4303: 			$env{'request.course.id'});
                   4304: 	   }
1.237     www      4305:            return '';
                   4306:        }
                   4307: 
1.620     albertel 4308:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4309: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4310: 	   if ($priv ne 'pch') { 
                   4311: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4312: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4313: 			$env{'request.course.id'});
                   4314: 	   }
1.54      www      4315:            return '';
                   4316:        }
1.53      www      4317:    }
                   4318: 
                   4319: # Resource preferences
                   4320: 
                   4321:    if ($thisallowed=~/R/) {
1.620     albertel 4322:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4323:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4324: 	   if ($priv ne 'pch') { 
                   4325: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4326: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4327: 	   }
                   4328: 	   return '';
1.54      www      4329:        }
1.53      www      4330:    }
1.30      www      4331: 
1.246     www      4332: # Restricted by state or randomout?
1.30      www      4333: 
1.52      www      4334:    if ($thisallowed=~/X/) {
1.620     albertel 4335:       if ($env{'acc.randomout'}) {
1.579     albertel 4336: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4337:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4338:             return ''; 
                   4339:          }
1.247     www      4340:       }
                   4341:       if (&condval($statecond)) {
1.52      www      4342: 	 return '2';
                   4343:       } else {
                   4344:          return '';
                   4345:       }
                   4346:    }
1.30      www      4347: 
1.766     albertel 4348:     if ($thisallowed eq 'A') {
                   4349: 	return 'A';
1.814     raeburn  4350:     } elsif ($thisallowed eq 'B') {
                   4351:         return 'B';
1.766     albertel 4352:     }
1.52      www      4353:    return 'F';
1.232     www      4354: }
                   4355: 
1.710     albertel 4356: sub split_uri_for_cond {
                   4357:     my $uri=&deversion(&declutter(shift));
                   4358:     my @uriparts=split(/\//,$uri);
                   4359:     my $filename=pop(@uriparts);
                   4360:     my $pathname=join('/',@uriparts);
                   4361:     return ($pathname,$filename);
                   4362: }
1.232     www      4363: # --------------------------------------------------- Is a resource on the map?
                   4364: 
                   4365: sub is_on_map {
1.710     albertel 4366:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4367:     #Trying to find the conditional for the file
1.620     albertel 4368:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4369: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4370:     if ($match) {
1.289     bowersj2 4371: 	return (1,$1);
                   4372:     } else {
1.434     www      4373: 	return (0,0);
1.289     bowersj2 4374:     }
1.12      www      4375: }
                   4376: 
1.427     www      4377: # --------------------------------------------------------- Get symb from alias
                   4378: 
                   4379: sub get_symb_from_alias {
                   4380:     my $symb=shift;
                   4381:     my ($map,$resid,$url)=&decode_symb($symb);
                   4382: # Already is a symb
                   4383:     if ($url) { return $symb; }
                   4384: # Must be an alias
                   4385:     my $aliassymb='';
                   4386:     my %bighash;
1.620     albertel 4387:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4388:                             &GDBM_READER(),0640)) {
                   4389:         my $rid=$bighash{'mapalias_'.$symb};
                   4390: 	if ($rid) {
                   4391: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4392: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4393: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4394: 	}
                   4395:         untie %bighash;
                   4396:     }
                   4397:     return $aliassymb;
                   4398: }
                   4399: 
1.12      www      4400: # ----------------------------------------------------------------- Define Role
                   4401: 
                   4402: sub definerole {
                   4403:   if (allowed('mcr','/')) {
                   4404:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4405:     foreach my $role (split(':',$sysrole)) {
                   4406: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4407:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4408:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4409: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4410:                return "refused:s:$crole&$cqual"; 
                   4411:             }
                   4412:         }
1.191     harris41 4413:     }
1.800     albertel 4414:     foreach my $role (split(':',$domrole)) {
                   4415: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4416:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4417:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4418: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4419:                return "refused:d:$crole&$cqual"; 
                   4420:             }
                   4421:         }
1.191     harris41 4422:     }
1.800     albertel 4423:     foreach my $role (split(':',$courole)) {
                   4424: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4425:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4426:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4427: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4428:                return "refused:c:$crole&$cqual"; 
                   4429:             }
                   4430:         }
1.191     harris41 4431:     }
1.620     albertel 4432:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4433:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4434: 	        "rolesdef_$rolename=".
                   4435:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4436:     return reply($command,$env{'user.home'});
1.12      www      4437:   } else {
                   4438:     return 'refused';
                   4439:   }
1.105     harris41 4440: }
                   4441: 
                   4442: # ---------------- Make a metadata query against the network of library servers
                   4443: 
                   4444: sub metadata_query {
1.244     matthew  4445:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4446:     my %rhash;
1.845     albertel 4447:     my %libserv = &all_library();
1.244     matthew  4448:     my @server_list = (defined($server_array) ? @$server_array
                   4449:                                               : keys(%libserv) );
                   4450:     for my $server (@server_list) {
1.118     harris41 4451: 	unless ($custom or $customshow) {
                   4452: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4453: 	    $rhash{$server}=$reply;
                   4454: 	}
                   4455: 	else {
                   4456: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4457: 			     &escape($custom).':'.&escape($customshow),
                   4458: 			     $server);
                   4459: 	    $rhash{$server}=$reply;
                   4460: 	}
1.112     harris41 4461:     }
1.118     harris41 4462:     return \%rhash;
1.240     www      4463: }
                   4464: 
                   4465: # ----------------------------------------- Send log queries and wait for reply
                   4466: 
                   4467: sub log_query {
                   4468:     my ($uname,$udom,$query,%filters)=@_;
                   4469:     my $uhome=&homeserver($uname,$udom);
                   4470:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4471:     my $uhost=&hostname($uhome);
1.800     albertel 4472:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4473:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4474:                        $uhome);
1.479     albertel 4475:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4476:     return get_query_reply($queryid);
                   4477: }
                   4478: 
1.818     raeburn  4479: # -------------------------- Update MySQL table for portfolio file
                   4480: 
                   4481: sub update_portfolio_table {
1.821     raeburn  4482:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4483:     my $homeserver = &homeserver($uname,$udom);
                   4484:     my $queryid=
1.821     raeburn  4485:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4486:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4487:     my $reply = &get_query_reply($queryid);
                   4488:     return $reply;
                   4489: }
                   4490: 
1.899     raeburn  4491: # -------------------------- Update MySQL allusers table
                   4492: 
                   4493: sub update_allusers_table {
                   4494:     my ($uname,$udom,$names) = @_;
                   4495:     my $homeserver = &homeserver($uname,$udom);
                   4496:     my $queryid=
                   4497:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4498:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4499:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4500:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4501:                'generation='.&escape($names->{'generation'}).'%%'.
                   4502:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4503:                'id='.&escape($names->{'id'}),$homeserver);
                   4504:     my $reply = &get_query_reply($queryid);
                   4505:     return $reply;
                   4506: }
                   4507: 
1.508     raeburn  4508: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4509: 
                   4510: sub fetch_enrollment_query {
1.511     raeburn  4511:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4512:     my $homeserver;
1.547     raeburn  4513:     my $maxtries = 1;
1.508     raeburn  4514:     if ($context eq 'automated') {
                   4515:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4516:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4517:     } else {
                   4518:         $homeserver = &homeserver($cnum,$dom);
                   4519:     }
1.838     albertel 4520:     my $host=&hostname($homeserver);
1.506     raeburn  4521:     my $cmd = '';
1.800     albertel 4522:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4523:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4524:     }
                   4525:     $cmd =~ s/%%$//;
                   4526:     $cmd = &escape($cmd);
                   4527:     my $query = 'fetchenrollment';
1.620     albertel 4528:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4529:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4530:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4531:         return 'error: '.$queryid;
                   4532:     }
1.506     raeburn  4533:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4534:     my $tries = 1;
                   4535:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4536:         $reply = &get_query_reply($queryid);
                   4537:         $tries ++;
                   4538:     }
1.526     raeburn  4539:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4540:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4541:     } else {
1.901     albertel 4542:         my @responses = split(/:/,$reply);
1.515     raeburn  4543:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4544:             foreach my $line (@responses) {
                   4545:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4546:                 $$replyref{$key} = $value;
                   4547:             }
                   4548:         } else {
1.506     raeburn  4549:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4550:             foreach my $line (@responses) {
                   4551:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4552:                 $$replyref{$key} = $value;
                   4553:                 if ($value > 0) {
1.800     albertel 4554:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4555:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4556:                         my $destname = $pathname.'/'.$filename;
                   4557:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4558:                         if ($xml_classlist =~ /^error/) {
                   4559:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4560:                         } else {
1.506     raeburn  4561:                             if ( open(FILE,">$destname") ) {
                   4562:                                 print FILE &unescape($xml_classlist);
                   4563:                                 close(FILE);
1.526     raeburn  4564:                             } else {
                   4565:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4566:                             }
                   4567:                         }
                   4568:                     }
                   4569:                 }
                   4570:             }
                   4571:         }
                   4572:         return 'ok';
                   4573:     }
                   4574:     return 'error';
                   4575: }
                   4576: 
1.242     www      4577: sub get_query_reply {
                   4578:     my $queryid=shift;
1.240     www      4579:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4580:     my $reply='';
                   4581:     for (1..100) {
                   4582: 	sleep 2;
                   4583:         if (-e $replyfile.'.end') {
1.448     albertel 4584: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4585: 		$reply = join('',<$fh>);
                   4586: 		close($fh);
1.240     www      4587: 	   } else { return 'error: reply_file_error'; }
1.242     www      4588:            return &unescape($reply);
                   4589: 	}
1.240     www      4590:     }
1.242     www      4591:     return 'timeout:'.$queryid;
1.240     www      4592: }
                   4593: 
                   4594: sub courselog_query {
1.241     www      4595: #
                   4596: # possible filters:
                   4597: # url: url or symb
                   4598: # username
                   4599: # domain
                   4600: # action: view, submit, grade
                   4601: # start: timestamp
                   4602: # end: timestamp
                   4603: #
1.240     www      4604:     my (%filters)=@_;
1.620     albertel 4605:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4606:     if ($filters{'url'}) {
                   4607: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4608:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4609:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4610:     }
1.620     albertel 4611:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4612:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4613:     return &log_query($cname,$cdom,'courselog',%filters);
                   4614: }
                   4615: 
                   4616: sub userlog_query {
1.858     raeburn  4617: #
                   4618: # possible filters:
                   4619: # action: log check role
                   4620: # start: timestamp
                   4621: # end: timestamp
                   4622: #
1.240     www      4623:     my ($uname,$udom,%filters)=@_;
                   4624:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4625: }
                   4626: 
1.506     raeburn  4627: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4628: 
                   4629: sub auto_run {
1.508     raeburn  4630:     my ($cnum,$cdom) = @_;
1.876     raeburn  4631:     my $response = 0;
                   4632:     my $settings;
                   4633:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4634:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4635:         $settings = $domconfig{'autoenroll'};
                   4636:         if ($settings->{'run'} eq '1') {
                   4637:             $response = 1;
                   4638:         }
                   4639:     } else {
                   4640:         my $homeserver = &homeserver($cnum,$cdom);
                   4641:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4642:     }
1.506     raeburn  4643:     return $response;
                   4644: }
1.776     albertel 4645: 
1.506     raeburn  4646: sub auto_get_sections {
1.508     raeburn  4647:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4648:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4649:     my @secs = ();
1.511     raeburn  4650:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4651:     unless ($response eq 'refused') {
1.901     albertel 4652:         @secs = split(/:/,$response);
1.506     raeburn  4653:     }
                   4654:     return @secs;
                   4655: }
1.776     albertel 4656: 
1.506     raeburn  4657: sub auto_new_course {
1.508     raeburn  4658:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4659:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4660:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4661:     return $response;
                   4662: }
1.776     albertel 4663: 
1.506     raeburn  4664: sub auto_validate_courseID {
1.508     raeburn  4665:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4666:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4667:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4668:     return $response;
                   4669: }
1.776     albertel 4670: 
1.506     raeburn  4671: sub auto_create_password {
1.873     raeburn  4672:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4673:     my ($homeserver,$response);
1.506     raeburn  4674:     my $create_passwd = 0;
                   4675:     my $authchk = '';
1.873     raeburn  4676:     if ($udom =~ /^$match_domain$/) {
                   4677:         $homeserver = &domain($udom,'primary');
                   4678:     }
                   4679:     if ($homeserver eq '') {
                   4680:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4681:             $homeserver = &homeserver($cnum,$cdom);
                   4682:         }
                   4683:     }
                   4684:     if ($homeserver eq '') {
                   4685:         $authchk = 'nodomain';
1.506     raeburn  4686:     } else {
1.873     raeburn  4687:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4688:         if ($response eq 'refused') {
                   4689:             $authchk = 'refused';
                   4690:         } else {
1.901     albertel 4691:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4692:         }
1.506     raeburn  4693:     }
                   4694:     return ($authparam,$create_passwd,$authchk);
                   4695: }
                   4696: 
1.706     raeburn  4697: sub auto_photo_permission {
                   4698:     my ($cnum,$cdom,$students) = @_;
                   4699:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4700:     my ($outcome,$perm_reqd,$conditions) = 
                   4701: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4702:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4703: 	return (undef,undef);
                   4704:     }
1.706     raeburn  4705:     return ($outcome,$perm_reqd,$conditions);
                   4706: }
                   4707: 
                   4708: sub auto_checkphotos {
                   4709:     my ($uname,$udom,$pid) = @_;
                   4710:     my $homeserver = &homeserver($uname,$udom);
                   4711:     my ($result,$resulttype);
                   4712:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4713: 				   &escape($uname).':'.&escape($pid),
                   4714: 				   $homeserver));
1.709     albertel 4715:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4716: 	return (undef,undef);
                   4717:     }
1.706     raeburn  4718:     if ($outcome) {
                   4719:         ($result,$resulttype) = split(/:/,$outcome);
                   4720:     } 
                   4721:     return ($result,$resulttype);
                   4722: }
                   4723: 
                   4724: sub auto_photochoice {
                   4725:     my ($cnum,$cdom) = @_;
                   4726:     my $homeserver = &homeserver($cnum,$cdom);
                   4727:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4728: 						       &escape($cdom),
                   4729: 						       $homeserver)));
1.709     albertel 4730:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4731: 	return (undef,undef);
                   4732:     }
1.706     raeburn  4733:     return ($update,$comment);
                   4734: }
                   4735: 
                   4736: sub auto_photoupdate {
                   4737:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4738:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4739:     my $host=&hostname($homeserver);
1.706     raeburn  4740:     my $cmd = '';
                   4741:     my $maxtries = 1;
1.800     albertel 4742:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4743:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4744:     }
                   4745:     $cmd =~ s/%%$//;
                   4746:     $cmd = &escape($cmd);
                   4747:     my $query = 'institutionalphotos';
                   4748:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4749:     unless ($queryid=~/^\Q$host\E\_/) {
                   4750:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4751:         return 'error: '.$queryid;
                   4752:     }
                   4753:     my $reply = &get_query_reply($queryid);
                   4754:     my $tries = 1;
                   4755:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4756:         $reply = &get_query_reply($queryid);
                   4757:         $tries ++;
                   4758:     }
                   4759:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4760:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4761:     } else {
                   4762:         my @responses = split(/:/,$reply);
                   4763:         my $outcome = shift(@responses); 
                   4764:         foreach my $item (@responses) {
                   4765:             my ($key,$value) = split(/=/,$item);
                   4766:             $$photo{$key} = $value;
                   4767:         }
                   4768:         return $outcome;
                   4769:     }
                   4770:     return 'error';
                   4771: }
                   4772: 
1.521     raeburn  4773: sub auto_instcode_format {
1.793     albertel 4774:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4775: 	$cat_order) = @_;
1.521     raeburn  4776:     my $courses = '';
1.772     raeburn  4777:     my @homeservers;
1.521     raeburn  4778:     if ($caller eq 'global') {
1.841     albertel 4779: 	my %servers = &get_servers($codedom,'library');
                   4780: 	foreach my $tryserver (keys(%servers)) {
                   4781: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4782: 		push(@homeservers,$tryserver);
                   4783: 	    }
1.584     raeburn  4784:         }
1.521     raeburn  4785:     } else {
1.772     raeburn  4786:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4787:     }
1.793     albertel 4788:     foreach my $code (keys(%{$instcodes})) {
                   4789:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4790:     }
                   4791:     chop($courses);
1.772     raeburn  4792:     my $ok_response = 0;
                   4793:     my $response;
                   4794:     while (@homeservers > 0 && $ok_response == 0) {
                   4795:         my $server = shift(@homeservers); 
                   4796:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4797:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4798:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4799: 		split(/:/,$response);
1.772     raeburn  4800:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4801:             push(@{$codetitles},&str2array($codetitles_str));
                   4802:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4803:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4804:             $ok_response = 1;
                   4805:         }
                   4806:     }
                   4807:     if ($ok_response) {
1.521     raeburn  4808:         return 'ok';
1.772     raeburn  4809:     } else {
                   4810:         return $response;
1.521     raeburn  4811:     }
                   4812: }
                   4813: 
1.792     raeburn  4814: sub auto_instcode_defaults {
                   4815:     my ($domain,$returnhash,$code_order) = @_;
                   4816:     my @homeservers;
1.841     albertel 4817: 
                   4818:     my %servers = &get_servers($domain,'library');
                   4819:     foreach my $tryserver (keys(%servers)) {
                   4820: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4821: 	    push(@homeservers,$tryserver);
                   4822: 	}
1.792     raeburn  4823:     }
1.841     albertel 4824: 
1.792     raeburn  4825:     my $response;
1.841     albertel 4826:     foreach my $server (@homeservers) {
1.792     raeburn  4827:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4828:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4829: 	
                   4830: 	foreach my $pair (split(/\&/,$response)) {
                   4831: 	    my ($name,$value)=split(/\=/,$pair);
                   4832: 	    if ($name eq 'code_order') {
                   4833: 		@{$code_order} = split(/\&/,&unescape($value));
                   4834: 	    } else {
                   4835: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4836: 	    }
                   4837: 	}
                   4838: 	return 'ok';
1.792     raeburn  4839:     }
1.841     albertel 4840: 
                   4841:     return $response;
1.792     raeburn  4842: } 
                   4843: 
1.777     albertel 4844: sub auto_validate_class_sec {
1.773     raeburn  4845:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4846:     my $homeserver = &homeserver($cnum,$cdom);
                   4847:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4848:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4849:     return $response;
                   4850: }
                   4851: 
1.679     raeburn  4852: # ------------------------------------------------------- Course Group routines
                   4853: 
                   4854: sub get_coursegroups {
1.809     raeburn  4855:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4856:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4857: }
                   4858: 
1.679     raeburn  4859: sub modify_coursegroup {
                   4860:     my ($cdom,$cnum,$groupsettings) = @_;
                   4861:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4862: }
                   4863: 
1.809     raeburn  4864: sub toggle_coursegroup_status {
                   4865:     my ($cdom,$cnum,$group,$action) = @_;
                   4866:     my ($from_namespace,$to_namespace);
                   4867:     if ($action eq 'delete') {
                   4868:         $from_namespace = 'coursegroups';
                   4869:         $to_namespace = 'deleted_groups';
                   4870:     } else {
                   4871:         $from_namespace = 'deleted_groups';
                   4872:         $to_namespace = 'coursegroups';
                   4873:     }
                   4874:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4875:     if (my $tmp = &error(%curr_group)) {
                   4876:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4877:         return ('read error',$tmp);
                   4878:     } else {
                   4879:         my %savedsettings = %curr_group; 
1.809     raeburn  4880:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4881:         my $deloutcome;
                   4882:         if ($result eq 'ok') {
1.809     raeburn  4883:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4884:         } else {
                   4885:             return ('write error',$result);
                   4886:         }
                   4887:         if ($deloutcome eq 'ok') {
                   4888:             return 'ok';
                   4889:         } else {
                   4890:             return ('delete error',$deloutcome);
                   4891:         }
                   4892:     }
                   4893: }
                   4894: 
1.679     raeburn  4895: sub modify_group_roles {
                   4896:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4897:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4898:     my $role = 'gr/'.&escape($userprivs);
                   4899:     my ($uname,$udom) = split(/:/,$user);
                   4900:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4901:     if ($result eq 'ok') {
                   4902:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4903:     }
1.679     raeburn  4904:     return $result;
                   4905: }
                   4906: 
                   4907: sub modify_coursegroup_membership {
                   4908:     my ($cdom,$cnum,$membership) = @_;
                   4909:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4910:     return $result;
                   4911: }
                   4912: 
1.682     raeburn  4913: sub get_active_groups {
                   4914:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4915:     my $now = time;
                   4916:     my %groups = ();
                   4917:     foreach my $key (keys(%env)) {
1.811     albertel 4918:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4919:             my ($start,$end) = split(/\./,$env{$key});
                   4920:             if (($end!=0) && ($end<$now)) { next; }
                   4921:             if (($start!=0) && ($start>$now)) { next; }
                   4922:             if ($1 eq $cdom && $2 eq $cnum) {
                   4923:                 $groups{$3} = $env{$key} ;
                   4924:             }
                   4925:         }
                   4926:     }
                   4927:     return %groups;
                   4928: }
                   4929: 
1.683     raeburn  4930: sub get_group_membership {
                   4931:     my ($cdom,$cnum,$group) = @_;
                   4932:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4933: }
                   4934: 
                   4935: sub get_users_groups {
                   4936:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4937:     my @usersgroups;
1.683     raeburn  4938:     my $cachetime=1800;
                   4939: 
                   4940:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4941:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4942:     if (defined($cached)) {
1.734     albertel 4943:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4944:     } else {  
                   4945:         $grouplist = '';
1.816     raeburn  4946:         my $courseurl = &courseid_to_courseurl($courseid);
                   4947:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4948:         my $access_end = $env{'course.'.$courseid.
                   4949:                               '.default_enrollment_end_date'};
                   4950:         my $now = time;
                   4951:         foreach my $key (keys(%roleshash)) {
                   4952:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4953:                 my $group = $1;
                   4954:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4955:                     my $start = $2;
                   4956:                     my $end = $1;
                   4957:                     if ($start == -1) { next; } # deleted from group
                   4958:                     if (($start!=0) && ($start>$now)) { next; }
                   4959:                     if (($end!=0) && ($end<$now)) {
                   4960:                         if ($access_end && $access_end < $now) {
                   4961:                             if ($access_end - $end < 86400) {
                   4962:                                 push(@usersgroups,$group);
1.733     raeburn  4963:                             }
                   4964:                         }
1.817     raeburn  4965:                         next;
1.733     raeburn  4966:                     }
1.817     raeburn  4967:                     push(@usersgroups,$group);
1.683     raeburn  4968:                 }
                   4969:             }
                   4970:         }
1.817     raeburn  4971:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4972:         $grouplist = join(':',@usersgroups);
                   4973:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4974:     }
1.733     raeburn  4975:     return @usersgroups;
1.683     raeburn  4976: }
                   4977: 
                   4978: sub devalidate_getgroups_cache {
                   4979:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4980:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4981: 
1.683     raeburn  4982:     my $hashid="$udom:$uname:$courseid";
                   4983:     &devalidate_cache_new('getgroups',$hashid);
                   4984: }
                   4985: 
1.12      www      4986: # ------------------------------------------------------------------ Plain Text
                   4987: 
                   4988: sub plaintext {
1.742     raeburn  4989:     my ($short,$type,$cid) = @_;
1.758     albertel 4990:     if ($short =~ /^cr/) {
                   4991: 	return (split('/',$short))[-1];
                   4992:     }
1.742     raeburn  4993:     if (!defined($cid)) {
                   4994:         $cid = $env{'request.course.id'};
                   4995:     }
                   4996:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4997:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4998:                                           '.plaintext'});
                   4999:     }
                   5000:     my %rolenames = (
                   5001:                       Course => 'std',
                   5002:                       Group => 'alt1',
                   5003:                     );
                   5004:     if (defined($type) && 
                   5005:          defined($rolenames{$type}) && 
                   5006:          defined($prp{$short}{$rolenames{$type}})) {
                   5007:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5008:     } else {
                   5009:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5010:     }
1.12      www      5011: }
                   5012: 
                   5013: # ----------------------------------------------------------------- Assign Role
                   5014: 
                   5015: sub assignrole {
1.357     www      5016:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5017:     my $mrole;
                   5018:     if ($role =~ /^cr\//) {
1.393     www      5019:         my $cwosec=$url;
1.811     albertel 5020:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5021: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5022:            &logthis('Refused custom assignrole: '.
                   5023:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5024: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5025:            return 'refused'; 
                   5026:         }
1.21      www      5027:         $mrole='cr';
1.678     raeburn  5028:     } elsif ($role =~ /^gr\//) {
                   5029:         my $cwogrp=$url;
1.811     albertel 5030:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5031:         unless (&allowed('mdg',$cwogrp)) {
                   5032:             &logthis('Refused group assignrole: '.
                   5033:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5034:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5035:             return 'refused';
                   5036:         }
                   5037:         $mrole='gr';
1.21      www      5038:     } else {
1.82      www      5039:         my $cwosec=$url;
1.811     albertel 5040:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5041:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5042:            &logthis('Refused assignrole: '.
                   5043:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5044: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5045:            return 'refused'; 
                   5046:         }
1.21      www      5047:         $mrole=$role;
                   5048:     }
1.620     albertel 5049:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5050:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5051:     if ($end) { $command.='_'.$end; }
1.21      www      5052:     if ($start) {
                   5053: 	if ($end) { 
1.81      www      5054:            $command.='_'.$start; 
1.21      www      5055:         } else {
1.81      www      5056:            $command.='_0_'.$start;
1.21      www      5057:         }
                   5058:     }
1.739     raeburn  5059:     my $origstart = $start;
                   5060:     my $origend = $end;
1.357     www      5061: # actually delete
                   5062:     if ($deleteflag) {
1.373     www      5063: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5064: # modify command to delete the role
1.620     albertel 5065:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5066:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5067: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5068: # set start and finish to negative values for userrolelog
                   5069:            $start=-1;
                   5070:            $end=-1;
                   5071:         }
                   5072:     }
                   5073: # send command
1.349     www      5074:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5075: # log new user role if status is ok
1.349     www      5076:     if ($answer eq 'ok') {
1.663     raeburn  5077: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5078: # for course roles, perform group memberships changes triggered by role change.
                   5079:         unless ($role =~ /^gr/) {
                   5080:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5081:                                              $origstart);
                   5082:         }
1.349     www      5083:     }
                   5084:     return $answer;
1.169     harris41 5085: }
                   5086: 
                   5087: # -------------------------------------------------- Modify user authentication
1.197     www      5088: # Overrides without validation
                   5089: 
1.169     harris41 5090: sub modifyuserauth {
                   5091:     my ($udom,$uname,$umode,$upass)=@_;
                   5092:     my $uhome=&homeserver($uname,$udom);
1.197     www      5093:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5094:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5095:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5096:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5097:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5098: 		     &escape($upass),$uhome);
1.620     albertel 5099:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5100:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5101:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5102:     &log($udom,,$uname,$uhome,
1.620     albertel 5103:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5104:                                      $env{'user.name'}.', '.$umode.
1.197     www      5105:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5106:     unless ($reply eq 'ok') {
1.197     www      5107:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5108: 	return 'error: '.$reply;
                   5109:     }   
1.170     harris41 5110:     return 'ok';
1.80      www      5111: }
                   5112: 
1.81      www      5113: # --------------------------------------------------------------- Modify a user
1.80      www      5114: 
1.81      www      5115: sub modifyuser {
1.206     matthew  5116:     my ($udom,    $uname, $uid,
                   5117:         $umode,   $upass, $first,
                   5118:         $middle,  $last,  $gene,
1.387     www      5119:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5120:     $udom= &LONCAPA::clean_domain($udom);
                   5121:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5122:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5123:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5124: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5125:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5126:                                      ' desiredhome not specified'). 
1.620     albertel 5127:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5128:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5129:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5130: # ----------------------------------------------------------------- Create User
1.406     albertel 5131:     if (($uhome eq 'no_host') && 
                   5132: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5133:         my $unhome='';
1.844     albertel 5134:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5135:             $unhome = $desiredhome;
1.620     albertel 5136: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5137: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5138:         } else { # load balancing routine for determining $unhome
1.81      www      5139:             my $loadm=10000000;
1.841     albertel 5140: 	    my %servers = &get_servers($udom,'library');
                   5141: 	    foreach my $tryserver (keys(%servers)) {
                   5142: 		my $answer=reply('load',$tryserver);
                   5143: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5144: 		    $loadm=$answer;
                   5145: 		    $unhome=$tryserver;
                   5146: 		}
1.80      www      5147: 	    }
                   5148:         }
                   5149:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5150: 	    return 'error: unable to find a home server for '.$uname.
                   5151:                    ' in domain '.$udom;
1.80      www      5152:         }
                   5153:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5154:                          &escape($upass),$unhome);
                   5155: 	unless ($reply eq 'ok') {
                   5156:             return 'error: '.$reply;
                   5157:         }   
1.230     stredwic 5158:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5159:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5160: 	    return 'error: unable verify users home machine.';
1.80      www      5161:         }
1.209     matthew  5162:     }   # End of creation of new user
1.80      www      5163: # ---------------------------------------------------------------------- Add ID
                   5164:     if ($uid) {
                   5165:        $uid=~tr/A-Z/a-z/;
                   5166:        my %uidhash=&idrget($udom,$uname);
1.196     www      5167:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5168:          && (!$forceid)) {
1.80      www      5169: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5170: 	      return 'error: user id "'.$uid.'" does not match '.
                   5171:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5172:           }
                   5173:        } else {
                   5174: 	  &idput($udom,($uname => $uid));
                   5175:        }
                   5176:     }
                   5177: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5178:     my @tmp=&get('environment',
1.899     raeburn  5179: 		   ['firstname','middlename','lastname','generation','id',
                   5180:                     'permanentemail'],
1.134     albertel 5181: 		   $udom,$uname);
1.313     matthew  5182:     my %names;
                   5183:     if ($tmp[0] =~ m/^error:.*/) { 
                   5184:         %names=(); 
                   5185:     } else {
                   5186:         %names = @tmp;
                   5187:     }
1.388     www      5188: #
                   5189: # Make sure to not trash student environment if instructor does not bother
                   5190: # to supply name and email information
                   5191: #
                   5192:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5193:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5194:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5195:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5196:     if ($email) {
                   5197:        $email=~s/[^\w\@\.\-\,]//gs;
                   5198:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5199: 			   $names{'critnotification'} = $email;
                   5200: 			   $names{'permanentemail'} = $email; }
                   5201:     }
1.899     raeburn  5202:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5203:     my $reply = &put('environment', \%names, $udom,$uname);
                   5204:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5205:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5206:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5207:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5208:              $umode.', '.$first.', '.$middle.', '.
                   5209: 	     $last.', '.$gene.' by '.
1.620     albertel 5210:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5211:     return 'ok';
1.80      www      5212: }
                   5213: 
1.81      www      5214: # -------------------------------------------------------------- Modify student
1.80      www      5215: 
1.81      www      5216: sub modifystudent {
                   5217:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5218:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5219:     if (!$cid) {
1.620     albertel 5220: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5221: 	    return 'not_in_class';
                   5222: 	}
1.80      www      5223:     }
                   5224: # --------------------------------------------------------------- Make the user
1.81      www      5225:     my $reply=&modifyuser
1.209     matthew  5226: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5227:          $desiredhome,$email);
1.80      www      5228:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5229:     # This will cause &modify_student_enrollment to get the uid from the
                   5230:     # students environment
                   5231:     $uid = undef if (!$forceid);
1.455     albertel 5232:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5233: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5234:     return $reply;
                   5235: }
                   5236: 
                   5237: sub modify_student_enrollment {
1.515     raeburn  5238:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5239:     my ($cdom,$cnum,$chome);
                   5240:     if (!$cid) {
1.620     albertel 5241: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5242: 	    return 'not_in_class';
                   5243: 	}
1.620     albertel 5244: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5245: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5246:     } else {
                   5247: 	($cdom,$cnum)=split(/_/,$cid);
                   5248:     }
1.620     albertel 5249:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5250:     if (!$chome) {
1.457     raeburn  5251: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5252:     }
1.455     albertel 5253:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5254:     # Make sure the user exists
1.81      www      5255:     my $uhome=&homeserver($uname,$udom);
                   5256:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5257: 	return 'error: no such user';
                   5258:     }
1.297     matthew  5259:     # Get student data if we were not given enough information
                   5260:     if (!defined($first)  || $first  eq '' || 
                   5261:         !defined($last)   || $last   eq '' || 
                   5262:         !defined($uid)    || $uid    eq '' || 
                   5263:         !defined($middle) || $middle eq '' || 
                   5264:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5265:         # They did not supply us with enough data to enroll the student, so
                   5266:         # we need to pick up more information.
1.297     matthew  5267:         my %tmp = &get('environment',
1.294     matthew  5268:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5269:                        ,$udom,$uname);
                   5270: 
1.800     albertel 5271:         #foreach my $key (keys(%tmp)) {
                   5272:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5273:         #}
1.294     matthew  5274:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5275:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5276:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5277:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5278:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5279:     }
1.556     albertel 5280:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5281:     my $reply=cput('classlist',
                   5282: 		   {"$uname:$udom" => 
1.515     raeburn  5283: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5284: 		   $cdom,$cnum);
1.81      www      5285:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5286: 	return 'error: '.$reply;
1.652     albertel 5287:     } else {
                   5288: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5289:     }
1.297     matthew  5290:     # Add student role to user
1.83      www      5291:     my $uurl='/'.$cid;
1.81      www      5292:     $uurl=~s/\_/\//g;
                   5293:     if ($usec) {
                   5294: 	$uurl.='/'.$usec;
                   5295:     }
                   5296:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5297: }
                   5298: 
1.556     albertel 5299: sub format_name {
                   5300:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5301:     my $name;
                   5302:     if ($first ne 'lastname') {
                   5303: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5304:     } else {
                   5305: 	if ($lastname=~/\S/) {
                   5306: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5307: 	    $name=~s/\s+,/,/;
                   5308: 	} else {
                   5309: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5310: 	}
                   5311:     }
                   5312:     $name=~s/^\s+//;
                   5313:     $name=~s/\s+$//;
                   5314:     $name=~s/\s+/ /g;
                   5315:     return $name;
                   5316: }
                   5317: 
1.84      www      5318: # ------------------------------------------------- Write to course preferences
                   5319: 
                   5320: sub writecoursepref {
                   5321:     my ($courseid,%prefs)=@_;
                   5322:     $courseid=~s/^\///;
                   5323:     $courseid=~s/\_/\//g;
                   5324:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5325:     my $chome=homeserver($cnum,$cdomain);
                   5326:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5327: 	return 'error: no such course';
                   5328:     }
                   5329:     my $cstring='';
1.800     albertel 5330:     foreach my $pref (keys(%prefs)) {
                   5331: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5332:     }
1.84      www      5333:     $cstring=~s/\&$//;
                   5334:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5335: }
                   5336: 
                   5337: # ---------------------------------------------------------- Make/modify course
                   5338: 
                   5339: sub createcourse {
1.741     raeburn  5340:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5341:         $course_owner,$crstype)=@_;
1.84      www      5342:     $url=&declutter($url);
                   5343:     my $cid='';
1.264     matthew  5344:     unless (&allowed('ccc',$udom)) {
1.84      www      5345:         return 'refused';
                   5346:     }
                   5347: # ------------------------------------------------------------------- Create ID
1.674     www      5348:    my $uname=int(1+rand(9)).
                   5349:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5350:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5351:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5352: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5353:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5354:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5355:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5356:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5357:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5358:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5359:            return 'error: unable to generate unique course-ID';
                   5360:        } 
                   5361:    }
1.264     matthew  5362: # ------------------------------------------------ Check supplied server name
1.620     albertel 5363:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5364:     if (! &is_library($course_server)) {
1.264     matthew  5365:         return 'error:bad server name '.$course_server;
                   5366:     }
1.84      www      5367: # ------------------------------------------------------------- Make the course
                   5368:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5369:                       $course_server);
1.84      www      5370:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5371:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5372:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5373: 	return 'error: no such course';
                   5374:     }
1.271     www      5375: # ----------------------------------------------------------------- Course made
1.516     raeburn  5376: # log existence
                   5377:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5378:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5379:                   &escape($crstype),$uhome);
1.358     www      5380:     &flushcourselogs();
                   5381: # set toplevel url
1.271     www      5382:     my $topurl=$url;
                   5383:     unless ($nonstandard) {
                   5384: # ------------------------------------------ For standard courses, make top url
                   5385:         my $mapurl=&clutter($url);
1.278     www      5386:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5387:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5388: <map>
                   5389: <resource id="1" type="start"></resource>
                   5390: <resource id="2" src="$mapurl"></resource>
                   5391: <resource id="3" type="finish"></resource>
                   5392: <link index="1" from="1" to="2"></link>
                   5393: <link index="2" from="2" to="3"></link>
                   5394: </map>
                   5395: ENDINITMAP
                   5396:         $topurl=&declutter(
1.638     albertel 5397:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5398:                           );
                   5399:     }
                   5400: # ----------------------------------------------------------- Write preferences
1.84      www      5401:     &writecoursepref($udom.'_'.$uname,
                   5402:                      ('description' => $description,
1.271     www      5403:                       'url'         => $topurl));
1.84      www      5404:     return '/'.$udom.'/'.$uname;
                   5405: }
                   5406: 
1.813     albertel 5407: sub is_course {
                   5408:     my ($cdom,$cnum) = @_;
                   5409:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5410: 				undef,'.');
                   5411:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5412:         return 1;
                   5413:     }
                   5414:     return 0;
                   5415: }
                   5416: 
1.21      www      5417: # ---------------------------------------------------------- Assign Custom Role
                   5418: 
                   5419: sub assigncustomrole {
1.357     www      5420:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5421:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5422:                        $end,$start,$deleteflag);
1.21      www      5423: }
                   5424: 
                   5425: # ----------------------------------------------------------------- Revoke Role
                   5426: 
                   5427: sub revokerole {
1.357     www      5428:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5429:     my $now=time;
1.357     www      5430:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5431: }
                   5432: 
                   5433: # ---------------------------------------------------------- Revoke Custom Role
                   5434: 
                   5435: sub revokecustomrole {
1.357     www      5436:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5437:     my $now=time;
1.357     www      5438:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5439:            $deleteflag);
1.17      www      5440: }
                   5441: 
1.533     banghart 5442: # ------------------------------------------------------------ Disk usage
1.535     albertel 5443: sub diskusage {
1.533     banghart 5444:     my ($udom,$uname,$directoryRoot)=@_;
                   5445:     $directoryRoot =~ s/\/$//;
1.535     albertel 5446:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5447:     return $listing;
1.512     banghart 5448: }
                   5449: 
1.566     banghart 5450: sub is_locked {
                   5451:     my ($file_name, $domain, $user) = @_;
                   5452:     my @check;
                   5453:     my $is_locked;
                   5454:     push @check, $file_name;
1.613     albertel 5455:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5456: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5457:     my ($tmp)=keys(%locked);
                   5458:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5459:     
1.566     banghart 5460:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5461:         $is_locked = 'false';
                   5462:         foreach my $entry (@{$locked{$file_name}}) {
                   5463:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5464:                $is_locked = 'true';
                   5465:                last;
1.745     raeburn  5466:            }
                   5467:        }
1.566     banghart 5468:     } else {
                   5469:         $is_locked = 'false';
                   5470:     }
                   5471: }
                   5472: 
1.759     albertel 5473: sub declutter_portfile {
                   5474:     my ($file) = @_;
1.833     albertel 5475:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5476:     return $file;
                   5477: }
                   5478: 
1.559     banghart 5479: # ------------------------------------------------------------- Mark as Read Only
                   5480: 
                   5481: sub mark_as_readonly {
                   5482:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5483:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5484:     my ($tmp)=keys(%current_permissions);
                   5485:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5486:     foreach my $file (@{$files}) {
1.759     albertel 5487: 	$file = &declutter_portfile($file);
1.561     banghart 5488:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5489:     }
1.613     albertel 5490:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5491:     return;
                   5492: }
                   5493: 
1.572     banghart 5494: # ------------------------------------------------------------Save Selected Files
                   5495: 
                   5496: sub save_selected_files {
                   5497:     my ($user, $path, @files) = @_;
                   5498:     my $filename = $user."savedfiles";
1.573     banghart 5499:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5500:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5501:     foreach my $file (@files) {
1.620     albertel 5502:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5503:     }
                   5504:     foreach my $file (@other_files) {
1.574     banghart 5505:         print (OUT $file."\n");
1.572     banghart 5506:     }
1.574     banghart 5507:     close (OUT);
1.572     banghart 5508:     return 'ok';
                   5509: }
                   5510: 
1.574     banghart 5511: sub clear_selected_files {
                   5512:     my ($user) = @_;
                   5513:     my $filename = $user."savedfiles";
                   5514:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5515:     print (OUT undef);
                   5516:     close (OUT);
                   5517:     return ("ok");    
                   5518: }
                   5519: 
1.572     banghart 5520: sub files_in_path {
                   5521:     my ($user, $path) = @_;
                   5522:     my $filename = $user."savedfiles";
                   5523:     my %return_files;
1.574     banghart 5524:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5525:     while (my $line_in = <IN>) {
1.574     banghart 5526:         chomp ($line_in);
                   5527:         my @paths_and_file = split (m!/!, $line_in);
                   5528:         my $file_part = pop (@paths_and_file);
                   5529:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5530:         $path_part.='/';
                   5531:         my $path_and_file = $path_part.$file_part;
                   5532:         if ($path_part eq $path) {
                   5533:             $return_files{$file_part}= 'selected';
                   5534:         }
                   5535:     }
1.574     banghart 5536:     close (IN);
                   5537:     return (\%return_files);
1.572     banghart 5538: }
                   5539: 
                   5540: # called in portfolio select mode, to show files selected NOT in current directory
                   5541: sub files_not_in_path {
                   5542:     my ($user, $path) = @_;
                   5543:     my $filename = $user."savedfiles";
                   5544:     my @return_files;
                   5545:     my $path_part;
1.800     albertel 5546:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5547:     while (my $line = <IN>) {
1.572     banghart 5548:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5549:         my @paths_and_file = split(m|/|, $line);
                   5550:         my $file_part = pop(@paths_and_file);
                   5551:         chomp($file_part);
                   5552:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5553:         $path_part .= '/';
                   5554:         my $path_and_file = $path_part.$file_part;
                   5555:         if ($path_part ne $path) {
1.800     albertel 5556:             push(@return_files, ($path_and_file));
1.572     banghart 5557:         }
                   5558:     }
1.800     albertel 5559:     close(OUT);
1.574     banghart 5560:     return (@return_files);
1.572     banghart 5561: }
                   5562: 
1.745     raeburn  5563: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5564: 
1.745     raeburn  5565: sub get_portfile_permissions {
                   5566:     my ($domain,$user) = @_;
1.613     albertel 5567:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5568:     my ($tmp)=keys(%current_permissions);
                   5569:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5570:     return \%current_permissions;
                   5571: }
                   5572: 
                   5573: #---------------------------------------------Get portfolio file access controls
                   5574: 
1.749     raeburn  5575: sub get_access_controls {
1.745     raeburn  5576:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5577:     my %access;
                   5578:     my $real_file = $file;
                   5579:     $file =~ s/\.meta$//;
1.745     raeburn  5580:     if (defined($file)) {
1.749     raeburn  5581:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5582:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5583:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5584:             }
                   5585:         }
1.745     raeburn  5586:     } else {
1.749     raeburn  5587:         foreach my $key (keys(%{$current_permissions})) {
                   5588:             if ($key =~ /\0accesscontrol$/) {
                   5589:                 if (defined($group)) {
                   5590:                     if ($key !~ m-^\Q$group\E/-) {
                   5591:                         next;
                   5592:                     }
                   5593:                 }
                   5594:                 my ($fullpath) = split(/\0/,$key);
                   5595:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5596:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5597:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5598:                     }
                   5599:                 }
                   5600:             }
                   5601:         }
                   5602:     }
                   5603:     return %access;
                   5604: }
                   5605: 
                   5606: sub modify_access_controls {
                   5607:     my ($file_name,$changes,$domain,$user)=@_;
                   5608:     my ($outcome,$deloutcome);
                   5609:     my %store_permissions;
                   5610:     my %new_values;
                   5611:     my %new_control;
                   5612:     my %translation;
                   5613:     my @deletions = ();
                   5614:     my $now = time;
                   5615:     if (exists($$changes{'activate'})) {
                   5616:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5617:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5618:             my $numnew = scalar(@newitems);
                   5619:             for (my $i=0; $i<$numnew; $i++) {
                   5620:                 my $newkey = $newitems[$i];
                   5621:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5622:                 if ($newkey =~ /^\d+:/) { 
                   5623:                     $newkey =~ s/^(\d+)/$newid/;
                   5624:                     $translation{$1} = $newid;
                   5625:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5626:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5627:                     $translation{$1} = $newid;
                   5628:                 }
1.749     raeburn  5629:                 $new_values{$file_name."\0".$newkey} = 
                   5630:                                           $$changes{'activate'}{$newitems[$i]};
                   5631:                 $new_control{$newkey} = $now;
                   5632:             }
                   5633:         }
                   5634:     }
                   5635:     my %todelete;
                   5636:     my %changed_items;
                   5637:     foreach my $action ('delete','update') {
                   5638:         if (exists($$changes{$action})) {
                   5639:             if (ref($$changes{$action}) eq 'HASH') {
                   5640:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5641:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5642:                     if ($action eq 'delete') { 
                   5643:                         $todelete{$itemnum} = 1;
                   5644:                     } else {
                   5645:                         $changed_items{$itemnum} = $key;
                   5646:                     }
                   5647:                 }
1.745     raeburn  5648:             }
                   5649:         }
1.749     raeburn  5650:     }
                   5651:     # get lock on access controls for file.
                   5652:     my $lockhash = {
                   5653:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5654:                                                        ':'.$env{'user.domain'},
                   5655:                    }; 
                   5656:     my $tries = 0;
                   5657:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5658:    
                   5659:     while (($gotlock ne 'ok') && $tries <3) {
                   5660:         $tries ++;
                   5661:         sleep 1;
                   5662:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5663:     }
                   5664:     if ($gotlock eq 'ok') {
                   5665:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5666:         my ($tmp)=keys(%curr_permissions);
                   5667:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5668:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5669:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5670:             if (ref($curr_controls) eq 'HASH') {
                   5671:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5672:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5673:                     if (defined($todelete{$itemnum})) {
                   5674:                         push(@deletions,$file_name."\0".$control_item);
                   5675:                     } else {
                   5676:                         if (defined($changed_items{$itemnum})) {
                   5677:                             $new_control{$changed_items{$itemnum}} = $now;
                   5678:                             push(@deletions,$file_name."\0".$control_item);
                   5679:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5680:                         } else {
                   5681:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5682:                         }
                   5683:                     }
1.745     raeburn  5684:                 }
                   5685:             }
                   5686:         }
1.749     raeburn  5687:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5688:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5689:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5690:         #  remove lock
                   5691:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5692:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5693:         my ($file,$group);
                   5694:         if (&is_course($domain,$user)) {
                   5695:             ($group,$file) = split(/\//,$file_name,2);
                   5696:         } else {
                   5697:             $file = $file_name;
                   5698:         }
                   5699:         my $sqlresult =
                   5700:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5701:                                     $group);
1.749     raeburn  5702:     } else {
                   5703:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5704:     }
1.749     raeburn  5705:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5706: }
                   5707: 
1.827     raeburn  5708: sub make_public_indefinitely {
                   5709:     my ($requrl) = @_;
                   5710:     my $now = time;
                   5711:     my $action = 'activate';
                   5712:     my $aclnum = 0;
                   5713:     if (&is_portfolio_url($requrl)) {
                   5714:         my (undef,$udom,$unum,$file_name,$group) =
                   5715:             &parse_portfolio_url($requrl);
                   5716:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5717:         my %access_controls = &get_access_controls($current_perms,
                   5718:                                                    $group,$file_name);
                   5719:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5720:             my ($num,$scope,$end,$start) = 
                   5721:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5722:             if ($scope eq 'public') {
                   5723:                 if ($start <= $now && $end == 0) {
                   5724:                     $action = 'none';
                   5725:                 } else {
                   5726:                     $action = 'update';
                   5727:                     $aclnum = $num;
                   5728:                 }
                   5729:                 last;
                   5730:             }
                   5731:         }
                   5732:         if ($action eq 'none') {
                   5733:              return 'ok';
                   5734:         } else {
                   5735:             my %changes;
                   5736:             my $newend = 0;
                   5737:             my $newstart = $now;
                   5738:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5739:             $changes{$action}{$newkey} = {
                   5740:                 type => 'public',
                   5741:                 time => {
                   5742:                     start => $newstart,
                   5743:                     end   => $newend,
                   5744:                 },
                   5745:             };
                   5746:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5747:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5748:             return $outcome;
                   5749:         }
                   5750:     } else {
                   5751:         return 'invalid';
                   5752:     }
                   5753: }
                   5754: 
1.745     raeburn  5755: #------------------------------------------------------Get Marked as Read Only
                   5756: 
                   5757: sub get_marked_as_readonly {
                   5758:     my ($domain,$user,$what,$group) = @_;
                   5759:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5760:     my @readonly_files;
1.629     banghart 5761:     my $cmp1=$what;
                   5762:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5763:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5764:         if (defined($group)) {
                   5765:             if ($file_name !~ m-^\Q$group\E/-) {
                   5766:                 next;
                   5767:             }
                   5768:         }
1.561     banghart 5769:         if (ref($value) eq "ARRAY"){
                   5770:             foreach my $stored_what (@{$value}) {
1.629     banghart 5771:                 my $cmp2=$stored_what;
1.759     albertel 5772:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5773:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5774:                 }
1.629     banghart 5775:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5776:                     push(@readonly_files, $file_name);
1.745     raeburn  5777:                     last;
1.563     banghart 5778:                 } elsif (!defined($what)) {
                   5779:                     push(@readonly_files, $file_name);
1.745     raeburn  5780:                     last;
1.561     banghart 5781:                 }
                   5782:             }
1.745     raeburn  5783:         }
1.561     banghart 5784:     }
                   5785:     return @readonly_files;
                   5786: }
1.577     banghart 5787: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5788: 
1.577     banghart 5789: sub get_marked_as_readonly_hash {
1.745     raeburn  5790:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5791:     my %readonly_files;
1.745     raeburn  5792:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5793:         if (defined($group)) {
                   5794:             if ($file_name !~ m-^\Q$group\E/-) {
                   5795:                 next;
                   5796:             }
                   5797:         }
1.577     banghart 5798:         if (ref($value) eq "ARRAY"){
                   5799:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5800:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5801:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5802:                         if ($lock_descriptor eq 'graded') {
                   5803:                             $readonly_files{$file_name} = 'graded';
                   5804:                         } elsif ($lock_descriptor eq 'handback') {
                   5805:                             $readonly_files{$file_name} = 'handback';
                   5806:                         } else {
                   5807:                             if (!exists($readonly_files{$file_name})) {
                   5808:                                 $readonly_files{$file_name} = 'locked';
                   5809:                             }
                   5810:                         }
1.745     raeburn  5811:                     }
1.750     banghart 5812:                 } 
1.577     banghart 5813:             }
                   5814:         } 
                   5815:     }
                   5816:     return %readonly_files;
                   5817: }
1.559     banghart 5818: # ------------------------------------------------------------ Unmark as Read Only
                   5819: 
                   5820: sub unmark_as_readonly {
1.629     banghart 5821:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5822:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5823:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5824:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5825:     my $symb_crs = $what;
                   5826:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5827:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5828:     my ($tmp)=keys(%current_permissions);
                   5829:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5830:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5831:     foreach my $file (@readonly_files) {
1.759     albertel 5832: 	my $clean_file = &declutter_portfile($file);
                   5833: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5834: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5835:         my @new_locks;
                   5836:         my @del_keys;
                   5837:         if (ref($current_locks) eq "ARRAY"){
                   5838:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5839:                 my $compare=$locker;
1.749     raeburn  5840:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5841:                     $compare=join('',@{$locker});
1.746     raeburn  5842:                     if ($compare ne $symb_crs) {
                   5843:                         push(@new_locks, $locker);
                   5844:                     }
1.563     banghart 5845:                 }
                   5846:             }
1.650     albertel 5847:             if (scalar(@new_locks) > 0) {
1.563     banghart 5848:                 $current_permissions{$file} = \@new_locks;
                   5849:             } else {
                   5850:                 push(@del_keys, $file);
1.613     albertel 5851:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5852:                 delete($current_permissions{$file});
1.563     banghart 5853:             }
                   5854:         }
1.561     banghart 5855:     }
1.613     albertel 5856:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5857:     return;
                   5858: }
1.512     banghart 5859: 
1.17      www      5860: # ------------------------------------------------------------ Directory lister
                   5861: 
                   5862: sub dirlist {
1.253     stredwic 5863:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5864: 
1.18      www      5865:     $uri=~s/^\///;
                   5866:     $uri=~s/\/$//;
1.253     stredwic 5867:     my ($udom, $uname);
                   5868:     (undef,$udom,$uname)=split(/\//,$uri);
                   5869:     if(defined($userdomain)) {
                   5870:         $udom = $userdomain;
                   5871:     }
                   5872:     if(defined($username)) {
                   5873:         $uname = $username;
                   5874:     }
                   5875: 
                   5876:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5877:     if(defined($alternateDirectoryRoot)) {
                   5878:         $dirRoot = $alternateDirectoryRoot;
                   5879:         $dirRoot =~ s/\/$//;
1.751     banghart 5880:     }
1.253     stredwic 5881: 
                   5882:     if($udom) {
                   5883:         if($uname) {
1.800     albertel 5884:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5885: 				 &homeserver($uname,$udom));
1.605     matthew  5886:             my @listing_results;
                   5887:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5888:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5889: 				  &homeserver($uname,$udom));
1.605     matthew  5890:                 @listing_results = split(/:/,$listing);
                   5891:             } else {
                   5892:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5893:             }
                   5894:             return @listing_results;
1.253     stredwic 5895:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5896:             my %allusers;
1.841     albertel 5897: 	    my %servers = &get_servers($udom,'library');
                   5898: 	    foreach my $tryserver (keys(%servers)) {
                   5899: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5900: 				     $udom, $tryserver);
                   5901: 		my @listing_results;
                   5902: 		if ($listing eq 'unknown_cmd') {
                   5903: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5904: 				      $udom, $tryserver);
                   5905: 		    @listing_results = split(/:/,$listing);
                   5906: 		} else {
                   5907: 		    @listing_results =
                   5908: 			map { &unescape($_); } split(/:/,$listing);
                   5909: 		}
                   5910: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5911: 		    $listing_results[0] ne 'empty'       &&
                   5912: 		    $listing_results[0] ne 'con_lost') {
                   5913: 		    foreach my $line (@listing_results) {
                   5914: 			my ($entry) = split(/&/,$line,2);
                   5915: 			$allusers{$entry} = 1;
                   5916: 		    }
                   5917: 		}
1.253     stredwic 5918:             }
                   5919:             my $alluserstr='';
1.800     albertel 5920:             foreach my $user (sort(keys(%allusers))) {
                   5921:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5922:             }
                   5923:             $alluserstr=~s/:$//;
                   5924:             return split(/:/,$alluserstr);
                   5925:         } else {
1.800     albertel 5926:             return ('missing user name');
1.253     stredwic 5927:         }
                   5928:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5929:         my @all_domains = sort(&all_domains());
                   5930:          foreach my $domain (@all_domains) {
                   5931:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5932:          }
                   5933:          return @all_domains;
                   5934:      } else {
1.800     albertel 5935:         return ('missing domain');
1.275     stredwic 5936:     }
                   5937: }
                   5938: 
                   5939: # --------------------------------------------- GetFileTimestamp
                   5940: # This function utilizes dirlist and returns the date stamp for
                   5941: # when it was last modified.  It will also return an error of -1
                   5942: # if an error occurs
                   5943: 
1.410     matthew  5944: ##
                   5945: ## FIXME: This subroutine assumes its caller knows something about the
                   5946: ## directory structure of the home server for the student ($root).
                   5947: ## Not a good assumption to make.  Since this is for looking up files
                   5948: ## in user directories, the full path should be constructed by lond, not
                   5949: ## whatever machine we request data from.
                   5950: ##
1.275     stredwic 5951: sub GetFileTimestamp {
                   5952:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5953:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5954:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5955:     my $subdir=$studentName.'__';
                   5956:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5957:     my $proname="$studentDomain/$subdir/$studentName";
                   5958:     $proname .= '/'.$filename;
1.375     matthew  5959:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5960:                                               $studentName, $root);
1.275     stredwic 5961:     my @stats = split('&', $fileStat);
                   5962:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5963:         # @stats contains first the filename, then the stat output
                   5964:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5965:     } else {
                   5966:         return -1;
1.253     stredwic 5967:     }
1.26      www      5968: }
                   5969: 
1.712     albertel 5970: sub stat_file {
                   5971:     my ($uri) = @_;
1.787     albertel 5972:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5973: 
1.712     albertel 5974:     my ($udom,$uname,$file,$dir);
                   5975:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5976: 	($udom,$uname,$file) =
1.811     albertel 5977: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5978: 	$file = 'userfiles/'.$file;
1.740     www      5979: 	$dir = &propath($udom,$uname);
1.712     albertel 5980:     }
                   5981:     if ($uri =~ m-^/res/-) {
                   5982: 	($udom,$uname) = 
1.807     albertel 5983: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5984: 	$file = $uri;
                   5985:     }
                   5986: 
                   5987:     if (!$udom || !$uname || !$file) {
                   5988: 	# unable to handle the uri
                   5989: 	return ();
                   5990:     }
                   5991: 
                   5992:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5993:     my @stats = split('&', $result);
1.721     banghart 5994:     
1.712     albertel 5995:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5996: 	shift(@stats); #filename is first
                   5997: 	return @stats;
                   5998:     }
                   5999:     return ();
                   6000: }
                   6001: 
1.26      www      6002: # -------------------------------------------------------- Value of a Condition
                   6003: 
1.713     albertel 6004: # gets the value of a specific preevaluated condition
                   6005: #    stored in the string  $env{user.state.<cid>}
                   6006: # or looks up a condition reference in the bighash and if if hasn't
                   6007: # already been evaluated recurses into docondval to get the value of
                   6008: # the condition, then memoizing it to 
                   6009: #   $env{user.state.<cid>.<condition>}
1.40      www      6010: sub directcondval {
                   6011:     my $number=shift;
1.620     albertel 6012:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6013: 	&Apache::lonuserstate::evalstate();
                   6014:     }
1.713     albertel 6015:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6016: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6017:     } elsif ($number =~ /^_/) {
                   6018: 	my $sub_condition;
                   6019: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6020: 		&GDBM_READER(),0640)) {
                   6021: 	    $sub_condition=$bighash{'conditions'.$number};
                   6022: 	    untie(%bighash);
                   6023: 	}
                   6024: 	my $value = &docondval($sub_condition);
                   6025: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6026: 	return $value;
                   6027:     }
1.620     albertel 6028:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6029:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6030:     } else {
                   6031:        return 2;
                   6032:     }
                   6033: }
                   6034: 
1.713     albertel 6035: # get the collection of conditions for this resource
1.26      www      6036: sub condval {
                   6037:     my $condidx=shift;
1.54      www      6038:     my $allpathcond='';
1.713     albertel 6039:     foreach my $cond (split(/\|/,$condidx)) {
                   6040: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6041: 	    $allpathcond.=
                   6042: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6043: 	}
1.191     harris41 6044:     }
1.54      www      6045:     $allpathcond=~s/\|$//;
1.713     albertel 6046:     return &docondval($allpathcond);
                   6047: }
                   6048: 
                   6049: #evaluates an expression of conditions
                   6050: sub docondval {
                   6051:     my ($allpathcond) = @_;
                   6052:     my $result=0;
                   6053:     if ($env{'request.course.id'}
                   6054: 	&& defined($allpathcond)) {
                   6055: 	my $operand='|';
                   6056: 	my @stack;
                   6057: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6058: 	    if ($chunk eq '(') {
                   6059: 		push @stack,($operand,$result);
                   6060: 	    } elsif ($chunk eq ')') {
                   6061: 		my $before=pop @stack;
                   6062: 		if (pop @stack eq '&') {
                   6063: 		    $result=$result>$before?$before:$result;
                   6064: 		} else {
                   6065: 		    $result=$result>$before?$result:$before;
                   6066: 		}
                   6067: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6068: 		$operand=$chunk;
                   6069: 	    } else {
                   6070: 		my $new=directcondval($chunk);
                   6071: 		if ($operand eq '&') {
                   6072: 		    $result=$result>$new?$new:$result;
                   6073: 		} else {
                   6074: 		    $result=$result>$new?$result:$new;
                   6075: 		}
                   6076: 	    }
                   6077: 	}
1.26      www      6078:     }
                   6079:     return $result;
1.421     albertel 6080: }
                   6081: 
                   6082: # ---------------------------------------------------- Devalidate courseresdata
                   6083: 
                   6084: sub devalidatecourseresdata {
                   6085:     my ($coursenum,$coursedomain)=@_;
                   6086:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6087:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6088: }
                   6089: 
1.763     www      6090: 
1.200     www      6091: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6092: #
                   6093: #  Parameters:
                   6094: #      $coursenum    - Number of the course.
                   6095: #      $coursedomain - Domain at which the course was created.
                   6096: #  Returns:
                   6097: #     A hash of the course parameters along (I think) with timestamps
                   6098: #     and version info.
1.877     foxr     6099: 
1.624     albertel 6100: sub get_courseresdata {
                   6101:     my ($coursenum,$coursedomain)=@_;
1.200     www      6102:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6103:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6104:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6105:     my %dumpreply;
1.417     albertel 6106:     unless (defined($cached)) {
1.624     albertel 6107: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6108: 	$result=\%dumpreply;
1.251     albertel 6109: 	my ($tmp) = keys(%dumpreply);
                   6110: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6111: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6112: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6113: 	    return $tmp;
1.416     albertel 6114: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6115: 	    $result=undef;
1.599     albertel 6116: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6117: 	}
                   6118:     }
1.624     albertel 6119:     return $result;
                   6120: }
                   6121: 
1.633     albertel 6122: sub devalidateuserresdata {
                   6123:     my ($uname,$udom)=@_;
                   6124:     my $hashid="$udom:$uname";
                   6125:     &devalidate_cache_new('userres',$hashid);
                   6126: }
                   6127: 
1.624     albertel 6128: sub get_userresdata {
                   6129:     my ($uname,$udom)=@_;
                   6130:     #most student don\'t have any data set, check if there is some data
                   6131:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6132: 
                   6133:     my $hashid="$udom:$uname";
                   6134:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6135:     if (!defined($cached)) {
                   6136: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6137: 	$result=\%resourcedata;
                   6138: 	&do_cache_new('userres',$hashid,$result,600);
                   6139:     }
                   6140:     my ($tmp)=keys(%$result);
                   6141:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6142: 	return $result;
                   6143:     }
                   6144:     #error 2 occurs when the .db doesn't exist
                   6145:     if ($tmp!~/error: 2 /) {
1.672     albertel 6146: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6147: 		 " Trying to get resource data for ".
                   6148: 		 $uname." at ".$udom.": ".
                   6149: 		 $tmp."</font>");
                   6150:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6151: 	#&EXT_cache_set($udom,$uname);
                   6152: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6153: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6154:     }
                   6155:     return $tmp;
                   6156: }
1.879     foxr     6157: #----------------------------------------------- resdata - return resource data
                   6158: #  Purpose:
                   6159: #    Return resource data for either users or for a course.
                   6160: #  Parameters:
                   6161: #     $name      - Course/user name.
                   6162: #     $domain    - Name of the domain the user/course is registered on.
                   6163: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6164: #     @which     - Array of names of resources desired.
                   6165: #  Returns:
                   6166: #     The value of the first reasource in @which that is found in the
                   6167: #     resource hash.
                   6168: #  Exceptional Conditions:
                   6169: #     If the $type passed in is not valid (not the string 'course' or 
                   6170: #     'user', an undefined  reference is returned.
                   6171: #     If none of the resources are found, an undef is returned
1.624     albertel 6172: sub resdata {
                   6173:     my ($name,$domain,$type,@which)=@_;
                   6174:     my $result;
                   6175:     if ($type eq 'course') {
                   6176: 	$result=&get_courseresdata($name,$domain);
                   6177:     } elsif ($type eq 'user') {
                   6178: 	$result=&get_userresdata($name,$domain);
                   6179:     }
                   6180:     if (!ref($result)) { return $result; }    
1.251     albertel 6181:     foreach my $item (@which) {
1.417     albertel 6182: 	if (defined($result->{$item})) {
                   6183: 	    return $result->{$item};
1.251     albertel 6184: 	}
1.250     albertel 6185:     }
1.291     albertel 6186:     return undef;
1.200     www      6187: }
                   6188: 
1.379     matthew  6189: #
                   6190: # EXT resource caching routines
                   6191: #
                   6192: 
                   6193: sub clear_EXT_cache_status {
1.383     albertel 6194:     &delenv('cache.EXT.');
1.379     matthew  6195: }
                   6196: 
                   6197: sub EXT_cache_status {
                   6198:     my ($target_domain,$target_user) = @_;
1.383     albertel 6199:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6200:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6201:         # We know already the user has no data
                   6202:         return 1;
                   6203:     } else {
                   6204:         return 0;
                   6205:     }
                   6206: }
                   6207: 
                   6208: sub EXT_cache_set {
                   6209:     my ($target_domain,$target_user) = @_;
1.383     albertel 6210:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6211:     #&appenv($cachename => time);
1.379     matthew  6212: }
                   6213: 
1.28      www      6214: # --------------------------------------------------------- Value of a Variable
1.58      www      6215: sub EXT {
1.715     albertel 6216: 
1.395     albertel 6217:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6218:     unless ($varname) { return ''; }
1.218     albertel 6219:     #get real user name/domain, courseid and symb
                   6220:     my $courseid;
1.359     albertel 6221:     my $publicuser;
1.427     www      6222:     if ($symbparm) {
                   6223: 	$symbparm=&get_symb_from_alias($symbparm);
                   6224:     }
1.218     albertel 6225:     if (!($uname && $udom)) {
1.790     albertel 6226:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6227:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6228:     } else {
1.620     albertel 6229: 	$courseid=$env{'request.course.id'};
1.218     albertel 6230:     }
1.48      www      6231:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6232:     my $rest;
1.320     albertel 6233:     if (defined($therest[0])) {
1.48      www      6234:        $rest=join('.',@therest);
                   6235:     } else {
                   6236:        $rest='';
                   6237:     }
1.320     albertel 6238: 
1.57      www      6239:     my $qualifierrest=$qualifier;
                   6240:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6241:     my $spacequalifierrest=$space;
                   6242:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6243:     if ($realm eq 'user') {
1.48      www      6244: # --------------------------------------------------------------- user.resource
                   6245: 	if ($space eq 'resource') {
1.651     albertel 6246: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6247: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6248: 		 &&
1.744     albertel 6249: 		 ($symbparm eq &symbread()) ) {	
                   6250: 		# if we are in the middle of processing the resource the
                   6251: 		# get the value we are planning on committing
                   6252:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6253:                     return $Apache::lonhomework::results{$qualifierrest};
                   6254:                 } else {
                   6255:                     return $Apache::lonhomework::history{$qualifierrest};
                   6256:                 }
1.335     albertel 6257: 	    } else {
1.359     albertel 6258: 		my %restored;
1.620     albertel 6259: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6260: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6261: 		} else {
                   6262: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6263: 		}
1.335     albertel 6264: 		return $restored{$qualifierrest};
                   6265: 	    }
1.48      www      6266: # ----------------------------------------------------------------- user.access
                   6267:         } elsif ($space eq 'access') {
1.218     albertel 6268: 	    # FIXME - not supporting calls for a specific user
1.48      www      6269:             return &allowed($qualifier,$rest);
                   6270: # ------------------------------------------ user.preferences, user.environment
                   6271:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6272: 	    if (($uname eq $env{'user.name'}) &&
                   6273: 		($udom eq $env{'user.domain'})) {
                   6274: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6275: 	    } else {
1.359     albertel 6276: 		my %returnhash;
                   6277: 		if (!$publicuser) {
                   6278: 		    %returnhash=&userenvironment($udom,$uname,
                   6279: 						 $qualifierrest);
                   6280: 		}
1.218     albertel 6281: 		return $returnhash{$qualifierrest};
                   6282: 	    }
1.48      www      6283: # ----------------------------------------------------------------- user.course
                   6284:         } elsif ($space eq 'course') {
1.218     albertel 6285: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6286:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6287: # ------------------------------------------------------------------- user.role
                   6288:         } elsif ($space eq 'role') {
1.218     albertel 6289: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6290:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6291:             if ($qualifier eq 'value') {
                   6292: 		return $role;
                   6293:             } elsif ($qualifier eq 'extent') {
                   6294:                 return $where;
                   6295:             }
                   6296: # ----------------------------------------------------------------- user.domain
                   6297:         } elsif ($space eq 'domain') {
1.218     albertel 6298:             return $udom;
1.48      www      6299: # ------------------------------------------------------------------- user.name
                   6300:         } elsif ($space eq 'name') {
1.218     albertel 6301:             return $uname;
1.48      www      6302: # ---------------------------------------------------- Any other user namespace
1.29      www      6303:         } else {
1.359     albertel 6304: 	    my %reply;
                   6305: 	    if (!$publicuser) {
                   6306: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6307: 	    }
                   6308: 	    return $reply{$qualifierrest};
1.48      www      6309:         }
1.236     www      6310:     } elsif ($realm eq 'query') {
                   6311: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6312:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6313: 						[$spacequalifierrest]);
1.620     albertel 6314: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6315:    } elsif ($realm eq 'request') {
1.48      www      6316: # ------------------------------------------------------------- request.browser
                   6317:         if ($space eq 'browser') {
1.430     www      6318: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6319: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6320: 		    return 1;
                   6321: 		} else {
                   6322: 		    return 0;
                   6323: 		}
                   6324: 	    } else {
1.620     albertel 6325: 		return $env{'browser.'.$qualifier};
1.430     www      6326: 	    }
1.57      www      6327: # ------------------------------------------------------------ request.filename
                   6328:         } else {
1.620     albertel 6329:             return $env{'request.'.$spacequalifierrest};
1.29      www      6330:         }
1.28      www      6331:     } elsif ($realm eq 'course') {
1.48      www      6332: # ---------------------------------------------------------- course.description
1.620     albertel 6333:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6334:     } elsif ($realm eq 'resource') {
1.165     www      6335: 
1.620     albertel 6336: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6337: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6338: 	}
1.693     albertel 6339: 
                   6340: 	if ($space eq 'title') {
                   6341: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6342: 	    return &gettitle($symbparm);
                   6343: 	}
                   6344: 	
                   6345: 	if ($space eq 'map') {
                   6346: 	    my ($map) = &decode_symb($symbparm);
                   6347: 	    return &symbread($map);
                   6348: 	}
1.905     albertel 6349: 	if ($space eq 'filename') {
                   6350: 	    if ($symbparm) {
                   6351: 		return &clutter((&decode_symb($symbparm))[2]);
                   6352: 	    }
                   6353: 	    return &hreflocation('',$env{'request.filename'});
                   6354: 	}
1.693     albertel 6355: 
                   6356: 	my ($section, $group, @groups);
1.593     albertel 6357: 	my ($courselevelm,$courselevel);
1.539     albertel 6358: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6359: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6360: 
1.218     albertel 6361: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6362: 
1.60      www      6363: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6364: 	    my $symbp=$symbparm;
1.735     albertel 6365: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6366: 
                   6367: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6368: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6369: 
1.620     albertel 6370: 	    if (($env{'user.name'} eq $uname) &&
                   6371: 		($env{'user.domain'} eq $udom)) {
                   6372: 		$section=$env{'request.course.sec'};
1.733     raeburn  6373:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6374:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6375: 	    } else {
1.539     albertel 6376: 		if (! defined($usection)) {
1.551     albertel 6377: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6378: 		} else {
                   6379: 		    $section = $usection;
                   6380: 		}
1.733     raeburn  6381:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6382: 	    }
                   6383: 
                   6384: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6385: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6386: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6387: 
1.593     albertel 6388: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6389: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6390: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6391: 
1.60      www      6392: # ----------------------------------------------------------- first, check user
1.624     albertel 6393: 
                   6394: 	    my $userreply=&resdata($uname,$udom,'user',
                   6395: 				       ($courselevelr,$courselevelm,
                   6396: 					$courselevel));
                   6397: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6398: 
1.594     albertel 6399: # ------------------------------------------------ second, check some of course
1.684     raeburn  6400:             my $coursereply;
1.691     raeburn  6401:             if (@groups > 0) {
                   6402:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6403:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6404:                 if (defined($coursereply)) { return $coursereply; }
                   6405:             }
1.96      www      6406: 
1.684     raeburn  6407: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6408: 				     $env{'course.'.$courseid.'.domain'},
                   6409: 				     'course',
                   6410: 				     ($seclevelr,$seclevelm,$seclevel,
                   6411: 				      $courselevelr));
1.287     albertel 6412: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6413: 
1.60      www      6414: # ------------------------------------------------------ third, check map parms
1.218     albertel 6415: 	    my %parmhash=();
                   6416: 	    my $thisparm='';
                   6417: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6418: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6419: 		    &GDBM_READER(),0640)) {
1.218     albertel 6420: 		$thisparm=$parmhash{$symbparm};
                   6421: 		untie(%parmhash);
                   6422: 	    }
                   6423: 	    if ($thisparm) { return $thisparm; }
                   6424: 	}
1.594     albertel 6425: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6426: 
1.218     albertel 6427: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6428: 	my $filename;
                   6429: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6430: 	if ($symbparm) {
1.409     www      6431: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6432: 	} else {
1.620     albertel 6433: 	    $filename=$env{'request.filename'};
1.282     albertel 6434: 	}
                   6435: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6436: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6437: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6438: 	if (defined($metadata)) { return $metadata; }
1.142     www      6439: 
1.594     albertel 6440: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6441: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6442: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6443: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6444: 				     $env{'course.'.$courseid.'.domain'},
                   6445: 				     'course',
                   6446: 				     ($courselevelm,$courselevel));
1.593     albertel 6447: 	    if (defined($coursereply)) { return $coursereply; }
                   6448: 	}
1.145     www      6449: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6450: 	unless ($space eq '0') {
1.336     albertel 6451: 	    my @parts=split(/_/,$space);
                   6452: 	    my $id=pop(@parts);
                   6453: 	    my $part=join('_',@parts);
                   6454: 	    if ($part eq '') { $part='0'; }
                   6455: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6456: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6457: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6458: 	}
1.395     albertel 6459: 	if ($recurse) { return undef; }
                   6460: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6461: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6462: 
1.48      www      6463: # ---------------------------------------------------- Any other user namespace
                   6464:     } elsif ($realm eq 'environment') {
                   6465: # ----------------------------------------------------------------- environment
1.620     albertel 6466: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6467: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6468: 	} else {
1.770     albertel 6469: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6470: 		return '';
                   6471: 	    }
1.219     albertel 6472: 	    my %returnhash=&userenvironment($udom,$uname,
                   6473: 					    $spacequalifierrest);
                   6474: 	    return $returnhash{$spacequalifierrest};
                   6475: 	}
1.28      www      6476:     } elsif ($realm eq 'system') {
1.48      www      6477: # ----------------------------------------------------------------- system.time
                   6478: 	if ($space eq 'time') {
                   6479: 	    return time;
                   6480:         }
1.696     albertel 6481:     } elsif ($realm eq 'server') {
                   6482: # ----------------------------------------------------------------- system.time
                   6483: 	if ($space eq 'name') {
                   6484: 	    return $ENV{'SERVER_NAME'};
                   6485:         }
1.28      www      6486:     }
1.48      www      6487:     return '';
1.61      www      6488: }
                   6489: 
1.691     raeburn  6490: sub check_group_parms {
                   6491:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6492:     my @groupitems = ();
                   6493:     my $resultitem;
                   6494:     my @levels = ($symbparm,$mapparm,$what);
                   6495:     foreach my $group (@{$groups}) {
                   6496:         foreach my $level (@levels) {
                   6497:              my $item = $courseid.'.['.$group.'].'.$level;
                   6498:              push(@groupitems,$item);
                   6499:         }
                   6500:     }
                   6501:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6502:                             $env{'course.'.$courseid.'.domain'},
                   6503:                                      'course',@groupitems);
                   6504:     return $coursereply;
                   6505: }
                   6506: 
                   6507: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6508:     my ($courseid,@groups) = @_;
                   6509:     @groups = sort(@groups);
1.691     raeburn  6510:     return @groups;
                   6511: }
                   6512: 
1.395     albertel 6513: sub packages_tab_default {
                   6514:     my ($uri,$varname)=@_;
                   6515:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6516: 
                   6517:     my (@extension,@specifics,$do_default);
                   6518:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6519: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6520: 	if ($pack_type eq 'default') {
                   6521: 	    $do_default=1;
                   6522: 	} elsif ($pack_type eq 'extension') {
                   6523: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6524: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6525: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6526: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6527: 	}
                   6528:     }
                   6529:     # first look for a package that matches the requested part id
                   6530:     foreach my $package (@specifics) {
                   6531: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6532: 	next if ($pack_part ne $part);
                   6533: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6534: 	    return $packagetab{"$pack_type&$name&default"};
                   6535: 	}
                   6536:     }
                   6537:     # look for any possible matching non extension_ package
                   6538:     foreach my $package (@specifics) {
                   6539: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6540: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6541: 	    return $packagetab{"$pack_type&$name&default"};
                   6542: 	}
1.585     albertel 6543: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6544: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6545: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6546: 	}
                   6547:     }
1.738     albertel 6548:     # look for any posible extension_ match
                   6549:     foreach my $package (@extension) {
                   6550: 	my ($package,$pack_type)=@{$package};
                   6551: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6552: 	    return $packagetab{"$pack_type&$name&default"};
                   6553: 	}
                   6554: 	if (defined($packagetab{$package."&$name&default"})) {
                   6555: 	    return $packagetab{$package."&$name&default"};
                   6556: 	}
                   6557:     }
                   6558:     # look for a global default setting
                   6559:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6560: 	return $packagetab{"default&$name&default"};
                   6561:     }
1.395     albertel 6562:     return undef;
                   6563: }
                   6564: 
1.334     albertel 6565: sub add_prefix_and_part {
                   6566:     my ($prefix,$part)=@_;
                   6567:     my $keyroot;
                   6568:     if (defined($prefix) && $prefix !~ /^__/) {
                   6569: 	# prefix that has a part already
                   6570: 	$keyroot=$prefix;
                   6571:     } elsif (defined($prefix)) {
                   6572: 	# prefix that is missing a part
                   6573: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6574:     } else {
                   6575: 	# no prefix at all
                   6576: 	if (defined($part)) { $keyroot='_'.$part; }
                   6577:     }
                   6578:     return $keyroot;
                   6579: }
                   6580: 
1.71      www      6581: # ---------------------------------------------------------------- Get metadata
                   6582: 
1.599     albertel 6583: my %metaentry;
1.71      www      6584: sub metadata {
1.176     www      6585:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6586:     $uri=&declutter($uri);
1.288     albertel 6587:     # if it is a non metadata possible uri return quickly
1.529     albertel 6588:     if (($uri eq '') || 
                   6589: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6590: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6591:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6592: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6593: 	return undef;
1.288     albertel 6594:     }
1.73      www      6595:     my $filename=$uri;
                   6596:     $uri=~s/\.meta$//;
1.172     www      6597: #
                   6598: # Is the metadata already cached?
1.177     www      6599: # Look at timestamp of caching
1.172     www      6600: # Everything is cached by the main uri, libraries are never directly cached
                   6601: #
1.428     albertel 6602:     if (!defined($liburi)) {
1.599     albertel 6603: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6604: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6605:     }
                   6606:     {
1.172     www      6607: #
                   6608: # Is this a recursive call for a library?
                   6609: #
1.599     albertel 6610: #	if (! exists($metacache{$uri})) {
                   6611: #	    $metacache{$uri}={};
                   6612: #	}
1.171     www      6613:         if ($liburi) {
                   6614: 	    $liburi=&declutter($liburi);
                   6615:             $filename=$liburi;
1.401     bowersj2 6616:         } else {
1.599     albertel 6617: 	    &devalidate_cache_new('meta',$uri);
                   6618: 	    undef(%metaentry);
1.401     bowersj2 6619: 	}
1.140     www      6620:         my %metathesekeys=();
1.73      www      6621:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6622: 	my $metastring;
1.768     albertel 6623: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6624: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6625: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6626: 	    $metastring=&getfile($file);
1.489     albertel 6627: 	}
1.208     albertel 6628:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6629:         my $token;
1.140     www      6630:         undef %metathesekeys;
1.71      www      6631:         while ($token=$parser->get_token) {
1.339     albertel 6632: 	    if ($token->[0] eq 'S') {
                   6633: 		if (defined($token->[2]->{'package'})) {
1.172     www      6634: #
                   6635: # This is a package - get package info
                   6636: #
1.339     albertel 6637: 		    my $package=$token->[2]->{'package'};
                   6638: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6639: 		    if (defined($token->[2]->{'id'})) { 
                   6640: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6641: 		    }
1.599     albertel 6642: 		    if ($metaentry{':packages'}) {
                   6643: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6644: 		    } else {
1.599     albertel 6645: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6646: 		    }
1.736     albertel 6647: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6648: 			my $part=$keyroot;
                   6649: 			$part=~s/^\_//;
1.736     albertel 6650: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6651: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6652: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6653: 			    # ignore package.tab specified default values
                   6654:                             # here &package_tab_default() will fetch those
                   6655: 			    if ($subp eq 'default') { next; }
1.736     albertel 6656: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6657: 			    my $unikey;
                   6658: 			    if ($pack =~ /_0$/) {
                   6659: 				$unikey='parameter_0_'.$name;
                   6660: 				$part=0;
                   6661: 			    } else {
                   6662: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6663: 			    }
1.339     albertel 6664: 			    if ($subp eq 'display') {
                   6665: 				$value.=' [Part: '.$part.']';
                   6666: 			    }
1.599     albertel 6667: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6668: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6669: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6670: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6671: 			    }
1.599     albertel 6672: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6673: 				$metaentry{':'.$unikey}=
                   6674: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6675: 			    }
1.339     albertel 6676: 			}
                   6677: 		    }
                   6678: 		} else {
1.172     www      6679: #
                   6680: # This is not a package - some other kind of start tag
1.339     albertel 6681: #
                   6682: 		    my $entry=$token->[1];
                   6683: 		    my $unikey;
                   6684: 		    if ($entry eq 'import') {
                   6685: 			$unikey='';
                   6686: 		    } else {
                   6687: 			$unikey=$entry;
                   6688: 		    }
                   6689: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6690: 
                   6691: 		    if (defined($token->[2]->{'id'})) { 
                   6692: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6693: 		    }
1.175     www      6694: 
1.339     albertel 6695: 		    if ($entry eq 'import') {
1.175     www      6696: #
                   6697: # Importing a library here
1.339     albertel 6698: #
                   6699: 			if ($depthcount<20) {
                   6700: 			    my $location=$parser->get_text('/import');
                   6701: 			    my $dir=$filename;
                   6702: 			    $dir=~s|[^/]*$||;
                   6703: 			    $location=&filelocation($dir,$location);
1.736     albertel 6704: 			    my $metadata = 
                   6705: 				&metadata($uri,'keys', $location,$unikey,
                   6706: 					  $depthcount+1);
                   6707: 			    foreach my $meta (split(',',$metadata)) {
                   6708: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6709: 				$metathesekeys{$meta}=1;
1.339     albertel 6710: 			    }
                   6711: 			}
                   6712: 		    } else { 
                   6713: 			
                   6714: 			if (defined($token->[2]->{'name'})) { 
                   6715: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6716: 			}
                   6717: 			$metathesekeys{$unikey}=1;
1.736     albertel 6718: 			foreach my $param (@{$token->[3]}) {
                   6719: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6720: 				$token->[2]->{$param};
1.339     albertel 6721: 			}
                   6722: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6723: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6724: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6725: 		 # only ws inside the tag, and not in default, so use default
                   6726: 		 # as value
1.599     albertel 6727: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6728: 			} elsif ( $internaltext =~ /\S/ ) {
                   6729: 		  # something interesting inside the tag
                   6730: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6731: 			} else {
1.908     albertel 6732: 		  # no interesting values, don't set a default
1.339     albertel 6733: 			}
1.172     www      6734: # end of not-a-package not-a-library import
1.339     albertel 6735: 		    }
1.172     www      6736: # end of not-a-package start tag
1.339     albertel 6737: 		}
1.172     www      6738: # the next is the end of "start tag"
1.339     albertel 6739: 	    }
                   6740: 	}
1.483     albertel 6741: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6742: 	$extension = lc($extension);
                   6743: 	if ($extension eq 'htm') { $extension='html'; }
                   6744: 
1.737     albertel 6745: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6746: 	    #no specific packages #how's our extension
                   6747: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6748: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6749: 					 \%metathesekeys);
                   6750: 	}
1.883     albertel 6751: 
                   6752: 	if (!exists($metaentry{':packages'})
                   6753: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6754: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6755: 		#no specific packages well let's get default then
                   6756: 		if ($key!~/^default&/) { next; }
1.488     albertel 6757: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6758: 					     \%metathesekeys);
                   6759: 	    }
                   6760: 	}
1.338     www      6761: # are there custom rights to evaluate
1.599     albertel 6762: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6763: 
1.338     www      6764:     #
                   6765:     # Importing a rights file here
1.339     albertel 6766:     #
                   6767: 	    unless ($depthcount) {
1.599     albertel 6768: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6769: 		my $dir=$filename;
                   6770: 		$dir=~s|[^/]*$||;
                   6771: 		$location=&filelocation($dir,$location);
1.736     albertel 6772: 		my $rights_metadata =
                   6773: 		    &metadata($uri,'keys',$location,'_rights',
                   6774: 			      $depthcount+1);
                   6775: 		foreach my $rights (split(',',$rights_metadata)) {
                   6776: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6777: 		    $metathesekeys{$rights}=1;
1.339     albertel 6778: 		}
                   6779: 	    }
                   6780: 	}
1.737     albertel 6781: 	# uniqifiy package listing
                   6782: 	my %seen;
                   6783: 	my @uniq_packages =
                   6784: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6785: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6786: 
                   6787: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6788: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6789: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6790: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6791: # this is the end of "was not already recently cached
1.71      www      6792:     }
1.599     albertel 6793:     return $metaentry{':'.$what};
1.261     albertel 6794: }
                   6795: 
1.488     albertel 6796: sub metadata_create_package_def {
1.483     albertel 6797:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6798:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6799:     if ($subp eq 'default') { next; }
                   6800:     
1.599     albertel 6801:     if (defined($metaentry{':packages'})) {
                   6802: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6803:     } else {
1.599     albertel 6804: 	$metaentry{':packages'}=$package;
1.483     albertel 6805:     }
                   6806:     my $value=$packagetab{$key};
                   6807:     my $unikey;
                   6808:     $unikey='parameter_0_'.$name;
1.599     albertel 6809:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6810:     $$metathesekeys{$unikey}=1;
1.599     albertel 6811:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6812: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6813:     }
1.599     albertel 6814:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6815: 	$metaentry{':'.$unikey}=
                   6816: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6817:     }
                   6818: }
                   6819: 
1.261     albertel 6820: sub metadata_generate_part0 {
                   6821:     my ($metadata,$metacache,$uri) = @_;
                   6822:     my %allnames;
1.737     albertel 6823:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6824: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6825: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6826: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6827: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6828: 	    $allnames{$name}=$part;
                   6829: 	  }
                   6830: 	}
                   6831:     }
                   6832:     foreach my $name (keys(%allnames)) {
                   6833:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6834:       my $key=":parameter_0_$name";
1.261     albertel 6835:       $$metacache{"$key.part"}='0';
                   6836:       $$metacache{"$key.name"}=$name;
1.428     albertel 6837:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6838: 					   $allnames{$name}.'_'.$name.
                   6839: 					   '.type'};
1.428     albertel 6840:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6841: 			     '.display'};
1.644     www      6842:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6843:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6844:       $$metacache{"$key.display"}=$olddis;
                   6845:     }
1.71      www      6846: }
                   6847: 
1.764     albertel 6848: # ------------------------------------------------------ Devalidate title cache
                   6849: 
                   6850: sub devalidate_title_cache {
                   6851:     my ($url)=@_;
                   6852:     if (!$env{'request.course.id'}) { return; }
                   6853:     my $symb=&symbread($url);
                   6854:     if (!$symb) { return; }
                   6855:     my $key=$env{'request.course.id'}."\0".$symb;
                   6856:     &devalidate_cache_new('title',$key);
                   6857: }
                   6858: 
1.301     www      6859: # ------------------------------------------------- Get the title of a resource
                   6860: 
                   6861: sub gettitle {
                   6862:     my $urlsymb=shift;
                   6863:     my $symb=&symbread($urlsymb);
1.534     albertel 6864:     if ($symb) {
1.620     albertel 6865: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6866: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6867: 	if (defined($cached)) { 
                   6868: 	    return $result;
                   6869: 	}
1.534     albertel 6870: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6871: 	my $title='';
1.907     albertel 6872: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   6873: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   6874: 	} else {
                   6875: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6876: 		    &GDBM_READER(),0640)) {
                   6877: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6878: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   6879: 		untie(%bighash);
                   6880: 	    }
1.534     albertel 6881: 	}
                   6882: 	$title=~s/\&colon\;/\:/gs;
                   6883: 	if ($title) {
1.599     albertel 6884: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6885: 	}
                   6886: 	$urlsymb=$url;
                   6887:     }
                   6888:     my $title=&metadata($urlsymb,'title');
                   6889:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6890:     return $title;
1.301     www      6891: }
1.613     albertel 6892: 
1.614     albertel 6893: sub get_slot {
                   6894:     my ($which,$cnum,$cdom)=@_;
                   6895:     if (!$cnum || !$cdom) {
1.790     albertel 6896: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6897: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6898: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6899:     }
1.703     albertel 6900:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6901:     my %slotinfo;
                   6902:     if (exists($remembered{$key})) {
                   6903: 	$slotinfo{$which} = $remembered{$key};
                   6904:     } else {
                   6905: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6906: 	&Apache::lonhomework::showhash(%slotinfo);
                   6907: 	my ($tmp)=keys(%slotinfo);
                   6908: 	if ($tmp=~/^error:/) { return (); }
                   6909: 	$remembered{$key} = $slotinfo{$which};
                   6910:     }
1.616     albertel 6911:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6912: 	return %{$slotinfo{$which}};
                   6913:     }
                   6914:     return $slotinfo{$which};
1.614     albertel 6915: }
1.31      www      6916: # ------------------------------------------------- Update symbolic store links
                   6917: 
                   6918: sub symblist {
                   6919:     my ($mapname,%newhash)=@_;
1.438     www      6920:     $mapname=&deversion(&declutter($mapname));
1.31      www      6921:     my %hash;
1.620     albertel 6922:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6923:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6924:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6925: 	    foreach my $url (keys %newhash) {
                   6926: 		next if ($url eq 'last_known'
                   6927: 			 && $env{'form.no_update_last_known'});
                   6928: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6929: 						    $newhash{$url}->[1],
                   6930: 						    $newhash{$url}->[0]);
1.191     harris41 6931:             }
1.31      www      6932:             if (untie(%hash)) {
                   6933: 		return 'ok';
                   6934:             }
                   6935:         }
                   6936:     }
                   6937:     return 'error';
1.212     www      6938: }
                   6939: 
                   6940: # --------------------------------------------------------------- Verify a symb
                   6941: 
                   6942: sub symbverify {
1.510     www      6943:     my ($symb,$thisurl)=@_;
                   6944:     my $thisfn=$thisurl;
1.439     www      6945:     $thisfn=&declutter($thisfn);
1.215     www      6946: # direct jump to resource in page or to a sequence - will construct own symbs
                   6947:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6948: # check URL part
1.409     www      6949:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6950: 
1.431     www      6951:     unless ($url eq $thisfn) { return 0; }
1.213     www      6952: 
1.216     www      6953:     $symb=&symbclean($symb);
1.510     www      6954:     $thisurl=&deversion($thisurl);
1.439     www      6955:     $thisfn=&deversion($thisfn);
1.213     www      6956: 
                   6957:     my %bighash;
                   6958:     my $okay=0;
1.431     www      6959: 
1.620     albertel 6960:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6961:                             &GDBM_READER(),0640)) {
1.510     www      6962:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6963:         unless ($ids) { 
1.510     www      6964:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6965:         }
                   6966:         if ($ids) {
                   6967: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6968: 	    foreach my $id (split(/\,/,$ids)) {
                   6969: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6970:                if (
                   6971:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6972:    eq $symb) { 
1.620     albertel 6973: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6974: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6975: 		       $okay=1; 
                   6976: 		   }
                   6977: 	       }
1.216     www      6978: 	   }
                   6979:         }
1.213     www      6980: 	untie(%bighash);
                   6981:     }
                   6982:     return $okay;
1.31      www      6983: }
                   6984: 
1.210     www      6985: # --------------------------------------------------------------- Clean-up symb
                   6986: 
                   6987: sub symbclean {
                   6988:     my $symb=shift;
1.568     albertel 6989:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6990: # remove version from map
                   6991:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6992: 
1.210     www      6993: # remove version from URL
                   6994:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6995: 
1.507     www      6996: # remove wrapper
                   6997: 
1.510     www      6998:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6999:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7000:     return $symb;
1.409     www      7001: }
                   7002: 
                   7003: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7004: 
                   7005: sub encode_symb {
                   7006:     my ($map,$resid,$url)=@_;
                   7007:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7008: }
1.409     www      7009: 
                   7010: sub decode_symb {
1.568     albertel 7011:     my $symb=shift;
                   7012:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7013:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7014:     return (&fixversion($map),$resid,&fixversion($url));
                   7015: }
                   7016: 
                   7017: sub fixversion {
                   7018:     my $fn=shift;
1.609     banghart 7019:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7020:     my %bighash;
                   7021:     my $uri=&clutter($fn);
1.620     albertel 7022:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7023: # is this cached?
1.599     albertel 7024:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7025:     if (defined($cached)) { return $result; }
                   7026: # unfortunately not cached, or expired
1.620     albertel 7027:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7028: 	    &GDBM_READER(),0640)) {
                   7029:  	if ($bighash{'version_'.$uri}) {
                   7030:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7031:  	    unless (($version eq 'mostrecent') || 
                   7032: 		    ($version==&getversion($uri))) {
1.440     www      7033:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7034:  	    }
                   7035:  	}
                   7036:  	untie %bighash;
1.413     www      7037:     }
1.599     albertel 7038:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7039: }
                   7040: 
                   7041: sub deversion {
                   7042:     my $url=shift;
                   7043:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7044:     return $url;
1.210     www      7045: }
                   7046: 
1.31      www      7047: # ------------------------------------------------------ Return symb list entry
                   7048: 
                   7049: sub symbread {
1.249     www      7050:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7051:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7052:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7053: # no filename provided? try from environment
1.44      www      7054:     unless ($thisfn) {
1.620     albertel 7055:         if ($env{'request.symb'}) {
                   7056: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7057: 	}
1.620     albertel 7058: 	$thisfn=$env{'request.filename'};
1.44      www      7059:     }
1.569     albertel 7060:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7061: # is that filename actually a symb? Verify, clean, and return
                   7062:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7063: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7064: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7065: 	}
1.242     www      7066:     }
1.44      www      7067:     $thisfn=declutter($thisfn);
1.31      www      7068:     my %hash;
1.37      www      7069:     my %bighash;
                   7070:     my $syval='';
1.620     albertel 7071:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7072:         my $targetfn = $thisfn;
1.609     banghart 7073:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7074:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7075:         }
1.687     albertel 7076: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7077: 	    $targetfn=$1;
                   7078: 	}
1.620     albertel 7079:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7080:                       &GDBM_READER(),0640)) {
1.481     raeburn  7081: 	    $syval=$hash{$targetfn};
1.37      www      7082:             untie(%hash);
                   7083:         }
                   7084: # ---------------------------------------------------------- There was an entry
                   7085:         if ($syval) {
1.601     albertel 7086: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7087: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7088: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7089: 		    #return $env{$cache_str}='';
1.601     albertel 7090: 		#}    
                   7091: 		#$syval.=$1;
                   7092: 	    #}
1.37      www      7093:         } else {
                   7094: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7095:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7096:                             &GDBM_READER(),0640)) {
1.37      www      7097: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7098:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7099:               unless ($ids) { 
                   7100:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7101:               }
                   7102:               unless ($ids) {
                   7103: # alias?
                   7104: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7105:               }
1.37      www      7106:               if ($ids) {
                   7107: # ------------------------------------------------------------------- Has ID(s)
                   7108:                  my @possibilities=split(/\,/,$ids);
1.39      www      7109:                  if ($#possibilities==0) {
                   7110: # ----------------------------------------------- There is only one possibility
1.37      www      7111: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7112: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7113: 						    $resid,$thisfn);
1.249     www      7114:                  } elsif (!$donotrecurse) {
1.39      www      7115: # ------------------------------------------ There is more than one possibility
                   7116:                      my $realpossible=0;
1.800     albertel 7117:                      foreach my $id (@possibilities) {
                   7118: 			 my $file=$bighash{'src_'.$id};
1.39      www      7119:                          if (&allowed('bre',$file)) {
1.800     albertel 7120:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7121:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7122: 				$realpossible++;
1.626     albertel 7123:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7124: 						    $resid,$thisfn);
1.39      www      7125:                             }
                   7126: 			 }
1.191     harris41 7127:                      }
1.39      www      7128: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7129:                  } else {
                   7130:                      $syval='';
1.37      www      7131:                  }
                   7132: 	      }
                   7133:               untie(%bighash)
1.481     raeburn  7134:            }
1.31      www      7135:         }
1.62      www      7136:         if ($syval) {
1.620     albertel 7137: 	    return $env{$cache_str}=$syval;
1.62      www      7138:         }
1.31      www      7139:     }
1.44      www      7140:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7141:     return $env{$cache_str}='';
1.31      www      7142: }
                   7143: 
                   7144: # ---------------------------------------------------------- Return random seed
                   7145: 
1.32      www      7146: sub numval {
                   7147:     my $txt=shift;
                   7148:     $txt=~tr/A-J/0-9/;
                   7149:     $txt=~tr/a-j/0-9/;
                   7150:     $txt=~tr/K-T/0-9/;
                   7151:     $txt=~tr/k-t/0-9/;
                   7152:     $txt=~tr/U-Z/0-5/;
                   7153:     $txt=~tr/u-z/0-5/;
                   7154:     $txt=~s/\D//g;
1.564     albertel 7155:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7156:     return int($txt);
1.368     albertel 7157: }
                   7158: 
1.484     albertel 7159: sub numval2 {
                   7160:     my $txt=shift;
                   7161:     $txt=~tr/A-J/0-9/;
                   7162:     $txt=~tr/a-j/0-9/;
                   7163:     $txt=~tr/K-T/0-9/;
                   7164:     $txt=~tr/k-t/0-9/;
                   7165:     $txt=~tr/U-Z/0-5/;
                   7166:     $txt=~tr/u-z/0-5/;
                   7167:     $txt=~s/\D//g;
                   7168:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7169:     my $total;
                   7170:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7171:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7172:     return int($total);
                   7173: }
                   7174: 
1.575     albertel 7175: sub numval3 {
                   7176:     use integer;
                   7177:     my $txt=shift;
                   7178:     $txt=~tr/A-J/0-9/;
                   7179:     $txt=~tr/a-j/0-9/;
                   7180:     $txt=~tr/K-T/0-9/;
                   7181:     $txt=~tr/k-t/0-9/;
                   7182:     $txt=~tr/U-Z/0-5/;
                   7183:     $txt=~tr/u-z/0-5/;
                   7184:     $txt=~s/\D//g;
                   7185:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7186:     my $total;
                   7187:     foreach my $val (@txts) { $total+=$val; }
                   7188:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7189:     return $total;
                   7190: }
                   7191: 
1.675     albertel 7192: sub digest {
                   7193:     my ($data)=@_;
                   7194:     my $digest=&Digest::MD5::md5($data);
                   7195:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7196:     my ($e,$f);
                   7197:     {
                   7198:         use integer;
                   7199:         $e=($a+$b);
                   7200:         $f=($c+$d);
                   7201:         if ($_64bit) {
                   7202:             $e=(($e<<32)>>32);
                   7203:             $f=(($f<<32)>>32);
                   7204:         }
                   7205:     }
                   7206:     if (wantarray) {
                   7207: 	return ($e,$f);
                   7208:     } else {
                   7209: 	my $g;
                   7210: 	{
                   7211: 	    use integer;
                   7212: 	    $g=($e+$f);
                   7213: 	    if ($_64bit) {
                   7214: 		$g=(($g<<32)>>32);
                   7215: 	    }
                   7216: 	}
                   7217: 	return $g;
                   7218:     }
                   7219: }
                   7220: 
1.368     albertel 7221: sub latest_rnd_algorithm_id {
1.675     albertel 7222:     return '64bit5';
1.366     albertel 7223: }
1.32      www      7224: 
1.503     albertel 7225: sub get_rand_alg {
                   7226:     my ($courseid)=@_;
1.790     albertel 7227:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7228:     if ($courseid) {
1.620     albertel 7229: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7230:     }
                   7231:     return &latest_rnd_algorithm_id();
                   7232: }
                   7233: 
1.562     albertel 7234: sub validCODE {
                   7235:     my ($CODE)=@_;
                   7236:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7237:     return 0;
                   7238: }
                   7239: 
1.491     albertel 7240: sub getCODE {
1.620     albertel 7241:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7242:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7243: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7244: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7245: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7246:     }
                   7247:     return undef;
                   7248: }
                   7249: 
1.31      www      7250: sub rndseed {
1.155     albertel 7251:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7252:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7253:     if (!defined($symb)) {
1.366     albertel 7254: 	unless ($symb=$wsymb) { return time; }
                   7255:     }
                   7256:     if (!$courseid) { $courseid=$wcourseid; }
                   7257:     if (!$domain) { $domain=$wdomain; }
                   7258:     if (!$username) { $username=$wusername }
1.503     albertel 7259:     my $which=&get_rand_alg();
1.803     albertel 7260: 
1.491     albertel 7261:     if (defined(&getCODE())) {
1.675     albertel 7262: 	if ($which eq '64bit5') {
                   7263: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7264: 	} elsif ($which eq '64bit4') {
1.575     albertel 7265: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7266: 	} else {
                   7267: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7268: 	}
1.675     albertel 7269:     } elsif ($which eq '64bit5') {
                   7270: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7271:     } elsif ($which eq '64bit4') {
                   7272: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7273:     } elsif ($which eq '64bit3') {
                   7274: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7275:     } elsif ($which eq '64bit2') {
                   7276: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7277:     } elsif ($which eq '64bit') {
                   7278: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7279:     }
                   7280:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7281: }
                   7282: 
                   7283: sub rndseed_32bit {
                   7284:     my ($symb,$courseid,$domain,$username)=@_;
                   7285:     {
                   7286: 	use integer;
                   7287: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7288: 	my $symbseed=numval($symb) << 22;
                   7289: 	my $namechck=unpack("%32C*",$username) << 17;
                   7290: 	my $nameseed=numval($username) << 12;
                   7291: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7292: 	my $courseseed=unpack("%32C*",$courseid);
                   7293: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7294: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7295: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7296: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7297: 	return $num;
                   7298:     }
                   7299: }
                   7300: 
                   7301: sub rndseed_64bit {
                   7302:     my ($symb,$courseid,$domain,$username)=@_;
                   7303:     {
                   7304: 	use integer;
                   7305: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7306: 	my $symbseed=numval($symb) << 10;
                   7307: 	my $namechck=unpack("%32S*",$username);
                   7308: 	
                   7309: 	my $nameseed=numval($username) << 21;
                   7310: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7311: 	my $courseseed=unpack("%32S*",$courseid);
                   7312: 	
                   7313: 	my $num1=$symbchck+$symbseed+$namechck;
                   7314: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7315: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7316: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7317: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7318: 	return "$num1,$num2";
1.155     albertel 7319:     }
1.366     albertel 7320: }
                   7321: 
1.443     albertel 7322: sub rndseed_64bit2 {
                   7323:     my ($symb,$courseid,$domain,$username)=@_;
                   7324:     {
                   7325: 	use integer;
                   7326: 	# strings need to be an even # of cahracters long, it it is odd the
                   7327:         # last characters gets thrown away
                   7328: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7329: 	my $symbseed=numval($symb) << 10;
                   7330: 	my $namechck=unpack("%32S*",$username.' ');
                   7331: 	
                   7332: 	my $nameseed=numval($username) << 21;
1.501     albertel 7333: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7334: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7335: 	
                   7336: 	my $num1=$symbchck+$symbseed+$namechck;
                   7337: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7338: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7339: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7340: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7341: 	return "$num1,$num2";
                   7342:     }
                   7343: }
                   7344: 
                   7345: sub rndseed_64bit3 {
                   7346:     my ($symb,$courseid,$domain,$username)=@_;
                   7347:     {
                   7348: 	use integer;
                   7349: 	# strings need to be an even # of cahracters long, it it is odd the
                   7350:         # last characters gets thrown away
                   7351: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7352: 	my $symbseed=numval2($symb) << 10;
                   7353: 	my $namechck=unpack("%32S*",$username.' ');
                   7354: 	
                   7355: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7356: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7357: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7358: 	
                   7359: 	my $num1=$symbchck+$symbseed+$namechck;
                   7360: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7361: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7362: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7363: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7364: 	
1.503     albertel 7365: 	return "$num1:$num2";
1.443     albertel 7366:     }
                   7367: }
                   7368: 
1.575     albertel 7369: sub rndseed_64bit4 {
                   7370:     my ($symb,$courseid,$domain,$username)=@_;
                   7371:     {
                   7372: 	use integer;
                   7373: 	# strings need to be an even # of cahracters long, it it is odd the
                   7374:         # last characters gets thrown away
                   7375: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7376: 	my $symbseed=numval3($symb) << 10;
                   7377: 	my $namechck=unpack("%32S*",$username.' ');
                   7378: 	
                   7379: 	my $nameseed=numval3($username) << 21;
                   7380: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7381: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7382: 	
                   7383: 	my $num1=$symbchck+$symbseed+$namechck;
                   7384: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7385: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7386: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7387: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7388: 	
                   7389: 	return "$num1:$num2";
                   7390:     }
                   7391: }
                   7392: 
1.675     albertel 7393: sub rndseed_64bit5 {
                   7394:     my ($symb,$courseid,$domain,$username)=@_;
                   7395:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7396:     return "$num1:$num2";
                   7397: }
                   7398: 
1.366     albertel 7399: sub rndseed_CODE_64bit {
                   7400:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7401:     {
1.366     albertel 7402: 	use integer;
1.443     albertel 7403: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7404: 	my $symbseed=numval2($symb);
1.491     albertel 7405: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7406: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7407: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7408: 	my $num1=$symbseed+$CODEchck;
                   7409: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7410: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7411: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7412: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7413: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7414: 	return "$num1:$num2";
1.366     albertel 7415:     }
                   7416: }
                   7417: 
1.575     albertel 7418: sub rndseed_CODE_64bit4 {
                   7419:     my ($symb,$courseid,$domain,$username)=@_;
                   7420:     {
                   7421: 	use integer;
                   7422: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7423: 	my $symbseed=numval3($symb);
                   7424: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7425: 	my $CODEseed=numval3(&getCODE());
                   7426: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7427: 	my $num1=$symbseed+$CODEchck;
                   7428: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7429: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7430: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7431: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7432: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7433: 	return "$num1:$num2";
                   7434:     }
                   7435: }
                   7436: 
1.675     albertel 7437: sub rndseed_CODE_64bit5 {
                   7438:     my ($symb,$courseid,$domain,$username)=@_;
                   7439:     my $code = &getCODE();
                   7440:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7441:     return "$num1:$num2";
                   7442: }
                   7443: 
1.366     albertel 7444: sub setup_random_from_rndseed {
                   7445:     my ($rndseed)=@_;
1.503     albertel 7446:     if ($rndseed =~/([,:])/) {
                   7447: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7448: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7449:     } else {
                   7450: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7451:     }
1.36      albertel 7452: }
                   7453: 
1.474     albertel 7454: sub latest_receipt_algorithm_id {
1.835     albertel 7455:     return 'receipt3';
1.474     albertel 7456: }
                   7457: 
1.480     www      7458: sub recunique {
                   7459:     my $fucourseid=shift;
                   7460:     my $unique;
1.835     albertel 7461:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7462: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7463: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7464:     } else {
                   7465: 	$unique=$perlvar{'lonReceipt'};
                   7466:     }
                   7467:     return unpack("%32C*",$unique);
                   7468: }
                   7469: 
                   7470: sub recprefix {
                   7471:     my $fucourseid=shift;
                   7472:     my $prefix;
1.835     albertel 7473:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7474: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7475: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7476:     } else {
                   7477: 	$prefix=$perlvar{'lonHostID'};
                   7478:     }
                   7479:     return unpack("%32C*",$prefix);
                   7480: }
                   7481: 
1.76      www      7482: sub ireceipt {
1.474     albertel 7483:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7484: 
                   7485:     my $return =&recprefix($fucourseid).'-';
                   7486: 
                   7487:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7488: 	$env{'request.state'} eq 'construct') {
                   7489: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7490: 	return $return;
                   7491:     }
                   7492: 
1.76      www      7493:     my $cuname=unpack("%32C*",$funame);
                   7494:     my $cudom=unpack("%32C*",$fudom);
                   7495:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7496:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7497:     my $cunique=&recunique($fucourseid);
1.474     albertel 7498:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7499:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7500: 
1.790     albertel 7501: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7502: 			       
                   7503: 	$return.= ($cunique%$cuname+
                   7504: 		   $cunique%$cudom+
                   7505: 		   $cusymb%$cuname+
                   7506: 		   $cusymb%$cudom+
                   7507: 		   $cucourseid%$cuname+
                   7508: 		   $cucourseid%$cudom+
                   7509: 		   $cpart%$cuname+
                   7510: 		   $cpart%$cudom);
                   7511:     } else {
                   7512: 	$return.= ($cunique%$cuname+
                   7513: 		   $cunique%$cudom+
                   7514: 		   $cusymb%$cuname+
                   7515: 		   $cusymb%$cudom+
                   7516: 		   $cucourseid%$cuname+
                   7517: 		   $cucourseid%$cudom);
                   7518:     }
                   7519:     return $return;
1.76      www      7520: }
                   7521: 
                   7522: sub receipt {
1.474     albertel 7523:     my ($part)=@_;
1.790     albertel 7524:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7525:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7526: }
1.260     ng       7527: 
1.790     albertel 7528: sub whichuser {
                   7529:     my ($passedsymb)=@_;
                   7530:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7531:     if (defined($env{'form.grade_symb'})) {
                   7532: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7533: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7534: 	if (!$allowed &&
                   7535: 	    exists($env{'request.course.sec'}) &&
                   7536: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7537: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7538: 			      '/'.$env{'request.course.sec'});
                   7539: 	}
                   7540: 	if ($allowed) {
                   7541: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7542: 	    $courseid=$tmp_courseid;
                   7543: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7544: 	    ($name)=&get_env_multiple('form.grade_username');
                   7545: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7546: 	}
                   7547:     }
                   7548:     if (!$passedsymb) {
                   7549: 	$symb=&symbread();
                   7550:     } else {
                   7551: 	$symb=$passedsymb;
                   7552:     }
                   7553:     $courseid=$env{'request.course.id'};
                   7554:     $domain=$env{'user.domain'};
                   7555:     $name=$env{'user.name'};
                   7556:     if ($name eq 'public' && $domain eq 'public') {
                   7557: 	if (!defined($env{'form.username'})) {
                   7558: 	    $env{'form.username'}.=time.rand(10000000);
                   7559: 	}
                   7560: 	$name.=$env{'form.username'};
                   7561:     }
                   7562:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7563: 
                   7564: }
                   7565: 
1.36      albertel 7566: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7567: # returns either the contents of the file or 
                   7568: # -1 if the file doesn't exist
1.481     raeburn  7569: #
                   7570: # if the target is a file that was uploaded via DOCS, 
                   7571: # a check will be made to see if a current copy exists on the local server,
                   7572: # if it does this will be served, otherwise a copy will be retrieved from
                   7573: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7574: # the local server.   
1.472     albertel 7575: 
1.36      albertel 7576: sub getfile {
1.538     albertel 7577:     my ($file) = @_;
1.609     banghart 7578:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7579:     &repcopy($file);
                   7580:     return &readfile($file);
                   7581: }
                   7582: 
                   7583: sub repcopy_userfile {
                   7584:     my ($file)=@_;
1.609     banghart 7585:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7586:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7587:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7588: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7589:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7590:     if (-e "$file") {
1.828     www      7591: # we already have a local copy, check it out
1.538     albertel 7592: 	my @fileinfo = stat($file);
1.828     www      7593: 	my $rtncode;
                   7594: 	my $info;
1.538     albertel 7595: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7596: 	if ($lwpresp ne 'ok') {
1.828     www      7597: # there is no such file anymore, even though we had a local copy
1.482     albertel 7598: 	    if ($rtncode eq '404') {
1.538     albertel 7599: 		unlink($file);
1.482     albertel 7600: 	    }
                   7601: 	    return -1;
                   7602: 	}
                   7603: 	if ($info < $fileinfo[9]) {
1.828     www      7604: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7605: 	    return 'ok';
1.828     www      7606: 	} else {
                   7607: # the file is outdated, get rid of it
                   7608: 	    unlink($file);
1.482     albertel 7609: 	}
1.828     www      7610:     }
                   7611: # one way or the other, at this point, we don't have the file
                   7612: # construct the correct path for the file
                   7613:     my @parts = ($cdom,$cnum); 
                   7614:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7615: 	push @parts, split(/\//,$1);
                   7616:     }
                   7617:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7618:     foreach my $part (@parts) {
                   7619: 	$path .= '/'.$part;
                   7620: 	if (!-e $path) {
                   7621: 	    mkdir($path,0770);
1.482     albertel 7622: 	}
                   7623:     }
1.828     www      7624: # now the path exists for sure
                   7625: # get a user agent
                   7626:     my $ua=new LWP::UserAgent;
                   7627:     my $transferfile=$file.'.in.transfer';
                   7628: # FIXME: this should flock
                   7629:     if (-e $transferfile) { return 'ok'; }
                   7630:     my $request;
                   7631:     $uri=~s/^\///;
1.838     albertel 7632:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7633:     my $response=$ua->request($request,$transferfile);
                   7634: # did it work?
                   7635:     if ($response->is_error()) {
                   7636: 	unlink($transferfile);
                   7637: 	&logthis("Userfile repcopy failed for $uri");
                   7638: 	return -1;
                   7639:     }
                   7640: # worked, rename the transfer file
                   7641:     rename($transferfile,$file);
1.607     raeburn  7642:     return 'ok';
1.481     raeburn  7643: }
                   7644: 
1.517     albertel 7645: sub tokenwrapper {
                   7646:     my $uri=shift;
1.552     albertel 7647:     $uri=~s|^http\://([^/]+)||;
                   7648:     $uri=~s|^/||;
1.620     albertel 7649:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7650:     my $token=$1;
1.552     albertel 7651:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7652:     if ($udom && $uname && $file) {
                   7653: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7654:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7655:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7656:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7657:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7658:     } else {
                   7659:         return '/adm/notfound.html';
                   7660:     }
                   7661: }
                   7662: 
1.828     www      7663: # call with reqtype HEAD: get last modification time
                   7664: # call with reqtype GET: get the file contents
                   7665: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7666: #
1.481     raeburn  7667: sub getuploaded {
                   7668:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7669:     $uri=~s/^\///;
1.838     albertel 7670:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7671:     my $ua=new LWP::UserAgent;
                   7672:     my $request=new HTTP::Request($reqtype,$uri);
                   7673:     my $response=$ua->request($request);
                   7674:     $$rtncode = $response->code;
1.482     albertel 7675:     if (! $response->is_success()) {
                   7676: 	return 'failed';
                   7677:     }      
                   7678:     if ($reqtype eq 'HEAD') {
1.486     www      7679: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7680:     } elsif ($reqtype eq 'GET') {
                   7681: 	$$info = $response->content;
1.472     albertel 7682:     }
1.482     albertel 7683:     return 'ok';
1.36      albertel 7684: }
                   7685: 
1.481     raeburn  7686: sub readfile {
                   7687:     my $file = shift;
                   7688:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7689:     my $fh;
                   7690:     open($fh,"<$file");
                   7691:     my $a='';
1.800     albertel 7692:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7693:     return $a;
                   7694: }
                   7695: 
1.36      albertel 7696: sub filelocation {
1.590     banghart 7697:     my ($dir,$file) = @_;
                   7698:     my $location;
                   7699:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7700: 
                   7701:     if ($file =~ m-^/adm/-) {
                   7702: 	$file=~s-^/adm/wrapper/-/-;
                   7703: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7704:     }
1.882     albertel 7705: 
1.590     banghart 7706:     if ($file=~m:^/~:) { # is a contruction space reference
                   7707:         $location = $file;
                   7708:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7709:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7710: 	# is a correct contruction space reference
                   7711:         $location = $file;
1.609     banghart 7712:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7713:         my ($udom,$uname,$filename)=
1.811     albertel 7714:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7715:         my $home=&homeserver($uname,$udom);
                   7716:         my $is_me=0;
                   7717:         my @ids=&current_machine_ids();
                   7718:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7719:         if ($is_me) {
1.740     www      7720:   	    $location=&propath($udom,$uname).
1.590     banghart 7721:   	      '/userfiles/'.$filename;
                   7722:         } else {
                   7723:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7724:   	      $udom.'/'.$uname.'/'.$filename;
                   7725:         }
1.882     albertel 7726:     } elsif ($file =~ m-^/adm/-) {
                   7727: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7728:     } else {
                   7729:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7730:         $file=~s:^/res/:/:;
                   7731:         if ( !( $file =~ m:^/:) ) {
                   7732:             $location = $dir. '/'.$file;
                   7733:         } else {
                   7734:             $location = '/home/httpd/html/res'.$file;
                   7735:         }
1.59      albertel 7736:     }
1.590     banghart 7737:     $location=~s://+:/:g; # remove duplicate /
                   7738:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7739:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7740:     return $location;
1.46      www      7741: }
1.36      albertel 7742: 
1.46      www      7743: sub hreflocation {
                   7744:     my ($dir,$file)=@_;
1.460     albertel 7745:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7746: 	$file=filelocation($dir,$file);
1.700     albertel 7747:     } elsif ($file=~m-^/adm/-) {
                   7748: 	$file=~s-^/adm/wrapper/-/-;
                   7749: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7750:     }
                   7751:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7752: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7753:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7754: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7755:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7756: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7757: 	    -/uploaded/$1/$2/-x;
1.46      www      7758:     }
1.910.2.1  albertel 7759:     if ($file=~ m{^/userfiles/}) {
                   7760: 	$file =~ s{^/userfiles/}{/uploaded/};
                   7761:     }
1.462     albertel 7762:     return $file;
1.465     albertel 7763: }
                   7764: 
                   7765: sub current_machine_domains {
1.853     albertel 7766:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7767: }
                   7768: 
                   7769: sub machine_domains {
                   7770:     my ($hostname) = @_;
1.465     albertel 7771:     my @domains;
1.838     albertel 7772:     my %hostname = &all_hostnames();
1.465     albertel 7773:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7774: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7775: 	if ($hostname eq $name) {
1.844     albertel 7776: 	    push(@domains,&host_domain($id));
1.465     albertel 7777: 	}
                   7778:     }
                   7779:     return @domains;
                   7780: }
                   7781: 
                   7782: sub current_machine_ids {
1.853     albertel 7783:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7784: }
                   7785: 
                   7786: sub machine_ids {
                   7787:     my ($hostname) = @_;
                   7788:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7789:     my @ids;
1.888     albertel 7790:     my %name_to_host = &all_names();
1.889     albertel 7791:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7792: 	return @{ $name_to_host{$hostname} };
                   7793:     }
                   7794:     return;
1.31      www      7795: }
                   7796: 
1.824     raeburn  7797: sub additional_machine_domains {
                   7798:     my @domains;
                   7799:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7800:     while( my $line = <$fh>) {
                   7801:         $line =~ s/\s//g;
                   7802:         push(@domains,$line);
                   7803:     }
                   7804:     return @domains;
                   7805: }
                   7806: 
                   7807: sub default_login_domain {
                   7808:     my $domain = $perlvar{'lonDefDomain'};
                   7809:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7810:     foreach my $posdom (&current_machine_domains(),
                   7811:                         &additional_machine_domains()) {
                   7812:         if (lc($posdom) eq lc($testdomain)) {
                   7813:             $domain=$posdom;
                   7814:             last;
                   7815:         }
                   7816:     }
                   7817:     return $domain;
                   7818: }
                   7819: 
1.31      www      7820: # ------------------------------------------------------------- Declutters URLs
                   7821: 
                   7822: sub declutter {
                   7823:     my $thisfn=shift;
1.569     albertel 7824:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7825:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7826:     $thisfn=~s/^\///;
1.697     albertel 7827:     $thisfn=~s|^adm/wrapper/||;
                   7828:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7829:     $thisfn=~s/^res\///;
1.235     www      7830:     $thisfn=~s/\?.+$//;
1.268     www      7831:     return $thisfn;
                   7832: }
                   7833: 
                   7834: # ------------------------------------------------------------- Clutter up URLs
                   7835: 
                   7836: sub clutter {
                   7837:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7838:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7839: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7840:        $thisfn='/res'.$thisfn; 
                   7841:     }
1.694     albertel 7842:     if ($thisfn !~m|/adm|) {
1.695     albertel 7843: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7844: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7845: 	} else {
                   7846: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7847: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7848: 	    if ($embstyle eq 'ssi'
                   7849: 		|| ($embstyle eq 'hdn')
                   7850: 		|| ($embstyle eq 'rat')
                   7851: 		|| ($embstyle eq 'prv')
                   7852: 		|| ($embstyle eq 'ign')) {
                   7853: 		#do nothing with these
                   7854: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7855: 		|| ($embstyle eq 'emb')
                   7856: 		|| ($embstyle eq 'wrp')) {
                   7857: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7858: 	    } elsif ($embstyle eq 'unk'
                   7859: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7860: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7861: 	    } else {
1.718     www      7862: #		&logthis("Got a blank emb style");
1.695     albertel 7863: 	    }
1.694     albertel 7864: 	}
                   7865:     }
1.31      www      7866:     return $thisfn;
1.12      www      7867: }
                   7868: 
1.787     albertel 7869: sub clutter_with_no_wrapper {
                   7870:     my $uri = &clutter(shift);
                   7871:     if ($uri =~ m-^/adm/-) {
                   7872: 	$uri =~ s-^/adm/wrapper/-/-;
                   7873: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7874:     }
                   7875:     return $uri;
                   7876: }
                   7877: 
1.557     albertel 7878: sub freeze_escape {
                   7879:     my ($value)=@_;
                   7880:     if (ref($value)) {
                   7881: 	$value=&nfreeze($value);
                   7882: 	return '__FROZEN__'.&escape($value);
                   7883:     }
                   7884:     return &escape($value);
                   7885: }
                   7886: 
1.11      www      7887: 
1.557     albertel 7888: sub thaw_unescape {
                   7889:     my ($value)=@_;
                   7890:     if ($value =~ /^__FROZEN__/) {
                   7891: 	substr($value,0,10,undef);
                   7892: 	$value=&unescape($value);
                   7893: 	return &thaw($value);
                   7894:     }
                   7895:     return &unescape($value);
                   7896: }
                   7897: 
1.436     albertel 7898: sub correct_line_ends {
                   7899:     my ($result)=@_;
                   7900:     $$result =~s/\r\n/\n/mg;
                   7901:     $$result =~s/\r/\n/mg;
1.415     albertel 7902: }
1.1       albertel 7903: # ================================================================ Main Program
                   7904: 
1.184     www      7905: sub goodbye {
1.204     albertel 7906:    &logthis("Starting Shut down");
1.443     albertel 7907: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7908:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7909: #converted
1.599     albertel 7910: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7911:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7912: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7913: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7914: #1.1 only
1.870     albertel 7915: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7916: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7917: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7918: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7919:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7920:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7921:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7922:    &flushcourselogs();
                   7923:    &logthis("Shutting down");
                   7924: }
                   7925: 
1.852     albertel 7926: sub get_dns {
1.869     albertel 7927:     my ($url,$func,$ignore_cache) = @_;
                   7928:     if (!$ignore_cache) {
                   7929: 	my ($content,$cached)=
                   7930: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7931: 	if ($cached) {
                   7932: 	    &$func($content);
                   7933: 	    return;
                   7934: 	}
                   7935:     }
                   7936: 
                   7937:     my %alldns;
1.852     albertel 7938:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7939:     foreach my $dns (<$config>) {
                   7940: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7941: 	$alldns{$1} = 1;
                   7942:     }
                   7943:     while (%alldns) {
                   7944: 	my ($dns) = keys(%alldns);
                   7945: 	delete($alldns{$dns});
1.852     albertel 7946: 	my $ua=new LWP::UserAgent;
                   7947: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7948: 	my $response=$ua->request($request);
                   7949: 	next if ($response->is_error());
                   7950: 	my @content = split("\n",$response->content);
1.869     albertel 7951: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7952: 	&$func(\@content);
1.869     albertel 7953: 	return;
1.852     albertel 7954:     }
                   7955:     close($config);
1.871     albertel 7956:     my $which = (split('/',$url))[3];
                   7957:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7958:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7959:     my @content = <$config>;
                   7960:     &$func(\@content);
                   7961:     return;
1.852     albertel 7962: }
1.327     albertel 7963: # ------------------------------------------------------------ Read domain file
                   7964: {
1.852     albertel 7965:     my $loaded;
1.846     albertel 7966:     my %domain;
                   7967: 
1.852     albertel 7968:     sub parse_domain_tab {
                   7969: 	my ($lines) = @_;
                   7970: 	foreach my $line (@$lines) {
                   7971: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7972: 
1.846     albertel 7973: 	    chomp($line);
1.852     albertel 7974: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7975: 	    my %this_domain;
                   7976: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7977: 			       'lang_def', 'city', 'longi', 'lati',
                   7978: 			       'primary') {
                   7979: 		$this_domain{$field} = shift(@elements);
                   7980: 	    }
                   7981: 	    $domain{$name} = \%this_domain;
1.852     albertel 7982: 	}
                   7983:     }
1.864     albertel 7984: 
                   7985:     sub reset_domain_info {
                   7986: 	undef($loaded);
                   7987: 	undef(%domain);
                   7988:     }
                   7989: 
1.852     albertel 7990:     sub load_domain_tab {
1.869     albertel 7991: 	my ($ignore_cache) = @_;
                   7992: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7993: 	my $fh;
                   7994: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7995: 	    my @lines = <$fh>;
                   7996: 	    &parse_domain_tab(\@lines);
1.448     albertel 7997: 	}
1.852     albertel 7998: 	close($fh);
                   7999: 	$loaded = 1;
1.327     albertel 8000:     }
1.846     albertel 8001: 
                   8002:     sub domain {
1.852     albertel 8003: 	&load_domain_tab() if (!$loaded);
                   8004: 
1.846     albertel 8005: 	my ($name,$what) = @_;
                   8006: 	return if ( !exists($domain{$name}) );
                   8007: 
                   8008: 	if (!$what) {
                   8009: 	    return $domain{$name}{'description'};
                   8010: 	}
                   8011: 	return $domain{$name}{$what};
                   8012:     }
1.327     albertel 8013: }
                   8014: 
                   8015: 
1.1       albertel 8016: # ------------------------------------------------------------- Read hosts file
                   8017: {
1.838     albertel 8018:     my %hostname;
1.844     albertel 8019:     my %hostdom;
1.845     albertel 8020:     my %libserv;
1.852     albertel 8021:     my $loaded;
1.888     albertel 8022:     my %name_to_host;
1.852     albertel 8023: 
                   8024:     sub parse_hosts_tab {
                   8025: 	my ($file) = @_;
                   8026: 	foreach my $configline (@$file) {
                   8027: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8028: 	    next if ($configline =~ /^\^/);
                   8029: 	    chomp($configline);
                   8030: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8031: 	    $name=~s/\s//g;
                   8032: 	    if ($id && $domain && $role && $name) {
                   8033: 		$hostname{$id}=$name;
1.888     albertel 8034: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8035: 		$hostdom{$id}=$domain;
                   8036: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8037: 	    }
                   8038: 	}
                   8039:     }
1.864     albertel 8040:     
                   8041:     sub reset_hosts_info {
1.897     albertel 8042: 	&purge_remembered();
1.864     albertel 8043: 	&reset_domain_info();
                   8044: 	&reset_hosts_ip_info();
1.892     albertel 8045: 	undef(%name_to_host);
1.864     albertel 8046: 	undef(%hostname);
                   8047: 	undef(%hostdom);
                   8048: 	undef(%libserv);
                   8049: 	undef($loaded);
                   8050:     }
1.1       albertel 8051: 
1.852     albertel 8052:     sub load_hosts_tab {
1.869     albertel 8053: 	my ($ignore_cache) = @_;
                   8054: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8055: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8056: 	my @config = <$config>;
                   8057: 	&parse_hosts_tab(\@config);
                   8058: 	close($config);
                   8059: 	$loaded=1;
1.1       albertel 8060:     }
1.852     albertel 8061: 
1.838     albertel 8062:     sub hostname {
1.852     albertel 8063: 	&load_hosts_tab() if (!$loaded);
                   8064: 
1.838     albertel 8065: 	my ($lonid) = @_;
                   8066: 	return $hostname{$lonid};
                   8067:     }
1.845     albertel 8068: 
1.838     albertel 8069:     sub all_hostnames {
1.852     albertel 8070: 	&load_hosts_tab() if (!$loaded);
                   8071: 
1.838     albertel 8072: 	return %hostname;
                   8073:     }
1.845     albertel 8074: 
1.888     albertel 8075:     sub all_names {
                   8076: 	&load_hosts_tab() if (!$loaded);
                   8077: 
                   8078: 	return %name_to_host;
                   8079:     }
                   8080: 
1.845     albertel 8081:     sub is_library {
1.852     albertel 8082: 	&load_hosts_tab() if (!$loaded);
                   8083: 
1.845     albertel 8084: 	return exists($libserv{$_[0]});
                   8085:     }
                   8086: 
                   8087:     sub all_library {
1.852     albertel 8088: 	&load_hosts_tab() if (!$loaded);
                   8089: 
1.845     albertel 8090: 	return %libserv;
                   8091:     }
                   8092: 
1.841     albertel 8093:     sub get_servers {
1.852     albertel 8094: 	&load_hosts_tab() if (!$loaded);
                   8095: 
1.841     albertel 8096: 	my ($domain,$type) = @_;
                   8097: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8098: 	                                          : %hostname;
                   8099: 	my %result;
1.842     albertel 8100: 	if (ref($domain) eq 'ARRAY') {
                   8101: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8102: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8103: 		    $result{$host} = $hostname;
                   8104: 		}
                   8105: 	    }
                   8106: 	} else {
                   8107: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8108: 		if ($hostdom{$host} eq $domain) {
                   8109: 		    $result{$host} = $hostname;
                   8110: 		}
1.841     albertel 8111: 	    }
                   8112: 	}
                   8113: 	return %result;
                   8114:     }
1.845     albertel 8115: 
1.844     albertel 8116:     sub host_domain {
1.852     albertel 8117: 	&load_hosts_tab() if (!$loaded);
                   8118: 
1.844     albertel 8119: 	my ($lonid) = @_;
                   8120: 	return $hostdom{$lonid};
                   8121:     }
                   8122: 
1.841     albertel 8123:     sub all_domains {
1.852     albertel 8124: 	&load_hosts_tab() if (!$loaded);
                   8125: 
1.841     albertel 8126: 	my %seen;
                   8127: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8128: 	return @uniq;
                   8129:     }
1.1       albertel 8130: }
                   8131: 
1.847     albertel 8132: { 
                   8133:     my %iphost;
1.856     albertel 8134:     my %name_to_ip;
                   8135:     my %lonid_to_ip;
1.869     albertel 8136: 
1.847     albertel 8137:     sub get_hosts_from_ip {
                   8138: 	my ($ip) = @_;
                   8139: 	my %iphosts = &get_iphost();
                   8140: 	if (ref($iphosts{$ip})) {
                   8141: 	    return @{$iphosts{$ip}};
                   8142: 	}
                   8143: 	return;
1.839     albertel 8144:     }
1.864     albertel 8145:     
                   8146:     sub reset_hosts_ip_info {
                   8147: 	undef(%iphost);
                   8148: 	undef(%name_to_ip);
                   8149: 	undef(%lonid_to_ip);
                   8150:     }
1.856     albertel 8151: 
                   8152:     sub get_host_ip {
                   8153: 	my ($lonid) = @_;
                   8154: 	if (exists($lonid_to_ip{$lonid})) {
                   8155: 	    return $lonid_to_ip{$lonid};
                   8156: 	}
                   8157: 	my $name=&hostname($lonid);
                   8158:    	my $ip = gethostbyname($name);
                   8159: 	return if (!$ip || length($ip) ne 4);
                   8160: 	$ip=inet_ntoa($ip);
                   8161: 	$name_to_ip{$name}   = $ip;
                   8162: 	$lonid_to_ip{$lonid} = $ip;
                   8163: 	return $ip;
                   8164:     }
1.847     albertel 8165:     
                   8166:     sub get_iphost {
1.869     albertel 8167: 	my ($ignore_cache) = @_;
1.894     albertel 8168: 
1.869     albertel 8169: 	if (!$ignore_cache) {
                   8170: 	    if (%iphost) {
                   8171: 		return %iphost;
                   8172: 	    }
                   8173: 	    my ($ip_info,$cached)=
                   8174: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8175: 	    if ($cached) {
                   8176: 		%iphost      = %{$ip_info->[0]};
                   8177: 		%name_to_ip  = %{$ip_info->[1]};
                   8178: 		%lonid_to_ip = %{$ip_info->[2]};
                   8179: 		return %iphost;
                   8180: 	    }
                   8181: 	}
1.894     albertel 8182: 
                   8183: 	# get yesterday's info for fallback
                   8184: 	my %old_name_to_ip;
                   8185: 	my ($ip_info,$cached)=
                   8186: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8187: 	if ($cached) {
                   8188: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8189: 	}
                   8190: 
1.888     albertel 8191: 	my %name_to_host = &all_names();
                   8192: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8193: 	    my $ip;
                   8194: 	    if (!exists($name_to_ip{$name})) {
                   8195: 		$ip = gethostbyname($name);
                   8196: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8197: 		    if (defined($old_name_to_ip{$name})) {
                   8198: 			$ip = $old_name_to_ip{$name};
                   8199: 			&logthis("Can't find $name defaulting to old $ip");
                   8200: 		    } else {
                   8201: 			&logthis("Name $name no IP found");
                   8202: 			next;
                   8203: 		    }
                   8204: 		} else {
                   8205: 		    $ip=inet_ntoa($ip);
1.847     albertel 8206: 		}
                   8207: 		$name_to_ip{$name} = $ip;
                   8208: 	    } else {
                   8209: 		$ip = $name_to_ip{$name};
1.653     albertel 8210: 	    }
1.888     albertel 8211: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8212: 		$lonid_to_ip{$id} = $ip;
                   8213: 	    }
                   8214: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8215: 	}
1.869     albertel 8216: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8217: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8218: 				      48*60*60);
1.869     albertel 8219: 
1.847     albertel 8220: 	return %iphost;
1.598     albertel 8221:     }
                   8222: }
                   8223: 
1.862     albertel 8224: BEGIN {
                   8225: 
                   8226: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8227:     unless ($readit) {
                   8228: {
                   8229:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8230:     %perlvar = (%perlvar,%{$configvars});
                   8231: }
                   8232: 
                   8233: 
1.1       albertel 8234: # ------------------------------------------------------ Read spare server file
                   8235: {
1.448     albertel 8236:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8237: 
                   8238:     while (my $configline=<$config>) {
                   8239:        chomp($configline);
1.284     matthew  8240:        if ($configline) {
1.784     albertel 8241: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8242: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8243: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8244:        }
                   8245:     }
1.448     albertel 8246:     close($config);
1.1       albertel 8247: }
1.11      www      8248: # ------------------------------------------------------------ Read permissions
                   8249: {
1.448     albertel 8250:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8251: 
                   8252:     while (my $configline=<$config>) {
1.448     albertel 8253: 	chomp($configline);
                   8254: 	if ($configline) {
                   8255: 	    my ($role,$perm)=split(/ /,$configline);
                   8256: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8257: 	}
1.11      www      8258:     }
1.448     albertel 8259:     close($config);
1.11      www      8260: }
                   8261: 
                   8262: # -------------------------------------------- Read plain texts for permissions
                   8263: {
1.448     albertel 8264:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8265: 
                   8266:     while (my $configline=<$config>) {
1.448     albertel 8267: 	chomp($configline);
                   8268: 	if ($configline) {
1.742     raeburn  8269: 	    my ($short,@plain)=split(/:/,$configline);
                   8270:             %{$prp{$short}} = ();
                   8271: 	    if (@plain > 0) {
                   8272:                 $prp{$short}{'std'} = $plain[0];
                   8273:                 for (my $i=1; $i<@plain; $i++) {
                   8274:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8275:                 }
                   8276:             }
1.448     albertel 8277: 	}
1.135     www      8278:     }
1.448     albertel 8279:     close($config);
1.135     www      8280: }
                   8281: 
                   8282: # ---------------------------------------------------------- Read package table
                   8283: {
1.448     albertel 8284:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8285: 
                   8286:     while (my $configline=<$config>) {
1.483     albertel 8287: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8288: 	chomp($configline);
                   8289: 	my ($short,$plain)=split(/:/,$configline);
                   8290: 	my ($pack,$name)=split(/\&/,$short);
                   8291: 	if ($plain ne '') {
                   8292: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8293: 	    $packagetab{$short}=$plain; 
                   8294: 	}
1.11      www      8295:     }
1.448     albertel 8296:     close($config);
1.329     matthew  8297: }
                   8298: 
                   8299: # ------------- set up temporary directory
                   8300: {
                   8301:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8302: 
1.11      www      8303: }
                   8304: 
1.794     albertel 8305: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8306: 				'compress_threshold'=> 20_000,
                   8307:  			        });
1.185     www      8308: 
1.281     www      8309: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8310: $dumpcount=0;
1.22      www      8311: 
1.163     harris41 8312: &logtouch();
1.672     albertel 8313: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8314: $readit=1;
1.564     albertel 8315:     {
                   8316: 	use integer;
                   8317: 	my $test=(2**32)+1;
1.568     albertel 8318: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8319: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8320:     }
1.195     www      8321: }
1.1       albertel 8322: }
1.179     www      8323: 
1.1       albertel 8324: 1;
1.191     harris41 8325: __END__
                   8326: 
1.243     albertel 8327: =pod
                   8328: 
1.191     harris41 8329: =head1 NAME
                   8330: 
1.243     albertel 8331: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8332: 
                   8333: =head1 SYNOPSIS
                   8334: 
1.243     albertel 8335: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8336: 
                   8337:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8338: 
1.243     albertel 8339: Common parameters:
                   8340: 
                   8341: =over 4
                   8342: 
                   8343: =item *
                   8344: 
                   8345: $uname : an internal username (if $cname expecting a course Id specifically)
                   8346: 
                   8347: =item *
                   8348: 
                   8349: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8350: 
                   8351: =item *
                   8352: 
                   8353: $symb : a resource instance identifier
                   8354: 
                   8355: =item *
                   8356: 
                   8357: $namespace : the name of a .db file that contains the data needed or
                   8358: being set.
                   8359: 
                   8360: =back
                   8361: 
1.394     bowersj2 8362: =head1 OVERVIEW
1.191     harris41 8363: 
1.394     bowersj2 8364: lonnet provides subroutines which interact with the
                   8365: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8366: about classes, users, and resources.
1.243     albertel 8367: 
                   8368: For many of these objects you can also use this to store data about
                   8369: them or modify them in various ways.
1.191     harris41 8370: 
1.394     bowersj2 8371: =head2 Symbs
1.191     harris41 8372: 
1.394     bowersj2 8373: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8374: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8375: map, the resource number of the resource in the map, and the URL of
                   8376: the resource itself. The latter is somewhat redundant, but might help
                   8377: if maps change.
                   8378: 
                   8379: An example is
                   8380: 
                   8381:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8382: 
                   8383: The respective map entry is
                   8384: 
                   8385:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8386:   title="Problem 2">
                   8387:  </resource>
                   8388: 
                   8389: Symbs are used by the random number generator, as well as to store and
                   8390: restore data specific to a certain instance of for example a problem.
                   8391: 
                   8392: =head2 Storing And Retrieving Data
                   8393: 
                   8394: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8395: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8396: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8397: is is the non-critical message twin of cstore. These functions are for
                   8398: handlers to store a perl hash to a user's permanent data space in an
                   8399: easy manner, and to retrieve it again on another call. It is expected
                   8400: that a handler would use this once at the beginning to retrieve data,
                   8401: and then again once at the end to send only the new data back.
                   8402: 
                   8403: The data is stored in the user's data directory on the user's
                   8404: homeserver under the ID of the course.
                   8405: 
                   8406: The hash that is returned by restore will have all of the previous
                   8407: value for all of the elements of the hash.
                   8408: 
                   8409: Example:
                   8410: 
                   8411:  #creating a hash
                   8412:  my %hash;
                   8413:  $hash{'foo'}='bar';
                   8414: 
                   8415:  #storing it
                   8416:  &Apache::lonnet::cstore(\%hash);
                   8417: 
                   8418:  #changing a value
                   8419:  $hash{'foo'}='notbar';
                   8420: 
                   8421:  #adding a new value
                   8422:  $hash{'bar'}='foo';
                   8423:  &Apache::lonnet::cstore(\%hash);
                   8424: 
                   8425:  #retrieving the hash
                   8426:  my %history=&Apache::lonnet::restore();
                   8427: 
                   8428:  #print the hash
                   8429:  foreach my $key (sort(keys(%history))) {
                   8430:    print("\%history{$key} = $history{$key}");
                   8431:  }
                   8432: 
                   8433: Will print out:
1.191     harris41 8434: 
1.394     bowersj2 8435:  %history{1:foo} = bar
                   8436:  %history{1:keys} = foo:timestamp
                   8437:  %history{1:timestamp} = 990455579
                   8438:  %history{2:bar} = foo
                   8439:  %history{2:foo} = notbar
                   8440:  %history{2:keys} = foo:bar:timestamp
                   8441:  %history{2:timestamp} = 990455580
                   8442:  %history{bar} = foo
                   8443:  %history{foo} = notbar
                   8444:  %history{timestamp} = 990455580
                   8445:  %history{version} = 2
                   8446: 
                   8447: Note that the special hash entries C<keys>, C<version> and
                   8448: C<timestamp> were added to the hash. C<version> will be equal to the
                   8449: total number of versions of the data that have been stored. The
                   8450: C<timestamp> attribute will be the UNIX time the hash was
                   8451: stored. C<keys> is available in every historical section to list which
                   8452: keys were added or changed at a specific historical revision of a
                   8453: hash.
                   8454: 
                   8455: B<Warning>: do not store the hash that restore returns directly. This
                   8456: will cause a mess since it will restore the historical keys as if the
                   8457: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8458: 
1.394     bowersj2 8459: Calling convention:
1.191     harris41 8460: 
1.394     bowersj2 8461:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8462:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8463: 
1.394     bowersj2 8464: For more detailed information, see lonnet specific documentation.
1.191     harris41 8465: 
1.394     bowersj2 8466: =head1 RETURN MESSAGES
1.191     harris41 8467: 
1.394     bowersj2 8468: =over 4
1.191     harris41 8469: 
1.394     bowersj2 8470: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8471: 
1.394     bowersj2 8472: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8473: when the connection is brought back up
1.191     harris41 8474: 
1.394     bowersj2 8475: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8476: for later delivery
1.191     harris41 8477: 
1.394     bowersj2 8478: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8479: 
1.394     bowersj2 8480: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8481: that was requested
1.191     harris41 8482: 
1.243     albertel 8483: =back
1.191     harris41 8484: 
1.243     albertel 8485: =head1 PUBLIC SUBROUTINES
1.191     harris41 8486: 
1.243     albertel 8487: =head2 Session Environment Functions
1.191     harris41 8488: 
1.243     albertel 8489: =over 4
1.191     harris41 8490: 
1.394     bowersj2 8491: =item * 
                   8492: X<appenv()>
                   8493: B<appenv(%hash)>: the value of %hash is written to
                   8494: the user envirnoment file, and will be restored for each access this
1.620     albertel 8495: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8496: process
1.191     harris41 8497: 
                   8498: =item *
1.394     bowersj2 8499: X<delenv()>
                   8500: B<delenv($regexp)>: removes all items from the session
                   8501: environment file that matches the regular expression in $regexp. The
1.620     albertel 8502: values are also delted from the current processes %env.
1.191     harris41 8503: 
1.795     albertel 8504: =item * get_env_multiple($name) 
                   8505: 
                   8506: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8507: values may be defined and end up as an array ref.
                   8508: 
                   8509: returns an array of values
                   8510: 
1.243     albertel 8511: =back
                   8512: 
                   8513: =head2 User Information
1.191     harris41 8514: 
1.243     albertel 8515: =over 4
1.191     harris41 8516: 
                   8517: =item *
1.394     bowersj2 8518: X<queryauthenticate()>
                   8519: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8520: authentication scheme
                   8521: 
                   8522: =item *
1.394     bowersj2 8523: X<authenticate()>
                   8524: B<authenticate($uname,$upass,$udom)>: try to
                   8525: authenticate user from domain's lib servers (first use the current
                   8526: one). C<$upass> should be the users password.
1.191     harris41 8527: 
                   8528: =item *
1.394     bowersj2 8529: X<homeserver()>
                   8530: B<homeserver($uname,$udom)>: find the server which has
                   8531: the user's directory and files (there must be only one), this caches
                   8532: the answer, and also caches if there is a borken connection.
1.191     harris41 8533: 
                   8534: =item *
1.394     bowersj2 8535: X<idget()>
                   8536: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8537: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8538: username, and only 1 username per ID in a specific domain) (returns
                   8539: hash: id=>name,id=>name)
1.191     harris41 8540: 
                   8541: =item *
1.394     bowersj2 8542: X<idrget()>
                   8543: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8544: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8545: 
                   8546: =item *
1.394     bowersj2 8547: X<idput()>
                   8548: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8549: 
                   8550: =item *
1.394     bowersj2 8551: X<rolesinit()>
                   8552: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8553: 
                   8554: =item *
1.551     albertel 8555: X<getsection()>
                   8556: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8557: course $cname, return section name/number or '' for "not in course"
                   8558: and '-1' for "no section"
                   8559: 
                   8560: =item *
1.394     bowersj2 8561: X<userenvironment()>
                   8562: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8563: passed in @what from the requested user's environment, returns a hash
                   8564: 
1.858     raeburn  8565: =item * 
                   8566: X<userlog_query()>
1.859     albertel 8567: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8568: activity.log file. %filters defines filters applied when parsing the
                   8569: log file. These can be start or end timestamps, or the type of action
                   8570: - log to look for Login or Logout events, check for Checkin or
                   8571: Checkout, role for role selection. The response is in the form
                   8572: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8573: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8574: 
1.243     albertel 8575: =back
                   8576: 
                   8577: =head2 User Roles
                   8578: 
                   8579: =over 4
                   8580: 
                   8581: =item *
                   8582: 
1.810     raeburn  8583: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8584:  F: full access
                   8585:  U,I,K: authentication modes (cxx only)
                   8586:  '': forbidden
                   8587:  1: user needs to choose course
                   8588:  2: browse allowed
1.766     albertel 8589:  A: passphrase authentication needed
1.243     albertel 8590: 
                   8591: =item *
                   8592: 
                   8593: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8594: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8595: and course level
                   8596: 
                   8597: =item *
                   8598: 
                   8599: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8600: explanation of a user role term
                   8601: 
1.832     raeburn  8602: =item *
                   8603: 
1.858     raeburn  8604: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8605: All arguments are optional. Returns a hash of a roles, either for
                   8606: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8607: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8608: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8609: and value is set to colon-separated start and end times for the role.
                   8610: If no username and domain are specified, will default to current
                   8611: user/domain. Types, roles, and roledoms are references to arrays,
                   8612: of role statuses (active, future or previous), roles 
                   8613: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8614: to restrict the list of roles reported. If no array ref is 
                   8615: provided for types, will default to return only active roles.
1.834     albertel 8616: 
1.243     albertel 8617: =back
                   8618: 
                   8619: =head2 User Modification
                   8620: 
                   8621: =over 4
                   8622: 
                   8623: =item *
                   8624: 
                   8625: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8626: user for the level given by URL.  Optional start and end dates (leave empty
                   8627: string or zero for "no date")
1.191     harris41 8628: 
                   8629: =item *
                   8630: 
1.243     albertel 8631: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8632: change a users, password, possible return values are: ok,
                   8633: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8634: refused
1.191     harris41 8635: 
                   8636: =item *
                   8637: 
1.243     albertel 8638: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8639: 
                   8640: =item *
                   8641: 
1.243     albertel 8642: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8643: modify user
1.191     harris41 8644: 
                   8645: =item *
                   8646: 
1.286     matthew  8647: modifystudent
                   8648: 
                   8649: modify a students enrollment and identification information.
                   8650: The course id is resolved based on the current users environment.  
                   8651: This means the envoking user must be a course coordinator or otherwise
                   8652: associated with a course.
                   8653: 
1.297     matthew  8654: This call is essentially a wrapper for lonnet::modifyuser and
                   8655: lonnet::modify_student_enrollment
1.286     matthew  8656: 
                   8657: Inputs: 
                   8658: 
                   8659: =over 4
                   8660: 
                   8661: =item B<$udom> Students loncapa domain
                   8662: 
                   8663: =item B<$uname> Students loncapa login name
                   8664: 
                   8665: =item B<$uid> Students id/student number
                   8666: 
                   8667: =item B<$umode> Students authentication mode
                   8668: 
                   8669: =item B<$upass> Students password
                   8670: 
                   8671: =item B<$first> Students first name
                   8672: 
                   8673: =item B<$middle> Students middle name
                   8674: 
                   8675: =item B<$last> Students last name
                   8676: 
                   8677: =item B<$gene> Students generation
                   8678: 
                   8679: =item B<$usec> Students section in course
                   8680: 
                   8681: =item B<$end> Unix time of the roles expiration
                   8682: 
                   8683: =item B<$start> Unix time of the roles start date
                   8684: 
                   8685: =item B<$forceid> If defined, allow $uid to be changed
                   8686: 
                   8687: =item B<$desiredhome> server to use as home server for student
                   8688: 
                   8689: =back
1.297     matthew  8690: 
                   8691: =item *
                   8692: 
                   8693: modify_student_enrollment
                   8694: 
                   8695: Change a students enrollment status in a class.  The environment variable
                   8696: 'role.request.course' must be defined for this function to proceed.
                   8697: 
                   8698: Inputs:
                   8699: 
                   8700: =over 4
                   8701: 
                   8702: =item $udom, students domain
                   8703: 
                   8704: =item $uname, students name
                   8705: 
                   8706: =item $uid, students user id
                   8707: 
                   8708: =item $first, students first name
                   8709: 
                   8710: =item $middle
                   8711: 
                   8712: =item $last
                   8713: 
                   8714: =item $gene
                   8715: 
                   8716: =item $usec
                   8717: 
                   8718: =item $end
                   8719: 
                   8720: =item $start
                   8721: 
                   8722: =back
                   8723: 
1.191     harris41 8724: 
                   8725: =item *
                   8726: 
1.243     albertel 8727: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8728: custom role; give a custom role to a user for the level given by URL.  Specify
                   8729: name and domain of role author, and role name
1.191     harris41 8730: 
                   8731: =item *
                   8732: 
1.243     albertel 8733: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8734: 
                   8735: =item *
                   8736: 
1.243     albertel 8737: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8738: 
                   8739: =back
                   8740: 
                   8741: =head2 Course Infomation
                   8742: 
                   8743: =over 4
1.191     harris41 8744: 
                   8745: =item *
                   8746: 
1.631     albertel 8747: coursedescription($courseid) : returns a hash of information about the
                   8748: specified course id, including all environment settings for the
                   8749: course, the description of the course will be in the hash under the
                   8750: key 'description'
1.191     harris41 8751: 
                   8752: =item *
                   8753: 
1.624     albertel 8754: resdata($name,$domain,$type,@which) : request for current parameter
                   8755: setting for a specific $type, where $type is either 'course' or 'user',
                   8756: @what should be a list of parameters to ask about. This routine caches
                   8757: answers for 5 minutes.
1.243     albertel 8758: 
1.877     foxr     8759: =item *
                   8760: 
                   8761: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8762: data base, returning a hash that is keyed by the resource name and has
                   8763: values that are the resource value.  I believe that the timestamps and
                   8764: versions are also returned.
                   8765: 
                   8766: 
1.243     albertel 8767: =back
                   8768: 
                   8769: =head2 Course Modification
                   8770: 
                   8771: =over 4
1.191     harris41 8772: 
                   8773: =item *
                   8774: 
1.243     albertel 8775: writecoursepref($courseid,%prefs) : write preferences (environment
                   8776: database) for a course
1.191     harris41 8777: 
                   8778: =item *
                   8779: 
1.243     albertel 8780: createcourse($udom,$description,$url) : make/modify course
                   8781: 
                   8782: =back
                   8783: 
                   8784: =head2 Resource Subroutines
                   8785: 
                   8786: =over 4
1.191     harris41 8787: 
                   8788: =item *
                   8789: 
1.243     albertel 8790: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8791: 
                   8792: =item *
                   8793: 
1.243     albertel 8794: repcopy($filename) : subscribes to the requested file, and attempts to
                   8795: replicate from the owning library server, Might return
1.607     raeburn  8796: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8797: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8798: resource. Expects the local filesystem pathname
                   8799: (/home/httpd/html/res/....)
                   8800: 
                   8801: =back
                   8802: 
                   8803: =head2 Resource Information
                   8804: 
                   8805: =over 4
1.191     harris41 8806: 
                   8807: =item *
                   8808: 
1.243     albertel 8809: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8810: a vairety of different possible values, $varname should be a request
                   8811: string, and the other parameters can be used to specify who and what
                   8812: one is asking about.
                   8813: 
                   8814: Possible values for $varname are environment.lastname (or other item
                   8815: from the envirnment hash), user.name (or someother aspect about the
                   8816: user), resource.0.maxtries (or some other part and parameter of a
                   8817: resource)
1.204     albertel 8818: 
                   8819: =item *
                   8820: 
1.243     albertel 8821: directcondval($number) : get current value of a condition; reads from a state
                   8822: string
1.204     albertel 8823: 
                   8824: =item *
                   8825: 
1.243     albertel 8826: condval($condidx) : value of condition index based on state
1.204     albertel 8827: 
                   8828: =item *
                   8829: 
1.243     albertel 8830: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8831: resource's metadata, $what should be either a specific key, or either
                   8832: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8833: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8834: 
                   8835: this function automatically caches all requests
1.191     harris41 8836: 
                   8837: =item *
                   8838: 
1.243     albertel 8839: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8840: network of library servers; returns file handle of where SQL and regex results
                   8841: will be stored for query
1.191     harris41 8842: 
                   8843: =item *
                   8844: 
1.243     albertel 8845: symbread($filename) : return symbolic list entry (filename argument optional);
                   8846: returns the data handle
1.191     harris41 8847: 
                   8848: =item *
                   8849: 
1.243     albertel 8850: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8851: a possible symb for the URL in $thisfn, and if is an encryypted
                   8852: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8853: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8854: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8855: 
1.191     harris41 8856: 
                   8857: =item *
                   8858: 
1.243     albertel 8859: symbclean($symb) : removes versions numbers from a symb, returns the
                   8860: cleaned symb
1.191     harris41 8861: 
                   8862: =item *
                   8863: 
1.243     albertel 8864: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8865: course map, user must be in a course for it to work.
1.191     harris41 8866: 
                   8867: =item *
                   8868: 
1.243     albertel 8869: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8870: 
                   8871: =item *
                   8872: 
1.243     albertel 8873: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8874: a random seed, all arguments are optional, if they aren't sent it uses the
                   8875: environment to derive them. Note: if symb isn't sent and it can't get one
                   8876: from &symbread it will use the current time as its return value
1.191     harris41 8877: 
                   8878: =item *
                   8879: 
1.243     albertel 8880: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8881: unfakeable, receipt
1.191     harris41 8882: 
                   8883: =item *
                   8884: 
1.620     albertel 8885: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8886: 
                   8887: =item *
                   8888: 
1.243     albertel 8889: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8890: 
                   8891: =item *
                   8892: 
1.243     albertel 8893: 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 8894: 
                   8895: =item *
                   8896: 
1.243     albertel 8897: 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 8898: 
                   8899: =item *
                   8900: 
1.243     albertel 8901: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8902: 
                   8903: =item *
                   8904: 
1.243     albertel 8905: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8906: forcing spreadsheet to reevaluate the resource scores next time.
                   8907: 
                   8908: =back
                   8909: 
                   8910: =head2 Storing/Retreiving Data
                   8911: 
                   8912: =over 4
1.191     harris41 8913: 
                   8914: =item *
                   8915: 
1.243     albertel 8916: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8917: for this url; hashref needs to be given and should be a \%hashname; the
                   8918: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8919: be derived from the env
1.191     harris41 8920: 
                   8921: =item *
                   8922: 
1.243     albertel 8923: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8924: uses critical subroutine
1.191     harris41 8925: 
                   8926: =item *
                   8927: 
1.243     albertel 8928: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8929: all args are optional
1.191     harris41 8930: 
                   8931: =item *
                   8932: 
1.717     albertel 8933: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8934: dumps the complete (or key matching regexp) namespace into a hash
                   8935: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8936: normally &store()ed into
                   8937: 
                   8938: $range should be either an integer '100' (give me the first 100
                   8939:                                            matching records)
                   8940:               or be  two integers sperated by a - with no spaces
                   8941:                  '30-50' (give me the 30th through the 50th matching
                   8942:                           records)
                   8943: 
                   8944: 
                   8945: =item *
                   8946: 
                   8947: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8948: replaces a &store() version of data with a replacement set of data
                   8949: for a particular resource in a namespace passed in the $storehash hash 
                   8950: reference
                   8951: 
                   8952: =item *
                   8953: 
1.243     albertel 8954: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8955: works very similar to store/cstore, but all data is stored in a
                   8956: temporary location and can be reset using tmpreset, $storehash should
                   8957: be a hash reference, returns nothing on success
1.191     harris41 8958: 
                   8959: =item *
                   8960: 
1.243     albertel 8961: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8962: similar to restore, but all data is stored in a temporary location and
                   8963: can be reset using tmpreset. Returns a hash of values on success,
                   8964: error string otherwise.
1.191     harris41 8965: 
                   8966: =item *
                   8967: 
1.243     albertel 8968: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8969: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8970: 
                   8971: =item *
                   8972: 
1.243     albertel 8973: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8974: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8975: 
                   8976: =item *
                   8977: 
1.243     albertel 8978: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8979: namesp ($udom and $uname are optional)
1.191     harris41 8980: 
                   8981: =item *
                   8982: 
1.702     albertel 8983: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8984: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8985: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8986: 
1.702     albertel 8987: $range should be either an integer '100' (give me the first 100
                   8988:                                            matching records)
                   8989:               or be  two integers sperated by a - with no spaces
                   8990:                  '30-50' (give me the 30th through the 50th matching
                   8991:                           records)
1.449     matthew  8992: =item *
                   8993: 
                   8994: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8995: $store can be a scalar, an array reference, or if the amount to be 
                   8996: incremented is > 1, a hash reference.
                   8997: 
                   8998: ($udom and $uname are optional)
1.191     harris41 8999: 
                   9000: =item *
                   9001: 
1.243     albertel 9002: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9003: ($udom and $uname are optional)
1.191     harris41 9004: 
                   9005: =item *
                   9006: 
1.243     albertel 9007: cput($namespace,$storehash,$udom,$uname) : critical put
                   9008: ($udom and $uname are optional)
1.191     harris41 9009: 
                   9010: =item *
                   9011: 
1.748     albertel 9012: newput($namespace,$storehash,$udom,$uname) :
                   9013: 
                   9014: Attempts to store the items in the $storehash, but only if they don't
                   9015: currently exist, if this succeeds you can be certain that you have 
                   9016: successfully created a new key value pair in the $namespace db.
                   9017: 
                   9018: 
                   9019: Args:
                   9020:  $namespace: name of database to store values to
                   9021:  $storehash: hashref to store to the db
                   9022:  $udom: (optional) domain of user containing the db
                   9023:  $uname: (optional) name of user caontaining the db
                   9024: 
                   9025: Returns:
                   9026:  'ok' -> succeeded in storing all keys of $storehash
                   9027:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9028:                         least <key> already existed in the db (other
                   9029:                         requested keys may also already exist)
                   9030:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9031:  'con_lost' -> unable to contact request server
                   9032:  'refused' -> action was not allowed by remote machine
                   9033: 
                   9034: 
                   9035: =item *
                   9036: 
1.243     albertel 9037: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9038: reference filled in from namesp (encrypts the return communication)
                   9039: ($udom and $uname are optional)
1.191     harris41 9040: 
                   9041: =item *
                   9042: 
1.243     albertel 9043: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9044: critical subroutine
                   9045: 
1.806     raeburn  9046: =item *
                   9047: 
1.860     raeburn  9048: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9049: array reference filled in from namespace found in domain level on either
                   9050: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9051: 
                   9052: =item *
                   9053: 
1.860     raeburn  9054: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9055: domain level either on specified domain server ($uhome) or primary domain 
                   9056: server ($udom and $uhome are optional)
1.806     raeburn  9057: 
1.243     albertel 9058: =back
                   9059: 
                   9060: =head2 Network Status Functions
                   9061: 
                   9062: =over 4
1.191     harris41 9063: 
                   9064: =item *
                   9065: 
                   9066: dirlist($uri) : return directory list based on URI
                   9067: 
                   9068: =item *
                   9069: 
1.243     albertel 9070: spareserver() : find server with least workload from spare.tab
                   9071: 
                   9072: =back
                   9073: 
                   9074: =head2 Apache Request
                   9075: 
                   9076: =over 4
1.191     harris41 9077: 
                   9078: =item *
                   9079: 
1.243     albertel 9080: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9081: localhost, posts hash
                   9082: 
                   9083: =back
                   9084: 
                   9085: =head2 Data to String to Data
                   9086: 
                   9087: =over 4
1.191     harris41 9088: 
                   9089: =item *
                   9090: 
1.243     albertel 9091: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9092: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9093: 
                   9094: =item *
                   9095: 
1.243     albertel 9096: hashref2str($hashref) : convert a hashref into a string complete with
                   9097: escaping and '=' and '&' separators, supports elements that are
                   9098: arrayrefs and hashrefs
1.191     harris41 9099: 
                   9100: =item *
                   9101: 
1.243     albertel 9102: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9103: with escaping and '&' separators, supports elements that are arrayrefs
                   9104: and hashrefs
1.191     harris41 9105: 
                   9106: =item *
                   9107: 
1.243     albertel 9108: str2hash($string) : convert string to hash using unescaping and
                   9109: splitting on '=' and '&', supports elements that are arrayrefs and
                   9110: hashrefs
1.191     harris41 9111: 
                   9112: =item *
                   9113: 
1.243     albertel 9114: str2array($string) : convert string to hash using unescaping and
                   9115: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9116: 
                   9117: =back
                   9118: 
                   9119: =head2 Logging Routines
                   9120: 
                   9121: =over 4
                   9122: 
                   9123: These routines allow one to make log messages in the lonnet.log and
                   9124: lonnet.perm logfiles.
1.191     harris41 9125: 
                   9126: =item *
                   9127: 
1.243     albertel 9128: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9129: 
                   9130: =item *
                   9131: 
1.243     albertel 9132: logthis() : append message to the normal lonnet.log file, it gets
                   9133: preiodically rolled over and deleted.
1.191     harris41 9134: 
                   9135: =item *
                   9136: 
1.243     albertel 9137: logperm() : append a permanent message to lonnet.perm.log, this log
                   9138: file never gets deleted by any automated portion of the system, only
                   9139: messages of critical importance should go in here.
                   9140: 
                   9141: =back
                   9142: 
                   9143: =head2 General File Helper Routines
                   9144: 
                   9145: =over 4
1.191     harris41 9146: 
                   9147: =item *
                   9148: 
1.481     raeburn  9149: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9150: (a) files in /uploaded
                   9151:   (i) If a local copy of the file exists - 
                   9152:       compares modification date of local copy with last-modified date for 
                   9153:       definitive version stored on home server for course. If local copy is 
                   9154:       stale, requests a new version from the home server and stores it. 
                   9155:       If the original has been removed from the home server, then local copy 
                   9156:       is unlinked.
                   9157:   (ii) If local copy does not exist -
                   9158:       requests the file from the home server and stores it. 
                   9159:   
                   9160:   If $caller is 'uploadrep':  
                   9161:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9162:     for request for files originally uploaded via DOCS. 
                   9163:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9164:   
                   9165:   Otherwise:
                   9166:      This indicates a call from the content generation phase of the request.
                   9167:      -  returns the entire contents of the file or -1.
                   9168:      
                   9169: (b) files in /res
                   9170:    - returns the entire contents of a file or -1; 
                   9171:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9172: 
1.712     albertel 9173: 
                   9174: =item *
                   9175: 
                   9176: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9177:                   reference
                   9178: 
                   9179: returns either a stat() list of data about the file or an empty list
                   9180: if the file doesn't exist or couldn't find out about it (connection
                   9181: problems or user unknown)
                   9182: 
1.191     harris41 9183: =item *
                   9184: 
1.243     albertel 9185: filelocation($dir,$file) : returns file system location of a file
                   9186: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9187: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9188: and a file of ../bob will become /a/bob)
1.191     harris41 9189: 
                   9190: =item *
                   9191: 
                   9192: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9193: filelocation except for hrefs
                   9194: 
                   9195: =item *
                   9196: 
                   9197: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9198: 
1.243     albertel 9199: =back
                   9200: 
1.608     albertel 9201: =head2 Usererfile file routines (/uploaded*)
                   9202: 
                   9203: =over 4
                   9204: 
                   9205: =item *
                   9206: 
                   9207: userfileupload(): main rotine for putting a file in a user or course's
                   9208:                   filespace, arguments are,
                   9209: 
1.620     albertel 9210:  formname - required - this is the name of the element in $env where the
1.608     albertel 9211:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9212:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9213:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9214:  coursedoc - if true, store the file in the course of the active role
                   9215:              of the current user
                   9216:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9217:          if undefined, it will be placed in "unknown"
                   9218: 
                   9219:  (This routine calls clean_filename() to remove any dangerous
                   9220:  characters from the filename, and then calls finuserfileupload() to
                   9221:  complete the transaction)
                   9222: 
                   9223:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9224:  and /adm/notfound.html if unsuccessful
                   9225: 
                   9226: =item *
                   9227: 
                   9228: clean_filename(): routine for cleaing a filename up for storage in
                   9229:                  userfile space, argument is:
                   9230: 
                   9231:  filename - proposed filename
                   9232: 
                   9233: returns: the new clean filename
                   9234: 
                   9235: =item *
                   9236: 
                   9237: finishuserfileupload(): routine that creaes and sends the file to
                   9238: userspace, probably shouldn't be called directly
                   9239: 
                   9240:   docuname: username or courseid of destination for the file
                   9241:   docudom: domain of user/course of destination for the file
                   9242:   formname: same as for userfileupload()
                   9243:   fname: filename (inculding subdirectories) for the file
                   9244: 
                   9245:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9246:  and /adm/notfound.html if unsuccessful
                   9247: 
                   9248: =item *
                   9249: 
                   9250: renameuserfile(): renames an existing userfile to a new name
                   9251: 
                   9252:   Args:
                   9253:    docuname: username or courseid of destination for the file
                   9254:    docudom: domain of user/course of destination for the file
                   9255:    old: current file name (including any subdirs under userfiles)
                   9256:    new: desired file name (including any subdirs under userfiles)
                   9257: 
                   9258: =item *
                   9259: 
                   9260: mkdiruserfile(): creates a directory is a userfiles dir
                   9261: 
                   9262:   Args:
                   9263:    docuname: username or courseid of destination for the file
                   9264:    docudom: domain of user/course of destination for the file
                   9265:    dir: dir to create (including any subdirs under userfiles)
                   9266: 
                   9267: =item *
                   9268: 
                   9269: removeuserfile(): removes a file that exists in userfiles
                   9270: 
                   9271:   Args:
                   9272:    docuname: username or courseid of destination for the file
                   9273:    docudom: domain of user/course of destination for the file
                   9274:    fname: filname to delete (including any subdirs under userfiles)
                   9275: 
                   9276: =item *
                   9277: 
                   9278: removeuploadedurl(): convience function for removeuserfile()
                   9279: 
                   9280:   Args:
                   9281:    url:  a full /uploaded/... url to delete
                   9282: 
1.747     albertel 9283: =item * 
                   9284: 
                   9285: get_portfile_permissions():
                   9286:   Args:
                   9287:     domain: domain of user or course contain the portfolio files
                   9288:     user: name of user or num of course contain the portfolio files
                   9289:   Returns:
                   9290:     hashref of a dump of the proper file_permissions.db
                   9291:    
                   9292: 
                   9293: =item * 
                   9294: 
                   9295: get_access_controls():
                   9296: 
                   9297: Args:
                   9298:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9299:   group: (optional) the group you want the files associated with
                   9300:   file: (optional) the file you want access info on
                   9301: 
                   9302: Returns:
1.749     raeburn  9303:     a hash (keys are file names) of hashes containing
                   9304:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9305:         values are XML containing access control settings (see below) 
1.747     albertel 9306: 
                   9307: Internal notes:
                   9308: 
1.749     raeburn  9309:  access controls are stored in file_permissions.db as key=value pairs.
                   9310:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9311:         where scope -> public,guest,course,group,domains or users.
                   9312:               end -> UNIX time for end of access (0 -> no end date)
                   9313:               start -> UNIX time for start of access
                   9314: 
                   9315:     value -> XML description of access control
                   9316:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9317:             <start></start>
                   9318:             <end></end>
                   9319: 
                   9320:             <password></password>  for scope type = guest
                   9321: 
                   9322:             <domain></domain>     for scope type = course or group
                   9323:             <number></number>
                   9324:             <roles id="">
                   9325:              <role></role>
                   9326:              <access></access>
                   9327:              <section></section>
                   9328:              <group></group>
                   9329:             </roles>
                   9330: 
                   9331:             <dom></dom>         for scope type = domains
                   9332: 
                   9333:             <users>             for scope type = users
                   9334:              <user>
                   9335:               <uname></uname>
                   9336:               <udom></udom>
                   9337:              </user>
                   9338:             </users>
                   9339:            </scope> 
                   9340:               
                   9341:  Access data is also aggregated for each file in an additional key=value pair:
                   9342:  key -> path to file/file_name\0accesscontrol 
                   9343:  value -> reference to hash
                   9344:           hash contains key = value pairs
                   9345:           where key = uniqueID:scope_end_start
                   9346:                 value = UNIX time record was last updated
                   9347: 
                   9348:           Used to improve speed of look-ups of access controls for each file.  
                   9349:  
                   9350:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9351: 
                   9352: modify_access_controls():
                   9353: 
                   9354: Modifies access controls for a portfolio file
                   9355: Args
                   9356: 1. file name
                   9357: 2. reference to hash of required changes,
                   9358: 3. domain
                   9359: 4. username
                   9360:   where domain,username are the domain of the portfolio owner 
                   9361:   (either a user or a course) 
                   9362: 
                   9363: Returns:
                   9364: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9365: 2. result of deletions ('ok' or 'error', with error message).
                   9366: 3. reference to hash of any new or updated access controls.
                   9367: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9368:    key = integer (inbound ID)
                   9369:    value = uniqueID  
1.747     albertel 9370: 
1.608     albertel 9371: =back
                   9372: 
1.243     albertel 9373: =head2 HTTP Helper Routines
                   9374: 
                   9375: =over 4
                   9376: 
1.191     harris41 9377: =item *
                   9378: 
                   9379: escape() : unpack non-word characters into CGI-compatible hex codes
                   9380: 
                   9381: =item *
                   9382: 
                   9383: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9384: 
1.243     albertel 9385: =back
                   9386: 
                   9387: =head1 PRIVATE SUBROUTINES
                   9388: 
                   9389: =head2 Underlying communication routines (Shouldn't call)
                   9390: 
                   9391: =over 4
                   9392: 
                   9393: =item *
                   9394: 
                   9395: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9396: 
                   9397: =item *
                   9398: 
                   9399: reply() : uses subreply to send a message to remote machine, logs all failures
                   9400: 
                   9401: =item *
                   9402: 
                   9403: critical() : passes a critical message to another server; if cannot
                   9404: get through then place message in connection buffer directory and
                   9405: returns con_delayed, if incapable of saving message, returns
                   9406: con_failed
                   9407: 
                   9408: =item *
                   9409: 
                   9410: reconlonc() : tries to reconnect lonc client processes.
                   9411: 
                   9412: =back
                   9413: 
                   9414: =head2 Resource Access Logging
                   9415: 
                   9416: =over 4
                   9417: 
                   9418: =item *
                   9419: 
                   9420: flushcourselogs() : flush (save) buffer logs and access logs
                   9421: 
                   9422: =item *
                   9423: 
                   9424: courselog($what) : save message for course in hash
                   9425: 
                   9426: =item *
                   9427: 
                   9428: courseacclog($what) : save message for course using &courselog().  Perform
                   9429: special processing for specific resource types (problems, exams, quizzes, etc).
                   9430: 
1.191     harris41 9431: =item *
                   9432: 
                   9433: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9434: as a PerlChildExitHandler
1.243     albertel 9435: 
                   9436: =back
                   9437: 
                   9438: =head2 Other
                   9439: 
                   9440: =over 4
                   9441: 
                   9442: =item *
                   9443: 
                   9444: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9445: 
                   9446: =back
                   9447: 
                   9448: =cut
1.877     foxr     9449: 

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