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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.909   ! raeburn     4: # $Id: lonnet.pm,v 1.908 2007/08/29 22:19:24 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.891     albertel  217:     my ($lonid) = @_;
                    218:     my $hostname = &hostname($lonid);
                    219:     if ($lonid) {
                    220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    221: 	if ($hostname && -e $peerfile) {
                    222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    224: 					     Type    => SOCK_STREAM,
                    225: 					     Timeout => 10);
                    226: 	    if ($client) {
                    227: 		print $client ("reset_retries\n");
                    228: 		my $answer=<$client>;
                    229: 		#reset just this one.
                    230: 	    }
                    231: 	}
                    232: 	return;
                    233:     }
                    234: 
1.836     www       235:     &logthis("Trying to reconnect lonc");
1.1       albertel  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  237:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  238: 	my $loncpid=<$fh>;
                    239:         chomp($loncpid);
                    240:         if (kill 0 => $loncpid) {
                    241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    242:             kill USR1 => $loncpid;
                    243:             sleep 1;
1.836     www       244:          } else {
1.12      www       245: 	    &logthis(
1.672     albertel  246:                "<font color=\"blue\">WARNING:".
1.12      www       247:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  248:         }
                    249:     } else {
1.836     www       250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  251:     }
                    252: }
                    253: 
                    254: # ------------------------------------------------------ Critical communication
1.12      www       255: 
1.1       albertel  256: sub critical {
                    257:     my ($cmd,$server)=@_;
1.838     albertel  258:     unless (&hostname($server)) {
1.672     albertel  259:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       260:                " Critical message to unknown server ($server)</font>");
                    261:         return 'no_such_host';
                    262:     }
1.1       albertel  263:     my $answer=reply($cmd,$server);
                    264:     if ($answer eq 'con_lost') {
                    265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  266: 	my $answer=reply($cmd,$server);
1.1       albertel  267:         if ($answer eq 'con_lost') {
                    268:             my $now=time;
                    269:             my $middlename=$cmd;
1.5       www       270:             $middlename=substr($middlename,0,16);
1.1       albertel  271:             $middlename=~s/\W//g;
                    272:             my $dfilename=
1.305     www       273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    274:             $dumpcount++;
1.1       albertel  275:             {
1.448     albertel  276: 		my $dfh;
                    277: 		if (open($dfh,">$dfilename")) {
                    278: 		    print $dfh "$cmd\n"; 
                    279: 		    close($dfh);
                    280: 		}
1.1       albertel  281:             }
                    282:             sleep 2;
                    283:             my $wcmd='';
                    284:             {
1.448     albertel  285: 		my $dfh;
                    286: 		if (open($dfh,"<$dfilename")) {
                    287: 		    $wcmd=<$dfh>; 
                    288: 		    close($dfh);
                    289: 		}
1.1       albertel  290:             }
                    291:             chomp($wcmd);
1.7       www       292:             if ($wcmd eq $cmd) {
1.672     albertel  293: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       294:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  295:                 &logperm("D:$server:$cmd");
                    296: 	        return 'con_delayed';
                    297:             } else {
1.672     albertel  298:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       299:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  300:                 &logperm("F:$server:$cmd");
                    301:                 return 'con_failed';
                    302:             }
                    303:         }
                    304:     }
                    305:     return $answer;
1.405     albertel  306: }
                    307: 
1.755     albertel  308: # ------------------------------------------- check if return value is an error
                    309: 
                    310: sub error {
                    311:     my ($result) = @_;
1.756     albertel  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  313: 	if ($2 == 2) { return undef; }
                    314: 	return $1;
                    315:     }
                    316:     return undef;
                    317: }
                    318: 
1.783     albertel  319: sub convert_and_load_session_env {
                    320:     my ($lonidsdir,$handle)=@_;
                    321:     my @profile;
                    322:     {
                    323: 	open(my $idf,"$lonidsdir/$handle.id");
                    324: 	flock($idf,LOCK_SH);
                    325: 	@profile=<$idf>;
                    326: 	close($idf);
                    327:     }
                    328:     my %temp_env;
                    329:     foreach my $line (@profile) {
1.786     albertel  330: 	if ($line !~ m/=/) {
                    331: 	    return 0;
                    332: 	}
1.783     albertel  333: 	chomp($line);
                    334: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    335: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    336:     }
                    337:     unlink("$lonidsdir/$handle.id");
                    338:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    339: 	    0640)) {
                    340: 	%disk_env = %temp_env;
                    341: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    342: 	untie(%disk_env);
                    343:     }
1.786     albertel  344:     return 1;
1.783     albertel  345: }
                    346: 
1.374     www       347: # ------------------------------------------- Transfer profile into environment
1.780     albertel  348: my $env_loaded;
                    349: sub transfer_profile_to_env {
1.788     albertel  350:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    351:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       352: 
1.720     albertel  353:     if (!defined($lonidsdir)) {
                    354: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    355:     }
                    356:     if (!defined($handle)) {
                    357:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    358:     }
                    359: 
1.786     albertel  360:     my $convert;
                    361:     {
                    362:     	open(my $idf,"$lonidsdir/$handle.id");
                    363: 	flock($idf,LOCK_SH);
                    364: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    365: 		&GDBM_READER(),0640)) {
                    366: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    367: 	    untie(%disk_env);
                    368: 	} else {
                    369: 	    $convert = 1;
                    370: 	}
                    371:     }
                    372:     if ($convert) {
                    373: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    374: 	    &logthis("Failed to load session, or convert session.");
                    375: 	}
1.374     www       376:     }
1.783     albertel  377: 
1.786     albertel  378:     my %remove;
1.783     albertel  379:     while ( my $envname = each(%env) ) {
1.433     matthew   380:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    381:             if ($time < time-300) {
1.783     albertel  382:                 $remove{$key}++;
1.433     matthew   383:             }
                    384:         }
                    385:     }
1.783     albertel  386: 
1.619     albertel  387:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  388:     $env_loaded=1;
1.783     albertel  389:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   390:         &delenv($expired_key);
1.374     www       391:     }
1.1       albertel  392: }
                    393: 
1.830     albertel  394: sub timed_flock {
                    395:     my ($file,$lock_type) = @_;
                    396:     my $failed=0;
                    397:     eval {
                    398: 	local $SIG{__DIE__}='DEFAULT';
                    399: 	local $SIG{ALRM}=sub {
                    400: 	    $failed=1;
                    401: 	    die("failed lock");
                    402: 	};
                    403: 	alarm(13);
                    404: 	flock($file,$lock_type);
                    405: 	alarm(0);
                    406:     };
                    407:     if ($failed) {
                    408: 	return undef;
                    409:     } else {
                    410: 	return 1;
                    411:     }
                    412: }
                    413: 
1.5       www       414: # ---------------------------------------------------------- Append Environment
                    415: 
                    416: sub appenv {
1.6       www       417:     my %newenv=@_;
1.692     albertel  418:     foreach my $key (keys(%newenv)) {
                    419: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  420:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  421:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       422:                 .'</font>');
1.692     albertel  423: 	    delete($newenv{$key});
1.35      www       424:         } else {
1.692     albertel  425:             $env{$key}=$newenv{$key};
1.35      www       426:         }
1.191     harris41  427:     }
1.830     albertel  428:     open(my $env_file,$env{'user.environment'});
                    429:     if (&timed_flock($env_file,LOCK_EX)
                    430: 	&&
                    431: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    432: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  433: 	while (my ($key,$value) = each(%newenv)) {
                    434: 	    $disk_env{$key} = $value;
1.448     albertel  435: 	}
1.783     albertel  436: 	untie(%disk_env);
1.56      www       437:     }
                    438:     return 'ok';
                    439: }
                    440: # ----------------------------------------------------- Delete from Environment
                    441: 
                    442: sub delenv {
                    443:     my $delthis=shift;
                    444:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  445:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       446:                 "Attempt to delete from environment ".$delthis);
                    447:         return 'error';
                    448:     }
1.830     albertel  449:     open(my $env_file,$env{'user.environment'});
                    450:     if (&timed_flock($env_file,LOCK_EX)
                    451: 	&&
                    452: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    453: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  454: 	foreach my $key (keys(%disk_env)) {
                    455: 	    if ($key=~/^$delthis/) { 
1.619     albertel  456:                 delete($env{$key});
1.783     albertel  457:                 delete($disk_env{$key});
1.473     matthew   458:             }
1.448     albertel  459: 	}
1.783     albertel  460: 	untie(%disk_env);
1.5       www       461:     }
                    462:     return 'ok';
1.369     albertel  463: }
                    464: 
1.790     albertel  465: sub get_env_multiple {
                    466:     my ($name) = @_;
                    467:     my @values;
                    468:     if (defined($env{$name})) {
                    469:         # exists is it an array
                    470:         if (ref($env{$name})) {
                    471:             @values=@{ $env{$name} };
                    472:         } else {
                    473:             $values[0]=$env{$name};
                    474:         }
                    475:     }
                    476:     return(@values);
                    477: }
                    478: 
1.369     albertel  479: # ------------------------------------------ Find out current server userload
                    480: # there is a copy in lond
                    481: sub userload {
                    482:     my $numusers=0;
                    483:     {
                    484: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    485: 	my $filename;
                    486: 	my $curtime=time;
                    487: 	while ($filename=readdir(LONIDS)) {
                    488: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  489: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  490: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  491: 	}
                    492: 	closedir(LONIDS);
                    493:     }
                    494:     my $userloadpercent=0;
                    495:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    496:     if ($maxuserload) {
1.371     albertel  497: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  498:     }
1.372     albertel  499:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  500:     return $userloadpercent;
1.283     www       501: }
                    502: 
                    503: # ------------------------------------------ Fight off request when overloaded
                    504: 
                    505: sub overloaderror {
                    506:     my ($r,$checkserver)=@_;
                    507:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    508:     my $loadavg;
                    509:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  510:        open(my $loadfile,'/proc/loadavg');
1.283     www       511:        $loadavg=<$loadfile>;
                    512:        $loadavg =~ s/\s.*//g;
1.285     matthew   513:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  514:        close($loadfile);
1.283     www       515:     } else {
                    516:        $loadavg=&reply('load',$checkserver);
                    517:     }
1.285     matthew   518:     my $overload=$loadavg-100;
1.283     www       519:     if ($overload>0) {
1.285     matthew   520: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       521:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       522:         return 413;
1.283     www       523:     }    
                    524:     return '';
1.5       www       525: }
1.1       albertel  526: 
                    527: # ------------------------------ Find server with least workload from spare.tab
1.11      www       528: 
1.1       albertel  529: sub spareserver {
1.670     albertel  530:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  531:     my $spare_server;
1.370     albertel  532:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  533:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    534:                                                      :  $userloadpercent;
                    535:     
                    536:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    537: 	($spare_server, $lowest_load) =
                    538: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    539:     }
                    540: 
                    541:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    542: 
                    543:     if (!$found_server) {
                    544: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    545: 	    ($spare_server, $lowest_load) =
                    546: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    547: 	}
                    548:     }
                    549: 
                    550:     if (!$want_server_name) {
1.838     albertel  551: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  552:     }
                    553:     return $spare_server;
                    554: }
                    555: 
                    556: sub compare_server_load {
                    557:     my ($try_server, $spare_server, $lowest_load) = @_;
                    558: 
                    559:     my $loadans     = &reply('load',    $try_server);
                    560:     my $userloadans = &reply('userload',$try_server);
                    561: 
                    562:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    563: 	next; #didn't get a number from the server
                    564:     }
                    565: 
                    566:     my $load;
                    567:     if ($loadans =~ /\d/) {
                    568: 	if ($userloadans =~ /\d/) {
                    569: 	    #both are numbers, pick the bigger one
                    570: 	    $load = ($loadans > $userloadans) ? $loadans 
                    571: 		                              : $userloadans;
1.411     albertel  572: 	} else {
1.784     albertel  573: 	    $load = $loadans;
1.411     albertel  574: 	}
1.784     albertel  575:     } else {
                    576: 	$load = $userloadans;
                    577:     }
                    578: 
                    579:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    580: 	$spare_server = $try_server;
                    581: 	$lowest_load  = $load;
1.370     albertel  582:     }
1.784     albertel  583:     return ($spare_server,$lowest_load);
1.202     matthew   584: }
                    585: # --------------------------------------------- Try to change a user's password
                    586: 
                    587: sub changepass {
1.799     raeburn   588:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   589:     $currentpass = &escape($currentpass);
                    590:     $newpass     = &escape($newpass);
1.799     raeburn   591:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   592: 		       $server);
                    593:     if (! $answer) {
                    594: 	&logthis("No reply on password change request to $server ".
                    595: 		 "by $uname in domain $udom.");
                    596:     } elsif ($answer =~ "^ok") {
                    597:         &logthis("$uname in $udom successfully changed their password ".
                    598: 		 "on $server.");
                    599:     } elsif ($answer =~ "^pwchange_failure") {
                    600: 	&logthis("$uname in $udom was unable to change their password ".
                    601: 		 "on $server.  The action was blocked by either lcpasswd ".
                    602: 		 "or pwchange");
                    603:     } elsif ($answer =~ "^non_authorized") {
                    604:         &logthis("$uname in $udom did not get their password correct when ".
                    605: 		 "attempting to change it on $server.");
                    606:     } elsif ($answer =~ "^auth_mode_error") {
                    607:         &logthis("$uname in $udom attempted to change their password despite ".
                    608: 		 "not being locally or internally authenticated on $server.");
                    609:     } elsif ($answer =~ "^unknown_user") {
                    610:         &logthis("$uname in $udom attempted to change their password ".
                    611: 		 "on $server but were unable to because $server is not ".
                    612: 		 "their home server.");
                    613:     } elsif ($answer =~ "^refused") {
                    614: 	&logthis("$server refused to change $uname in $udom password because ".
                    615: 		 "it was sent an unencrypted request to change the password.");
                    616:     }
                    617:     return $answer;
1.1       albertel  618: }
                    619: 
1.169     harris41  620: # ----------------------- Try to determine user's current authentication scheme
                    621: 
                    622: sub queryauthenticate {
                    623:     my ($uname,$udom)=@_;
1.456     albertel  624:     my $uhome=&homeserver($uname,$udom);
                    625:     if (!$uhome) {
                    626: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    627: 	return 'no_host';
                    628:     }
                    629:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    630:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    631: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  632:     }
1.456     albertel  633:     return $answer;
1.169     harris41  634: }
                    635: 
1.1       albertel  636: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       637: 
1.1       albertel  638: sub authenticate {
                    639:     my ($uname,$upass,$udom)=@_;
1.807     albertel  640:     $upass=&escape($upass);
                    641:     $uname= &LONCAPA::clean_username($uname);
1.836     www       642:     my $uhome=&homeserver($uname,$udom,1);
                    643:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    644: # Maybe the machine was offline and only re-appeared again recently?
                    645:         &reconlonc();
                    646: # One more
                    647: 	my $uhome=&homeserver($uname,$udom,1);
                    648: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    649: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    650: 	}
1.471     albertel  651: 	return 'no_host';
1.1       albertel  652:     }
1.471     albertel  653:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    654:     if ($answer eq 'authorized') {
                    655: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    656: 	return $uhome; 
                    657:     }
                    658:     if ($answer eq 'non_authorized') {
                    659: 	&logthis("User $uname at $udom rejected by $uhome");
                    660: 	return 'no_host'; 
1.9       www       661:     }
1.471     albertel  662:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  663:     return 'no_host';
                    664: }
                    665: 
                    666: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       667: 
1.599     albertel  668: my %homecache;
1.1       albertel  669: sub homeserver {
1.230     stredwic  670:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  671:     my $index="$uname:$udom";
1.426     albertel  672: 
1.599     albertel  673:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  674: 
                    675:     my %servers = &get_servers($udom,'library');
                    676:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  677:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  678: 		 exists($badServerCache{$tryserver}));
1.841     albertel  679: 
                    680: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    681: 	if ($answer eq 'found') {
                    682: 	    delete($badServerCache{$tryserver}); 
                    683: 	    return $homecache{$index}=$tryserver;
                    684: 	} elsif ($answer eq 'no_host') {
                    685: 	    $badServerCache{$tryserver}=1;
                    686: 	}
1.1       albertel  687:     }    
                    688:     return 'no_host';
1.70      www       689: }
                    690: 
                    691: # ------------------------------------- Find the usernames behind a list of IDs
                    692: 
                    693: sub idget {
                    694:     my ($udom,@ids)=@_;
                    695:     my %returnhash=();
                    696:     
1.841     albertel  697:     my %servers = &get_servers($udom,'library');
                    698:     foreach my $tryserver (keys(%servers)) {
                    699: 	my $idlist=join('&',@ids);
                    700: 	$idlist=~tr/A-Z/a-z/; 
                    701: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    702: 	my @answer=();
                    703: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    704: 	    @answer=split(/\&/,$reply);
                    705: 	}                    ;
                    706: 	my $i;
                    707: 	for ($i=0;$i<=$#ids;$i++) {
                    708: 	    if ($answer[$i]) {
                    709: 		$returnhash{$ids[$i]}=$answer[$i];
                    710: 	    } 
                    711: 	}
                    712:     } 
1.70      www       713:     return %returnhash;
                    714: }
                    715: 
                    716: # ------------------------------------- Find the IDs behind a list of usernames
                    717: 
                    718: sub idrget {
                    719:     my ($udom,@unames)=@_;
                    720:     my %returnhash=();
1.800     albertel  721:     foreach my $uname (@unames) {
                    722:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  723:     }
1.70      www       724:     return %returnhash;
                    725: }
                    726: 
                    727: # ------------------------------- Store away a list of names and associated IDs
                    728: 
                    729: sub idput {
                    730:     my ($udom,%ids)=@_;
                    731:     my %servers=();
1.800     albertel  732:     foreach my $uname (keys(%ids)) {
                    733: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    734:         my $uhom=&homeserver($uname,$udom);
1.70      www       735:         if ($uhom ne 'no_host') {
1.800     albertel  736:             my $id=&escape($ids{$uname});
1.70      www       737:             $id=~tr/A-Z/a-z/;
1.800     albertel  738:             my $esc_unam=&escape($uname);
1.70      www       739: 	    if ($servers{$uhom}) {
1.800     albertel  740: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       741:             } else {
1.800     albertel  742:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       743:             }
                    744:         }
1.191     harris41  745:     }
1.800     albertel  746:     foreach my $server (keys(%servers)) {
                    747:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  748:     }
1.344     www       749: }
                    750: 
1.806     raeburn   751: # ------------------------------------------- get items from domain db files   
                    752: 
                    753: sub get_dom {
1.860     raeburn   754:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   755:     my $items='';
                    756:     foreach my $item (@$storearr) {
                    757:         $items.=&escape($item).'&';
                    758:     }
                    759:     $items=~s/\&$//;
1.860     raeburn   760:     if (!$udom) {
                    761:         $udom=$env{'user.domain'};
                    762:         if (defined(&domain($udom,'primary'))) {
                    763:             $uhome=&domain($udom,'primary');
                    764:         } else {
1.874     albertel  765:             undef($uhome);
1.860     raeburn   766:         }
                    767:     } else {
                    768:         if (!$uhome) {
                    769:             if (defined(&domain($udom,'primary'))) {
                    770:                 $uhome=&domain($udom,'primary');
                    771:             }
                    772:         }
                    773:     }
                    774:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   775:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   776:         my %returnhash;
1.875     albertel  777:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   778:             return %returnhash;
                    779:         }
1.806     raeburn   780:         my @pairs=split(/\&/,$rep);
                    781:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    782:             return @pairs;
                    783:         }
                    784:         my $i=0;
                    785:         foreach my $item (@$storearr) {
                    786:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    787:             $i++;
                    788:         }
                    789:         return %returnhash;
                    790:     } else {
1.880     banghart  791:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   792:     }
                    793: }
                    794: 
                    795: # -------------------------------------------- put items in domain db files 
                    796: 
                    797: sub put_dom {
1.860     raeburn   798:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    799:     if (!$udom) {
                    800:         $udom=$env{'user.domain'};
                    801:         if (defined(&domain($udom,'primary'))) {
                    802:             $uhome=&domain($udom,'primary');
                    803:         } else {
1.874     albertel  804:             undef($uhome);
1.860     raeburn   805:         }
                    806:     } else {
                    807:         if (!$uhome) {
                    808:             if (defined(&domain($udom,'primary'))) {
                    809:                 $uhome=&domain($udom,'primary');
                    810:             }
                    811:         }
                    812:     } 
                    813:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   814:         my $items='';
                    815:         foreach my $item (keys(%$storehash)) {
                    816:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    817:         }
                    818:         $items=~s/\&$//;
                    819:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    820:     } else {
1.860     raeburn   821:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   822:     }
                    823: }
                    824: 
1.837     raeburn   825: sub retrieve_inst_usertypes {
                    826:     my ($udom) = @_;
                    827:     my (%returnhash,@order);
1.846     albertel  828:     if (defined(&domain($udom,'primary'))) {
                    829:         my $uhome=&domain($udom,'primary');
1.837     raeburn   830:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    831:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    832:         my @pairs=split(/\&/,$hashitems);
                    833:         foreach my $item (@pairs) {
                    834:             my ($key,$value)=split(/=/,$item,2);
                    835:             $key = &unescape($key);
                    836:             next if ($key =~ /^error: 2 /);
                    837:             $returnhash{$key}=&thaw_unescape($value);
                    838:         }
                    839:         my @esc_order = split(/\&/,$orderitems);
                    840:         foreach my $item (@esc_order) {
                    841:             push(@order,&unescape($item));
                    842:         }
                    843:     } else {
                    844:         &logthis("get_dom failed - no primary domain server for $udom");
                    845:     }
                    846:     return (\%returnhash,\@order);
                    847: }
                    848: 
1.868     raeburn   849: sub is_domainimage {
                    850:     my ($url) = @_;
                    851:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    852:         if (&domain($1) ne '') {
                    853:             return '1';
                    854:         }
                    855:     }
                    856:     return;
                    857: }
                    858: 
1.899     raeburn   859: sub inst_directory_query {
                    860:     my ($srch) = @_;
                    861:     my $udom = $srch->{'srchdomain'};
                    862:     my %results;
                    863:     my $homeserver = &domain($udom,'primary');
1.909   ! raeburn   864:     my $outcome;
1.899     raeburn   865:     if ($homeserver ne '') {
1.904     albertel  866: 	my $queryid=&reply("querysend:instdirsearch:".
                    867: 			   &escape($srch->{'srchby'}).':'.
                    868: 			   &escape($srch->{'srchterm'}).':'.
                    869: 			   &escape($srch->{'srchtype'}),$homeserver);
                    870: 	my $host=&hostname($homeserver);
                    871: 	if ($queryid !~/^\Q$host\E\_/) {
                    872: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    873: 	    return;
                    874: 	}
                    875: 	my $response = &get_query_reply($queryid);
                    876: 	my $maxtries = 5;
                    877: 	my $tries = 1;
                    878: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    879: 	    $response = &get_query_reply($queryid);
                    880: 	    $tries ++;
                    881: 	}
                    882: 
                    883:         if (!&error($response) && $response ne 'refused') {
1.909   ! raeburn   884:             if ($response eq 'unavailable') {
        !           885:                 $outcome = $response;
        !           886:             } else {
        !           887:                 $outcome = 'ok';
        !           888:                 my @matches = split(/\n/,$response);
        !           889:                 foreach my $match (@matches) {
        !           890:                     my ($key,$value) = split(/=/,$match);
        !           891:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
        !           892:                 }
1.899     raeburn   893:             }
                    894:         }
                    895:     }
1.909   ! raeburn   896:     return ($outcome,%results);
1.899     raeburn   897: }
                    898: 
                    899: sub usersearch {
                    900:     my ($srch) = @_;
                    901:     my $dom = $srch->{'srchdomain'};
                    902:     my %results;
                    903:     my %libserv = &all_library();
                    904:     my $query = 'usersearch';
                    905:     foreach my $tryserver (keys(%libserv)) {
                    906:         if (&host_domain($tryserver) eq $dom) {
                    907:             my $host=&hostname($tryserver);
                    908:             my $queryid=
                    909:                 &reply("querysend:".&escape($query).':'.&escape($dom).':'.
                    910:                        &escape($srch->{'srchby'}).'%%'.
                    911:                        &escape($srch->{'srchtype'}).':'.
                    912:                        &escape($srch->{'srchterm'}),$tryserver);
                    913:             if ($queryid !~/^\Q$host\E\_/) {
                    914:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   915:                 next;
1.899     raeburn   916:             }
                    917:             my $reply = &get_query_reply($queryid);
                    918:             my $maxtries = 1;
                    919:             my $tries = 1;
                    920:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    921:                 $reply = &get_query_reply($queryid);
                    922:                 $tries ++;
                    923:             }
                    924:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    925:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    926:             } else {
1.900     albertel  927:                 my @matches = split(/&/,$reply);
1.899     raeburn   928:                 foreach my $match (@matches) {
                    929:                     my @items = split(/:/,$match);
                    930:                     my ($uname,$udom,%userhash);
                    931:                     foreach my $entry (@items) {
                    932:                         my ($key,$value) = split(/=/,$entry);
                    933:                         $key = &unescape($key);
                    934:                         $value = &unescape($value);
                    935:                         $userhash{$key} = $value;
                    936:                         if ($key eq 'username') {
                    937:                             $uname = $value;
                    938:                         } elsif ($key eq 'domain') {
                    939:                             $udom = $value;
                    940:                         } 
                    941:                     }
                    942:                     $results{$uname.':'.$udom} = \%userhash;
                    943:                 }
                    944:             }
                    945:         }
                    946:     }
                    947:     return %results;
                    948: }
                    949: 
1.344     www       950: # --------------------------------------------------- Assign a key to a student
                    951: 
                    952: sub assign_access_key {
1.364     www       953: #
                    954: # a valid key looks like uname:udom#comments
                    955: # comments are being appended
                    956: #
1.498     www       957:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    958:     $kdom=
1.620     albertel  959:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       960:     $knum=
1.620     albertel  961:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       962:     $cdom=
1.620     albertel  963:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       964:     $cnum=
1.620     albertel  965:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    966:     $udom=$env{'user.name'} unless (defined($udom));
                    967:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       968:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       969:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  970:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       971:                                                   # assigned to this person
                    972:                                                   # - this should not happen,
1.345     www       973:                                                   # unless something went wrong
                    974:                                                   # the first time around
                    975: # ready to assign
1.364     www       976:         $logentry=$1.'; '.$logentry;
1.496     www       977:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       978:                                                  $kdom,$knum) eq 'ok') {
1.345     www       979: # key now belongs to user
1.346     www       980: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       981:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    982:                 &appenv('environment.'.$envkey => $ckey);
                    983:                 return 'ok';
                    984:             } else {
                    985:                 return 
                    986:   'error: Count not permanently assign key, will need to be re-entered later.';
                    987: 	    }
                    988:         } else {
                    989:             return 'error: Could not assign key, try again later.';
                    990:         }
1.364     www       991:     } elsif (!$existing{$ckey}) {
1.345     www       992: # the key does not exist
                    993: 	return 'error: The key does not exist';
                    994:     } else {
                    995: # the key is somebody else's
                    996: 	return 'error: The key is already in use';
                    997:     }
1.344     www       998: }
                    999: 
1.364     www      1000: # ------------------------------------------ put an additional comment on a key
                   1001: 
                   1002: sub comment_access_key {
                   1003: #
                   1004: # a valid key looks like uname:udom#comments
                   1005: # comments are being appended
                   1006: #
                   1007:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1008:     $cdom=
1.620     albertel 1009:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1010:     $cnum=
1.620     albertel 1011:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1012:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1013:     if ($existing{$ckey}) {
                   1014:         $existing{$ckey}.='; '.$logentry;
                   1015: # ready to assign
1.367     www      1016:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1017:                                                  $cdom,$cnum) eq 'ok') {
                   1018: 	    return 'ok';
                   1019:         } else {
                   1020: 	    return 'error: Count not store comment.';
                   1021:         }
                   1022:     } else {
                   1023: # the key does not exist
                   1024: 	return 'error: The key does not exist';
                   1025:     }
                   1026: }
                   1027: 
1.344     www      1028: # ------------------------------------------------------ Generate a set of keys
                   1029: 
                   1030: sub generate_access_keys {
1.364     www      1031:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1032:     $cdom=
1.620     albertel 1033:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1034:     $cnum=
1.620     albertel 1035:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1036:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1037:     unless (($cdom) && ($cnum)) { return 0; }
                   1038:     if ($number>10000) { return 0; }
                   1039:     sleep(2); # make sure don't get same seed twice
                   1040:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1041:     my $total=0;
                   1042:     for (my $i=1;$i<=$number;$i++) {
                   1043:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1044:                   sprintf("%lx",int(100000*rand)).'-'.
                   1045:                   sprintf("%lx",int(100000*rand));
                   1046:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1047:        $newkey=~s/0/h/g; # and also 0 and O
                   1048:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1049:        if ($existing{$newkey}) {
                   1050:            $i--;
                   1051:        } else {
1.364     www      1052: 	  if (&put('accesskeys',
                   1053:               { $newkey => '# generated '.localtime().
1.620     albertel 1054:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1055:                            '; '.$logentry },
                   1056: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1057:               $total++;
                   1058: 	  }
                   1059:        }
                   1060:     }
1.620     albertel 1061:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1062:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1063:     return $total;
                   1064: }
                   1065: 
                   1066: # ------------------------------------------------------- Validate an accesskey
                   1067: 
                   1068: sub validate_access_key {
                   1069:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1070:     $cdom=
1.620     albertel 1071:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1072:     $cnum=
1.620     albertel 1073:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1074:     $udom=$env{'user.domain'} unless (defined($udom));
                   1075:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1076:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1077:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1078: }
                   1079: 
                   1080: # ------------------------------------- Find the section of student in a course
1.652     albertel 1081: sub devalidate_getsection_cache {
                   1082:     my ($udom,$unam,$courseid)=@_;
                   1083:     my $hashid="$udom:$unam:$courseid";
                   1084:     &devalidate_cache_new('getsection',$hashid);
                   1085: }
1.298     matthew  1086: 
1.815     albertel 1087: sub courseid_to_courseurl {
                   1088:     my ($courseid) = @_;
                   1089:     #already url style courseid
                   1090:     return $courseid if ($courseid =~ m{^/});
                   1091: 
                   1092:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1093: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1094: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1095: 	return "/$cdom/$cnum";
                   1096:     }
                   1097: 
                   1098:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1099:     if (exists($courseinfo{'num'})) {
                   1100: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1101:     }
                   1102: 
                   1103:     return undef;
                   1104: }
                   1105: 
1.298     matthew  1106: sub getsection {
                   1107:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1108:     my $cachetime=1800;
1.551     albertel 1109: 
                   1110:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1111:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1112:     if (defined($cached)) { return $result; }
                   1113: 
1.298     matthew  1114:     my %Pending; 
                   1115:     my %Expired;
                   1116:     #
                   1117:     # Each role can either have not started yet (pending), be active, 
                   1118:     #    or have expired.
                   1119:     #
                   1120:     # If there is an active role, we are done.
                   1121:     #
                   1122:     # If there is more than one role which has not started yet, 
                   1123:     #     choose the one which will start sooner
                   1124:     # If there is one role which has not started yet, return it.
                   1125:     #
                   1126:     # If there is more than one expired role, choose the one which ended last.
                   1127:     # If there is a role which has expired, return it.
                   1128:     #
1.815     albertel 1129:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1130:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1131:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1132:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1133:         my $section=$1;
                   1134:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1135:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1136:         my $now=time;
1.548     albertel 1137:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1138:             $Expired{$end}=$section;
                   1139:             next;
                   1140:         }
1.548     albertel 1141:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1142:             $Pending{$start}=$section;
                   1143:             next;
                   1144:         }
1.599     albertel 1145:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1146:     }
                   1147:     #
                   1148:     # Presumedly there will be few matching roles from the above
                   1149:     # loop and the sorting time will be negligible.
                   1150:     if (scalar(keys(%Pending))) {
                   1151:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1152:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1153:     } 
                   1154:     if (scalar(keys(%Expired))) {
                   1155:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1156:         my $time = pop(@sorted);
1.599     albertel 1157:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1158:     }
1.599     albertel 1159:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1160: }
1.70      www      1161: 
1.599     albertel 1162: sub save_cache {
                   1163:     &purge_remembered();
1.722     albertel 1164:     #&Apache::loncommon::validate_page();
1.620     albertel 1165:     undef(%env);
1.780     albertel 1166:     undef($env_loaded);
1.599     albertel 1167: }
1.452     albertel 1168: 
1.599     albertel 1169: my $to_remember=-1;
                   1170: my %remembered;
                   1171: my %accessed;
                   1172: my $kicks=0;
                   1173: my $hits=0;
1.849     albertel 1174: sub make_key {
                   1175:     my ($name,$id) = @_;
1.872     albertel 1176:     if (length($id) > 65 
                   1177: 	&& length(&escape($id)) > 200) {
                   1178: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1179:     }
1.849     albertel 1180:     return &escape($name.':'.$id);
                   1181: }
                   1182: 
1.599     albertel 1183: sub devalidate_cache_new {
                   1184:     my ($name,$id,$debug) = @_;
                   1185:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1186:     $id=&make_key($name,$id);
1.599     albertel 1187:     $memcache->delete($id);
                   1188:     delete($remembered{$id});
                   1189:     delete($accessed{$id});
                   1190: }
                   1191: 
                   1192: sub is_cached_new {
                   1193:     my ($name,$id,$debug) = @_;
1.849     albertel 1194:     $id=&make_key($name,$id);
1.599     albertel 1195:     if (exists($remembered{$id})) {
                   1196: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1197: 	$accessed{$id}=[&gettimeofday()];
                   1198: 	$hits++;
                   1199: 	return ($remembered{$id},1);
                   1200:     }
                   1201:     my $value = $memcache->get($id);
                   1202:     if (!(defined($value))) {
                   1203: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1204: 	return (undef,undef);
1.416     albertel 1205:     }
1.599     albertel 1206:     if ($value eq '__undef__') {
                   1207: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1208: 	$value=undef;
                   1209:     }
                   1210:     &make_room($id,$value,$debug);
                   1211:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1212:     return ($value,1);
                   1213: }
                   1214: 
                   1215: sub do_cache_new {
                   1216:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1217:     $id=&make_key($name,$id);
1.599     albertel 1218:     my $setvalue=$value;
                   1219:     if (!defined($setvalue)) {
                   1220: 	$setvalue='__undef__';
                   1221:     }
1.623     albertel 1222:     if (!defined($time) ) {
                   1223: 	$time=600;
                   1224:     }
1.599     albertel 1225:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.872     albertel 1226:     if (!($memcache->set($id,$setvalue,$time))) {
                   1227: 	&logthis("caching of id -> $id  failed");
                   1228:     }
1.600     albertel 1229:     # need to make a copy of $value
                   1230:     #&make_room($id,$value,$debug);
1.599     albertel 1231:     return $value;
                   1232: }
                   1233: 
                   1234: sub make_room {
                   1235:     my ($id,$value,$debug)=@_;
                   1236:     $remembered{$id}=$value;
                   1237:     if ($to_remember<0) { return; }
                   1238:     $accessed{$id}=[&gettimeofday()];
                   1239:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1240:     my $to_kick;
                   1241:     my $max_time=0;
                   1242:     foreach my $other (keys(%accessed)) {
                   1243: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1244: 	    $to_kick=$other;
                   1245: 	    $max_time=&tv_interval($accessed{$other});
                   1246: 	}
                   1247:     }
                   1248:     delete($remembered{$to_kick});
                   1249:     delete($accessed{$to_kick});
                   1250:     $kicks++;
                   1251:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1252:     return;
                   1253: }
                   1254: 
1.599     albertel 1255: sub purge_remembered {
1.604     albertel 1256:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1257:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1258:     undef(%remembered);
                   1259:     undef(%accessed);
1.428     albertel 1260: }
1.70      www      1261: # ------------------------------------- Read an entry from a user's environment
                   1262: 
                   1263: sub userenvironment {
                   1264:     my ($udom,$unam,@what)=@_;
                   1265:     my %returnhash=();
                   1266:     my @answer=split(/\&/,
                   1267:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1268:                       &homeserver($unam,$udom)));
                   1269:     my $i;
                   1270:     for ($i=0;$i<=$#what;$i++) {
                   1271: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1272:     }
                   1273:     return %returnhash;
1.1       albertel 1274: }
                   1275: 
1.617     albertel 1276: # ---------------------------------------------------------- Get a studentphoto
                   1277: sub studentphoto {
                   1278:     my ($udom,$unam,$ext) = @_;
                   1279:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1280:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1281:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1282:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1283:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1284:             } else {
                   1285:                 my ($result,$perm_reqd)=
1.707     albertel 1286: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1287:                 if ($result eq 'ok') {
                   1288:                     if (!($perm_reqd eq 'yes')) {
                   1289:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1290:                     }
                   1291:                 }
                   1292:             }
                   1293:         }
                   1294:     } else {
                   1295:         my ($result,$perm_reqd) = 
1.707     albertel 1296: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1297:         if ($result eq 'ok') {
                   1298:             if (!($perm_reqd eq 'yes')) {
                   1299:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1300:             }
                   1301:         }
                   1302:     }
                   1303:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1304: }
                   1305: 
                   1306: sub retrievestudentphoto {
                   1307:     my ($udom,$unam,$ext,$type) = @_;
                   1308:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1309:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1310:     if ($ret eq 'ok') {
                   1311:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1312:         if ($type eq 'thumbnail') {
                   1313:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1314:         }
                   1315:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1316:         return $tokenurl;
                   1317:     } else {
                   1318:         if ($type eq 'thumbnail') {
                   1319:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1320:         } else { 
                   1321:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1322:         }
1.617     albertel 1323:     }
                   1324: }
                   1325: 
1.263     www      1326: # -------------------------------------------------------------------- New chat
                   1327: 
                   1328: sub chatsend {
1.724     raeburn  1329:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1330:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1331:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1332:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1333:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1334: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1335: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1336: }
                   1337: 
                   1338: # ------------------------------------------ Find current version of a resource
                   1339: 
                   1340: sub getversion {
                   1341:     my $fname=&clutter(shift);
                   1342:     unless ($fname=~/^\/res\//) { return -1; }
                   1343:     return &currentversion(&filelocation('',$fname));
                   1344: }
                   1345: 
                   1346: sub currentversion {
                   1347:     my $fname=shift;
1.599     albertel 1348:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1349:     if (defined($cached)) { return $result; }
1.292     www      1350:     my $author=$fname;
                   1351:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1352:     my ($udom,$uname)=split(/\//,$author);
                   1353:     my $home=homeserver($uname,$udom);
                   1354:     if ($home eq 'no_host') { 
                   1355:         return -1; 
                   1356:     }
                   1357:     my $answer=reply("currentversion:$fname",$home);
                   1358:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1359: 	return -1;
                   1360:     }
1.599     albertel 1361:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1362: }
                   1363: 
1.1       albertel 1364: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1365: 
1.1       albertel 1366: sub subscribe {
                   1367:     my $fname=shift;
1.761     raeburn  1368:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1369:     $fname=~s/[\n\r]//g;
1.1       albertel 1370:     my $author=$fname;
                   1371:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1372:     my ($udom,$uname)=split(/\//,$author);
                   1373:     my $home=homeserver($uname,$udom);
1.335     albertel 1374:     if ($home eq 'no_host') {
                   1375:         return 'not_found';
1.1       albertel 1376:     }
                   1377:     my $answer=reply("sub:$fname",$home);
1.64      www      1378:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1379: 	$answer.=' by '.$home;
                   1380:     }
1.1       albertel 1381:     return $answer;
                   1382: }
                   1383:     
1.8       www      1384: # -------------------------------------------------------------- Replicate file
                   1385: 
                   1386: sub repcopy {
                   1387:     my $filename=shift;
1.23      www      1388:     $filename=~s/\/+/\//g;
1.607     raeburn  1389:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1390:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1391:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1392: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1393: 	return &repcopy_userfile($filename);
                   1394:     }
1.532     albertel 1395:     $filename=~s/[\n\r]//g;
1.8       www      1396:     my $transname="$filename.in.transfer";
1.828     www      1397: # FIXME: this should flock
1.607     raeburn  1398:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1399:     my $remoteurl=subscribe($filename);
1.64      www      1400:     if ($remoteurl =~ /^con_lost by/) {
                   1401: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1402:            return 'unavailable';
1.8       www      1403:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1404: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1405: 	   return 'not_found';
1.64      www      1406:     } elsif ($remoteurl =~ /^rejected by/) {
                   1407: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1408:            return 'forbidden';
1.20      www      1409:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1410:            return 'ok';
1.8       www      1411:     } else {
1.290     www      1412:         my $author=$filename;
                   1413:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1414:         my ($udom,$uname)=split(/\//,$author);
                   1415:         my $home=homeserver($uname,$udom);
                   1416:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1417:            my @parts=split(/\//,$filename);
                   1418:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1419:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1420:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1421: 	       return 'bad_request';
1.8       www      1422:            }
                   1423:            my $count;
                   1424:            for ($count=5;$count<$#parts;$count++) {
                   1425:                $path.="/$parts[$count]";
                   1426:                if ((-e $path)!=1) {
                   1427: 		   mkdir($path,0777);
                   1428:                }
                   1429:            }
                   1430:            my $ua=new LWP::UserAgent;
                   1431:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1432:            my $response=$ua->request($request,$transname);
                   1433:            if ($response->is_error()) {
                   1434: 	       unlink($transname);
                   1435:                my $message=$response->status_line;
1.672     albertel 1436:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1437:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1438:                return 'unavailable';
1.8       www      1439:            } else {
1.16      www      1440: 	       if ($remoteurl!~/\.meta$/) {
                   1441:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1442:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1443:                   if ($mresponse->is_error()) {
                   1444: 		      unlink($filename.'.meta');
                   1445:                       &logthis(
1.672     albertel 1446:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1447:                   }
                   1448: 	       }
1.8       www      1449:                rename($transname,$filename);
1.607     raeburn  1450:                return 'ok';
1.8       www      1451:            }
1.290     www      1452:        }
1.8       www      1453:     }
1.330     www      1454: }
                   1455: 
                   1456: # ------------------------------------------------ Get server side include body
                   1457: sub ssi_body {
1.381     albertel 1458:     my ($filelink,%form)=@_;
1.606     matthew  1459:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1460:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1461:     }
1.330     www      1462:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1463:                                      &ssi($filelink,%form));
1.778     albertel 1464:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1465:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1466:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1467:     return $output;
1.8       www      1468: }
                   1469: 
1.15      www      1470: # --------------------------------------------------------- Server Side Include
                   1471: 
1.782     albertel 1472: sub absolute_url {
                   1473:     my ($host_name) = @_;
                   1474:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1475:     if ($host_name eq '') {
                   1476: 	$host_name = $ENV{'SERVER_NAME'};
                   1477:     }
                   1478:     return $protocol.$host_name;
                   1479: }
                   1480: 
1.15      www      1481: sub ssi {
                   1482: 
1.23      www      1483:     my ($fn,%form)=@_;
1.15      www      1484: 
                   1485:     my $ua=new LWP::UserAgent;
1.23      www      1486:     
                   1487:     my $request;
1.711     albertel 1488: 
                   1489:     $form{'no_update_last_known'}=1;
1.895     albertel 1490:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1491:     if (%form) {
1.782     albertel 1492:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1493:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1494:     } else {
1.782     albertel 1495:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1496:     }
                   1497: 
1.15      www      1498:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1499:     my $response=$ua->request($request);
                   1500: 
1.324     www      1501:     return $response->content;
                   1502: }
                   1503: 
                   1504: sub externalssi {
                   1505:     my ($url)=@_;
                   1506:     my $ua=new LWP::UserAgent;
                   1507:     my $request=new HTTP::Request('GET',$url);
                   1508:     my $response=$ua->request($request);
1.15      www      1509:     return $response->content;
                   1510: }
1.254     www      1511: 
1.492     albertel 1512: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1513: 
                   1514: sub allowuploaded {
                   1515:     my ($srcurl,$url)=@_;
                   1516:     $url=&clutter(&declutter($url));
                   1517:     my $dir=$url;
                   1518:     $dir=~s/\/[^\/]+$//;
                   1519:     my %httpref=();
                   1520:     my $httpurl=&hreflocation('',$url);
                   1521:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1522:     &Apache::lonnet::appenv(%httpref);
1.254     www      1523: }
1.477     raeburn  1524: 
1.478     albertel 1525: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1526: # input: action, courseID, current domain, intended
1.637     raeburn  1527: #        path to file, source of file, instruction to parse file for objects,
                   1528: #        ref to hash for embedded objects,
                   1529: #        ref to hash for codebase of java objects.
                   1530: #
1.485     raeburn  1531: # output: url to file (if action was uploaddoc), 
                   1532: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1533: #
1.478     albertel 1534: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1535: # course.
1.477     raeburn  1536: #
1.478     albertel 1537: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1538: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1539: #          course's home server.
1.477     raeburn  1540: #
1.478     albertel 1541: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1542: #          be copied from $source (current location) to 
                   1543: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1544: #         and will then be copied to
                   1545: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1546: #         course's home server.
1.485     raeburn  1547: #
1.481     raeburn  1548: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1549: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1550: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1551: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1552: #         in course's home server.
1.637     raeburn  1553: #
1.477     raeburn  1554: 
                   1555: sub process_coursefile {
1.638     albertel 1556:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1557:     my $fetchresult;
1.638     albertel 1558:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1559:     if ($action eq 'propagate') {
1.638     albertel 1560:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1561: 			     $home);
1.481     raeburn  1562:     } else {
1.477     raeburn  1563:         my $fpath = '';
                   1564:         my $fname = $file;
1.478     albertel 1565:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1566:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1567:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1568:         if ($action eq 'copy') {
                   1569:             if ($source eq '') {
                   1570:                 $fetchresult = 'no source file';
                   1571:                 return $fetchresult;
                   1572:             } else {
                   1573:                 my $destination = $filepath.'/'.$fname;
                   1574:                 rename($source,$destination);
                   1575:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1576:                                  $home);
1.481     raeburn  1577:             }
                   1578:         } elsif ($action eq 'uploaddoc') {
                   1579:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1580:             print $fh $env{'form.'.$source};
1.481     raeburn  1581:             close($fh);
1.637     raeburn  1582:             if ($parser eq 'parse') {
                   1583:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1584:                 unless ($parse_result eq 'ok') {
                   1585:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1586:                 }
                   1587:             }
1.477     raeburn  1588:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1589:                                  $home);
1.481     raeburn  1590:             if ($fetchresult eq 'ok') {
                   1591:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1592:             } else {
                   1593:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1594:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1595:                 return '/adm/notfound.html';
                   1596:             }
1.477     raeburn  1597:         }
                   1598:     }
1.485     raeburn  1599:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1600:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1601:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1602:     }
                   1603:     return $fetchresult;
                   1604: }
                   1605: 
1.637     raeburn  1606: sub build_filepath {
                   1607:     my ($fpath) = @_;
                   1608:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1609:     unless ($fpath eq '') {
                   1610:         my @parts=split('/',$fpath);
                   1611:         foreach my $part (@parts) {
                   1612:             $filepath.= '/'.$part;
                   1613:             if ((-e $filepath)!=1) {
                   1614:                 mkdir($filepath,0777);
                   1615:             }
                   1616:         }
                   1617:     }
                   1618:     return $filepath;
                   1619: }
                   1620: 
                   1621: sub store_edited_file {
1.638     albertel 1622:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1623:     my $file = $primary_url;
                   1624:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1625:     my $fpath = '';
                   1626:     my $fname = $file;
                   1627:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1628:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1629:     my $filepath = &build_filepath($fpath);
                   1630:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1631:     print $fh $content;
                   1632:     close($fh);
1.638     albertel 1633:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1634:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1635: 			  $home);
1.637     raeburn  1636:     if ($$fetchresult eq 'ok') {
                   1637:         return '/uploaded/'.$fpath.'/'.$fname;
                   1638:     } else {
1.638     albertel 1639:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1640: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1641:         return '/adm/notfound.html';
                   1642:     }
                   1643: }
                   1644: 
1.531     albertel 1645: sub clean_filename {
1.831     albertel 1646:     my ($fname,$args)=@_;
1.315     www      1647: # Replace Windows backslashes by forward slashes
1.257     www      1648:     $fname=~s/\\/\//g;
1.831     albertel 1649:     if (!$args->{'keep_path'}) {
                   1650:         # Get rid of everything but the actual filename
                   1651: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1652:     }
1.315     www      1653: # Replace spaces by underscores
                   1654:     $fname=~s/\s+/\_/g;
                   1655: # Replace all other weird characters by nothing
1.831     albertel 1656:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1657: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1658: # numbers
                   1659:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1660:     return $fname;
                   1661: }
                   1662: 
1.608     albertel 1663: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1664: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1665: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1666: #        $coursedoc - if true up to the current course
                   1667: #                     if false
                   1668: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1669: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1670: #        $allfiles - reference to hash for embedded objects
                   1671: #        $codebase - reference to hash for codebase of java objects
                   1672: #        $desuname - username for permanent storage of uploaded file
                   1673: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1674: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1675: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1676: # 
1.686     albertel 1677: # output: url of file in userspace, or error: <message> 
                   1678: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1679: 
                   1680: 
1.531     albertel 1681: sub userfileupload {
1.860     raeburn  1682:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1683:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1684:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1685:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1686:     $fname=&clean_filename($fname);
1.315     www      1687: # See if there is anything left
1.257     www      1688:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1689:     chop($env{'form.'.$formname});
1.523     raeburn  1690:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1691:         my $now = time;
                   1692:         my $filepath = 'tmp/helprequests/'.$now;
                   1693:         my @parts=split(/\//,$filepath);
                   1694:         my $fullpath = $perlvar{'lonDaemons'};
                   1695:         for (my $i=0;$i<@parts;$i++) {
                   1696:             $fullpath .= '/'.$parts[$i];
                   1697:             if ((-e $fullpath)!=1) {
                   1698:                 mkdir($fullpath,0777);
                   1699:             }
                   1700:         }
                   1701:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1702:         print $fh $env{'form.'.$formname};
1.523     raeburn  1703:         close($fh);
1.741     raeburn  1704:         return $fullpath.'/'.$fname;
                   1705:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1706:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1707:                        '_'.$env{'user.domain'}.'/pending';
                   1708:         my @parts=split(/\//,$filepath);
                   1709:         my $fullpath = $perlvar{'lonDaemons'};
                   1710:         for (my $i=0;$i<@parts;$i++) {
                   1711:             $fullpath .= '/'.$parts[$i];
                   1712:             if ((-e $fullpath)!=1) {
                   1713:                 mkdir($fullpath,0777);
                   1714:             }
                   1715:         }
                   1716:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1717:         print $fh $env{'form.'.$formname};
                   1718:         close($fh);
                   1719:         return $fullpath.'/'.$fname;
1.523     raeburn  1720:     }
1.719     banghart 1721:     
1.258     www      1722: # Create the directory if not present
1.493     albertel 1723:     $fname="$subdir/$fname";
1.259     www      1724:     if ($coursedoc) {
1.638     albertel 1725: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1726: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1727:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1728:             return &finishuserfileupload($docuname,$docudom,
                   1729: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1730: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1731:         } else {
1.620     albertel 1732:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1733:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1734: 				       $fname,$formname,$parser,
                   1735: 				       $allfiles,$codebase);
1.481     raeburn  1736:         }
1.719     banghart 1737:     } elsif (defined($destuname)) {
                   1738:         my $docuname=$destuname;
                   1739:         my $docudom=$destudom;
1.860     raeburn  1740: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1741: 				     $parser,$allfiles,$codebase,
                   1742:                                      $thumbwidth,$thumbheight);
1.719     banghart 1743:         
1.259     www      1744:     } else {
1.638     albertel 1745:         my $docuname=$env{'user.name'};
                   1746:         my $docudom=$env{'user.domain'};
1.714     raeburn  1747:         if (exists($env{'form.group'})) {
                   1748:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1749:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1750:         }
1.860     raeburn  1751: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1752: 				     $parser,$allfiles,$codebase,
                   1753:                                      $thumbwidth,$thumbheight);
1.259     www      1754:     }
1.271     www      1755: }
                   1756: 
                   1757: sub finishuserfileupload {
1.860     raeburn  1758:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1759:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1760:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1761:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1762:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1763:     $file=$fname;
                   1764:     if ($fname=~m|/|) {
                   1765:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1766: 	$path.=$fnamepath.'/';
                   1767:     }
1.259     www      1768:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1769:     my $count;
                   1770:     for ($count=4;$count<=$#parts;$count++) {
                   1771:         $filepath.="/$parts[$count]";
                   1772:         if ((-e $filepath)!=1) {
                   1773: 	    mkdir($filepath,0777);
                   1774:         }
                   1775:     }
                   1776: # Save the file
                   1777:     {
1.701     albertel 1778: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1779: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1780: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1781: 	    return '/adm/notfound.html';
                   1782: 	}
                   1783: 	if (!print FH ($env{'form.'.$formname})) {
                   1784: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1785: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1786: 	    return '/adm/notfound.html';
                   1787: 	}
1.570     albertel 1788: 	close(FH);
1.258     www      1789:     }
1.637     raeburn  1790:     if ($parser eq 'parse') {
1.638     albertel 1791:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1792: 						   $codebase);
1.637     raeburn  1793:         unless ($parse_result eq 'ok') {
1.638     albertel 1794:             &logthis('Failed to parse '.$filepath.$file.
                   1795: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1796:         }
                   1797:     }
1.860     raeburn  1798:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1799:         my $input = $filepath.'/'.$file;
                   1800:         my $output = $filepath.'/'.'tn-'.$file;
                   1801:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1802:         system("convert -sample $thumbsize $input $output");
                   1803:         if (-e $filepath.'/'.'tn-'.$file) {
                   1804:             $fetchthumb  = 1; 
                   1805:         }
                   1806:     }
1.858     raeburn  1807:  
1.259     www      1808: # Notify homeserver to grep it
                   1809: #
1.638     albertel 1810:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1811:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1812:     if ($fetchresult eq 'ok') {
1.860     raeburn  1813:         if ($fetchthumb) {
                   1814:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1815:             if ($thumbresult ne 'ok') {
                   1816:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1817:                          $docuhome.': '.$thumbresult);
                   1818:             }
                   1819:         }
1.259     www      1820: #
1.258     www      1821: # Return the URL to it
1.494     albertel 1822:         return '/uploaded/'.$path.$file;
1.263     www      1823:     } else {
1.494     albertel 1824:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1825: 		 ': '.$fetchresult);
1.263     www      1826:         return '/adm/notfound.html';
1.858     raeburn  1827:     }
1.493     albertel 1828: }
                   1829: 
1.637     raeburn  1830: sub extract_embedded_items {
1.648     raeburn  1831:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1832:     my @state = ();
                   1833:     my %javafiles = (
                   1834:                       codebase => '',
                   1835:                       code => '',
                   1836:                       archive => ''
                   1837:                     );
                   1838:     my %mediafiles = (
                   1839:                       src => '',
                   1840:                       movie => '',
                   1841:                      );
1.648     raeburn  1842:     my $p;
                   1843:     if ($content) {
                   1844:         $p = HTML::LCParser->new($content);
                   1845:     } else {
                   1846:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1847:     }
1.641     albertel 1848:     while (my $t=$p->get_token()) {
1.640     albertel 1849: 	if ($t->[0] eq 'S') {
                   1850: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1851: 	    push(@state, $tagname);
1.648     raeburn  1852:             if (lc($tagname) eq 'allow') {
                   1853:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1854:             }
1.640     albertel 1855: 	    if (lc($tagname) eq 'img') {
                   1856: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1857: 	    }
1.886     albertel 1858: 	    if (lc($tagname) eq 'a') {
                   1859: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1860: 	    }
1.645     raeburn  1861:             if (lc($tagname) eq 'script') {
                   1862:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1863:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1864:                 } else {
                   1865:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1866:                 }
                   1867:             }
                   1868:             if (lc($tagname) eq 'link') {
                   1869:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1870:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1871:                 }
                   1872:             }
1.640     albertel 1873: 	    if (lc($tagname) eq 'object' ||
                   1874: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1875: 		foreach my $item (keys(%javafiles)) {
                   1876: 		    $javafiles{$item} = '';
                   1877: 		}
                   1878: 	    }
                   1879: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1880: 		my $name = lc($attr->{'name'});
                   1881: 		foreach my $item (keys(%javafiles)) {
                   1882: 		    if ($name eq $item) {
                   1883: 			$javafiles{$item} = $attr->{'value'};
                   1884: 			last;
                   1885: 		    }
                   1886: 		}
                   1887: 		foreach my $item (keys(%mediafiles)) {
                   1888: 		    if ($name eq $item) {
                   1889: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1890: 			last;
                   1891: 		    }
                   1892: 		}
                   1893: 	    }
                   1894: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1895: 		foreach my $item (keys(%javafiles)) {
                   1896: 		    if ($attr->{$item}) {
                   1897: 			$javafiles{$item} = $attr->{$item};
                   1898: 			last;
                   1899: 		    }
                   1900: 		}
                   1901: 		foreach my $item (keys(%mediafiles)) {
                   1902: 		    if ($attr->{$item}) {
                   1903: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1904: 			last;
                   1905: 		    }
                   1906: 		}
                   1907: 	    }
                   1908: 	} elsif ($t->[0] eq 'E') {
                   1909: 	    my ($tagname) = ($t->[1]);
                   1910: 	    if ($javafiles{'codebase'} ne '') {
                   1911: 		$javafiles{'codebase'} .= '/';
                   1912: 	    }  
                   1913: 	    if (lc($tagname) eq 'applet' ||
                   1914: 		lc($tagname) eq 'object' ||
                   1915: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1916: 		) {
                   1917: 		foreach my $item (keys(%javafiles)) {
                   1918: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1919: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1920: 			&add_filetype($allfiles,$file,$item);
                   1921: 		    }
                   1922: 		}
                   1923: 	    } 
                   1924: 	    pop @state;
                   1925: 	}
                   1926:     }
1.637     raeburn  1927:     return 'ok';
                   1928: }
                   1929: 
1.639     albertel 1930: sub add_filetype {
                   1931:     my ($allfiles,$file,$type)=@_;
                   1932:     if (exists($allfiles->{$file})) {
                   1933: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1934: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1935: 	}
                   1936:     } else {
                   1937: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1938:     }
                   1939: }
                   1940: 
1.493     albertel 1941: sub removeuploadedurl {
                   1942:     my ($url)=@_;
                   1943:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1944:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1945: }
                   1946: 
                   1947: sub removeuserfile {
                   1948:     my ($docuname,$docudom,$fname)=@_;
                   1949:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1950:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1951:     if ($result eq 'ok') {
                   1952:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1953:             my $metafile = $fname.'.meta';
                   1954:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1955: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1956:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1957:             my $sqlresult = 
1.823     albertel 1958:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1959:                                         'portfolio_metadata',$group,
                   1960:                                         'delete');
1.798     raeburn  1961:         }
                   1962:     }
                   1963:     return $result;
1.257     www      1964: }
1.15      www      1965: 
1.530     albertel 1966: sub mkdiruserfile {
                   1967:     my ($docuname,$docudom,$dir)=@_;
                   1968:     my $home=&homeserver($docuname,$docudom);
                   1969:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1970: }
                   1971: 
1.531     albertel 1972: sub renameuserfile {
                   1973:     my ($docuname,$docudom,$old,$new)=@_;
                   1974:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1975:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1976:                         &escape("$old").':'.&escape("$new"),$home);
                   1977:     if ($result eq 'ok') {
                   1978:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1979:             my $oldmeta = $old.'.meta';
                   1980:             my $newmeta = $new.'.meta';
                   1981:             my $metaresult = 
                   1982:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1983: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1984:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1985:             my $sqlresult = 
1.823     albertel 1986:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1987:                                         'portfolio_metadata',$group,
                   1988:                                         'delete');
1.798     raeburn  1989:         }
                   1990:     }
                   1991:     return $result;
1.531     albertel 1992: }
                   1993: 
1.14      www      1994: # ------------------------------------------------------------------------- Log
                   1995: 
                   1996: sub log {
                   1997:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1998:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1999: }
                   2000: 
                   2001: # ------------------------------------------------------------------ Course Log
1.352     www      2002: #
                   2003: # This routine flushes several buffers of non-mission-critical nature
                   2004: #
1.157     www      2005: 
                   2006: sub flushcourselogs {
1.352     www      2007:     &logthis('Flushing log buffers');
                   2008: #
                   2009: # course logs
                   2010: # This is a log of all transactions in a course, which can be used
                   2011: # for data mining purposes
                   2012: #
                   2013: # It also collects the courseid database, which lists last transaction
                   2014: # times and course titles for all courseids
                   2015: #
                   2016:     my %courseidbuffer=();
1.800     albertel 2017:     foreach my $crsid (keys %courselogs) {
1.352     www      2018:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2019: 		          &escape($courselogs{$crsid}),
                   2020: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2021: 	    delete $courselogs{$crsid};
                   2022:         } else {
                   2023:             &logthis('Failed to flush log buffer for '.$crsid);
                   2024:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2025:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2026:                         " exceeded maximum size, deleting.</font>");
                   2027:                delete $courselogs{$crsid};
                   2028:             }
1.352     www      2029:         }
                   2030:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2031:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2032: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2033:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2034:         } else {
                   2035:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2036: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2037:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2038:         }
1.191     harris41 2039:     }
1.352     www      2040: #
                   2041: # Write course id database (reverse lookup) to homeserver of courses 
                   2042: # Is used in pickcourse
                   2043: #
1.840     albertel 2044:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2045:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2046: 		     $crs_home);
1.352     www      2047:     }
                   2048: #
                   2049: # File accesses
                   2050: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2051: #
1.449     matthew  2052:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2053:         if ($entry =~ /___count$/) {
                   2054:             my ($dom,$name);
1.807     albertel 2055:             ($dom,$name,undef)=
1.811     albertel 2056: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2057:             if (! defined($dom) || $dom eq '' || 
                   2058:                 ! defined($name) || $name eq '') {
1.620     albertel 2059:                 my $cid = $env{'request.course.id'};
                   2060:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2061:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2062:             }
1.450     matthew  2063:             my $value = $accesshash{$entry};
                   2064:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2065:             my %temphash=($url => $value);
1.449     matthew  2066:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2067:             if ($result eq 'ok') {
                   2068:                 delete $accesshash{$entry};
                   2069:             } elsif ($result eq 'unknown_cmd') {
                   2070:                 # Target server has old code running on it.
1.450     matthew  2071:                 my %temphash=($entry => $value);
1.449     matthew  2072:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2073:                     delete $accesshash{$entry};
                   2074:                 }
                   2075:             }
                   2076:         } else {
1.811     albertel 2077:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2078:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2079:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2080:                 delete $accesshash{$entry};
                   2081:             }
1.185     www      2082:         }
1.191     harris41 2083:     }
1.352     www      2084: #
                   2085: # Roles
                   2086: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2087: #
1.800     albertel 2088:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2089:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2090: 	    split(/\:/,$entry);
                   2091:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2092:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2093:                 $rudom,$runame) eq 'ok') {
                   2094: 	    delete $userrolehash{$entry};
                   2095:         }
                   2096:     }
1.662     raeburn  2097: #
                   2098: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2099: #
                   2100:     my %domrolebuffer = ();
                   2101:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2102:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2103:         if ($domrolebuffer{$rudom}) {
                   2104:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2105:                       '='.&escape($domainrolehash{$entry});
                   2106:         } else {
                   2107:             $domrolebuffer{$rudom}.=&escape($entry).
                   2108:                       '='.&escape($domainrolehash{$entry});
                   2109:         }
                   2110:         delete $domainrolehash{$entry};
                   2111:     }
                   2112:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2113: 	my %servers = &get_servers($dom,'library');
                   2114: 	foreach my $tryserver (keys(%servers)) {
                   2115: 	    unless (&reply('domroleput:'.$dom.':'.
                   2116: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2117: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2118: 	    }
1.662     raeburn  2119:         }
                   2120:     }
1.186     www      2121:     $dumpcount++;
1.157     www      2122: }
                   2123: 
                   2124: sub courselog {
                   2125:     my $what=shift;
1.158     www      2126:     $what=time.':'.$what;
1.620     albertel 2127:     unless ($env{'request.course.id'}) { return ''; }
                   2128:     $coursedombuf{$env{'request.course.id'}}=
                   2129:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2130:     $coursenumbuf{$env{'request.course.id'}}=
                   2131:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2132:     $coursehombuf{$env{'request.course.id'}}=
                   2133:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2134:     $coursedescrbuf{$env{'request.course.id'}}=
                   2135:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2136:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2137:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2138:     $courseownerbuf{$env{'request.course.id'}}=
                   2139:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2140:     $coursetypebuf{$env{'request.course.id'}}=
                   2141:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2142:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2143: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2144:     } else {
1.620     albertel 2145: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2146:     }
1.620     albertel 2147:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2148: 	&flushcourselogs();
                   2149:     }
1.158     www      2150: }
                   2151: 
                   2152: sub courseacclog {
                   2153:     my $fnsymb=shift;
1.620     albertel 2154:     unless ($env{'request.course.id'}) { return ''; }
                   2155:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2156:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2157:         $what.=':POST';
1.583     matthew  2158:         # FIXME: Probably ought to escape things....
1.800     albertel 2159: 	foreach my $key (keys(%env)) {
                   2160:             if ($key=~/^form\.(.*)/) {
                   2161: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2162:             }
1.191     harris41 2163:         }
1.583     matthew  2164:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2165:         # FIXME: We should not be depending on a form parameter that someone
                   2166:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2167:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2168:             $what.= ':POST';
                   2169:             # FIXME: Probably ought to escape things....
                   2170:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2171:                                  'crsdiscuss') {
1.620     albertel 2172:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2173:             }
                   2174:         }
1.158     www      2175:     }
                   2176:     &courselog($what);
1.149     www      2177: }
                   2178: 
1.185     www      2179: sub countacc {
                   2180:     my $url=&declutter(shift);
1.458     matthew  2181:     return if (! defined($url) || $url eq '');
1.620     albertel 2182:     unless ($env{'request.course.id'}) { return ''; }
                   2183:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2184:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2185:     $accesshash{$key}++;
1.185     www      2186: }
1.349     www      2187: 
1.361     www      2188: sub linklog {
                   2189:     my ($from,$to)=@_;
                   2190:     $from=&declutter($from);
                   2191:     $to=&declutter($to);
                   2192:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2193:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2194: }
                   2195:   
1.349     www      2196: sub userrolelog {
                   2197:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2198:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2199:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2200:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2201:         ($trole=~/^ta/)) {
1.350     www      2202:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2203:        $userrolehash
                   2204:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2205:                     =$tend.':'.$tstart;
1.662     raeburn  2206:     }
1.898     albertel 2207:     if (($env{'request.role'} =~ /dc\./) &&
                   2208: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2209: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2210: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2211:        $userrolehash
                   2212:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2213:                     =$tend.':'.$tstart;
                   2214:     }
1.662     raeburn  2215:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2216:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2217:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2218:         ($trole=~/^sc/)) {
                   2219:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2220:        $domainrolehash
                   2221:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2222:                     = $tend.':'.$tstart;
                   2223:     }
1.351     www      2224: }
                   2225: 
                   2226: sub get_course_adv_roles {
                   2227:     my $cid=shift;
1.620     albertel 2228:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2229:     my %coursehash=&coursedescription($cid);
1.470     www      2230:     my %nothide=();
1.800     albertel 2231:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2232: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2233:     }
1.351     www      2234:     my %returnhash=();
                   2235:     my %dumphash=
                   2236:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2237:     my $now=time;
1.800     albertel 2238:     foreach my $entry (keys %dumphash) {
                   2239: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2240:         if (($tstart) && ($tstart<0)) { next; }
                   2241:         if (($tend) && ($tend<$now)) { next; }
                   2242:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2243:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2244: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2245: 	if ((&privileged($username,$domain)) && 
                   2246: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2247: 	if ($role eq 'cr') { next; }
1.351     www      2248:         my $key=&plaintext($role);
                   2249:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2250:         if ($returnhash{$key}) {
                   2251: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2252:         } else {
                   2253:             $returnhash{$key}=$username.':'.$domain;
                   2254:         }
1.400     www      2255:      }
                   2256:     return %returnhash;
                   2257: }
                   2258: 
                   2259: sub get_my_roles {
1.858     raeburn  2260:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2261:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2262:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2263:     my %dumphash;
                   2264:     if ($context eq 'userroles') { 
                   2265:         %dumphash = &dump('roles',$udom,$uname);
                   2266:     } else {
                   2267:         %dumphash=
1.400     www      2268:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2269:     }
1.400     www      2270:     my %returnhash=();
                   2271:     my $now=time;
1.800     albertel 2272:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2273:         my ($role,$tend,$tstart);
                   2274:         if ($context eq 'userroles') {
                   2275: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2276:         } else {
                   2277:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2278:         }
1.400     www      2279:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2280:         my $status = 'active';
                   2281:         if (($tend) && ($tend<$now)) {
                   2282:             $status = 'previous';
                   2283:         } 
                   2284:         if (($tstart) && ($now<$tstart)) {
                   2285:             $status = 'future';
                   2286:         }
                   2287:         if (ref($types) eq 'ARRAY') {
                   2288:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2289:                 next;
                   2290:             } 
                   2291:         } else {
                   2292:             if ($status ne 'active') {
                   2293:                 next;
                   2294:             }
                   2295:         }
1.867     raeburn  2296:         my ($rolecode,$username,$domain,$section,$area);
                   2297:         if ($context eq 'userroles') {
                   2298:             ($area,$rolecode) = split(/_/,$entry);
                   2299:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2300:         } else {
                   2301:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2302:         }
1.832     raeburn  2303:         if (ref($roledoms) eq 'ARRAY') {
                   2304:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2305:                 next;
                   2306:             }
                   2307:         }
                   2308:         if (ref($roles) eq 'ARRAY') {
                   2309:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2310:                 next;
                   2311:             }
1.867     raeburn  2312:         }
1.400     www      2313: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2314:     }
1.373     www      2315:     return %returnhash;
1.399     www      2316: }
                   2317: 
                   2318: # ----------------------------------------------------- Frontpage Announcements
                   2319: #
                   2320: #
                   2321: 
                   2322: sub postannounce {
                   2323:     my ($server,$text)=@_;
1.844     albertel 2324:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2325:     unless ($text=~/\w/) { $text=''; }
                   2326:     return &reply('setannounce:'.&escape($text),$server);
                   2327: }
                   2328: 
                   2329: sub getannounce {
1.448     albertel 2330: 
                   2331:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2332: 	my $announcement='';
1.800     albertel 2333: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2334: 	close($fh);
1.399     www      2335: 	if ($announcement=~/\w/) { 
                   2336: 	    return 
                   2337:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2338:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2339: 	} else {
                   2340: 	    return '';
                   2341: 	}
                   2342:     } else {
                   2343: 	return '';
                   2344:     }
1.351     www      2345: }
1.353     www      2346: 
                   2347: # ---------------------------------------------------------- Course ID routines
                   2348: # Deal with domain's nohist_courseid.db files
                   2349: #
                   2350: 
                   2351: sub courseidput {
                   2352:     my ($domain,$what,$coursehome)=@_;
                   2353:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2354: }
                   2355: 
                   2356: sub courseiddump {
1.791     raeburn  2357:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2358:     my %returnhash=();
1.355     www      2359:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2360:     my %libserv = &all_library();
                   2361:     foreach my $tryserver (keys(%libserv)) {
                   2362:         if ( (  $hostidflag == 1 
                   2363: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2364: 	     || (!defined($hostidflag)) ) {
                   2365: 
                   2366: 	    if ($domfilter eq ''
                   2367: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2368: 	        foreach my $line (
1.844     albertel 2369:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2370: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2371:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2372:                                $tryserver))) {
1.800     albertel 2373: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2374:                     if (($key) && ($value)) {
1.516     raeburn  2375: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2376:                     }
1.353     www      2377:                 }
                   2378:             }
                   2379:         }
                   2380:     }
                   2381:     return %returnhash;
                   2382: }
                   2383: 
1.658     raeburn  2384: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2385: 
                   2386: sub dcmailput {
1.685     raeburn  2387:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2388:     my $status = &Apache::lonnet::critical(
1.740     www      2389:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2390:        &escape($message),$server);
1.662     raeburn  2391:     return $status;
                   2392: }
                   2393: 
1.658     raeburn  2394: sub dcmaildump {
                   2395:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2396:     my %returnhash=();
1.846     albertel 2397: 
                   2398:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2399:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2400:                                                          &escape($enddate).':';
                   2401: 	my @esc_senders=map { &escape($_)} @$senders;
                   2402: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2403: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2404:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2405:             if (($key) && ($value)) {
                   2406:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2407:             }
                   2408:         }
                   2409:     }
                   2410:     return %returnhash;
                   2411: }
1.662     raeburn  2412: # ---------------------------------------------------------- Domain roles
                   2413: 
                   2414: sub get_domain_roles {
                   2415:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2416:     if (undef($startdate) || $startdate eq '') {
                   2417:         $startdate = '.';
                   2418:     }
                   2419:     if (undef($enddate) || $enddate eq '') {
                   2420:         $enddate = '.';
                   2421:     }
                   2422:     my $rolelist = join(':',@{$roles});
                   2423:     my %personnel = ();
1.841     albertel 2424: 
                   2425:     my %servers = &get_servers($dom,'library');
                   2426:     foreach my $tryserver (keys(%servers)) {
                   2427: 	%{$personnel{$tryserver}}=();
                   2428: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2429: 					    &escape($startdate).':'.
                   2430: 					    &escape($enddate).':'.
                   2431: 					    &escape($rolelist), $tryserver))) {
                   2432: 	    my ($key,$value) = split(/\=/,$line,2);
                   2433: 	    if (($key) && ($value)) {
                   2434: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2435: 	    }
                   2436: 	}
1.662     raeburn  2437:     }
                   2438:     return %personnel;
                   2439: }
1.658     raeburn  2440: 
1.149     www      2441: # ----------------------------------------------------------- Check out an item
                   2442: 
1.504     albertel 2443: sub get_first_access {
                   2444:     my ($type,$argsymb)=@_;
1.790     albertel 2445:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2446:     if ($argsymb) { $symb=$argsymb; }
                   2447:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2448:     if ($type eq 'map') {
                   2449: 	$res=&symbread($map);
                   2450:     } else {
                   2451: 	$res=$symb;
                   2452:     }
                   2453:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2454:     return $times{"$courseid\0$res"};
1.504     albertel 2455: }
                   2456: 
                   2457: sub set_first_access {
                   2458:     my ($type)=@_;
1.790     albertel 2459:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2460:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2461:     if ($type eq 'map') {
                   2462: 	$res=&symbread($map);
                   2463:     } else {
                   2464: 	$res=$symb;
                   2465:     }
                   2466:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2467:     if (!$firstaccess) {
1.588     albertel 2468: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2469:     }
                   2470:     return 'already_set';
1.504     albertel 2471: }
                   2472: 
1.149     www      2473: sub checkout {
                   2474:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2475:     my $now=time;
                   2476:     my $lonhost=$perlvar{'lonHostID'};
                   2477:     my $infostr=&escape(
1.234     www      2478:                  'CHECKOUTTOKEN&'.
1.149     www      2479:                  $tuname.'&'.
                   2480:                  $tudom.'&'.
                   2481:                  $tcrsid.'&'.
                   2482:                  $symb.'&'.
                   2483: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2484:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2485:     if ($token=~/^error\:/) { 
1.672     albertel 2486:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2487:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2488:                  "</font>");
                   2489:         return ''; 
                   2490:     }
                   2491: 
1.149     www      2492:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2493:     $token=~tr/a-z/A-Z/;
                   2494: 
1.153     www      2495:     my %infohash=('resource.0.outtoken' => $token,
                   2496:                   'resource.0.checkouttime' => $now,
                   2497:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2498: 
                   2499:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2500:        return '';
1.151     www      2501:     } else {
1.672     albertel 2502:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2503:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2504:                  "</font>");
1.149     www      2505:     }    
                   2506: 
                   2507:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2508:                          &escape('Checkout '.$infostr.' - '.
                   2509:                                                  $token)) ne 'ok') {
                   2510: 	return '';
1.151     www      2511:     } else {
1.672     albertel 2512:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2513:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2514:                  "</font>");
1.149     www      2515:     }
1.151     www      2516:     return $token;
1.149     www      2517: }
                   2518: 
                   2519: # ------------------------------------------------------------ Check in an item
                   2520: 
                   2521: sub checkin {
                   2522:     my $token=shift;
1.150     www      2523:     my $now=time;
                   2524:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2525:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2526:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2527:     $dtoken=~s/\W/\_/g;
1.234     www      2528:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2529:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2530: 
1.154     www      2531:     unless (($tuname) && ($tudom)) {
                   2532:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2533:         return '';
                   2534:     }
                   2535:     
                   2536:     unless (&allowed('mgr',$tcrsid)) {
                   2537:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2538:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2539:         return '';
                   2540:     }
                   2541: 
1.153     www      2542:     my %infohash=('resource.0.intoken' => $token,
                   2543:                   'resource.0.checkintime' => $now,
                   2544:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2545: 
                   2546:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2547:        return '';
                   2548:     }    
                   2549: 
                   2550:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2551:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2552: 	return '';
                   2553:     }
                   2554: 
                   2555:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2556: }
                   2557: 
                   2558: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2559: 
                   2560: sub expirespread {
                   2561:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2562:     my $cid=$env{'request.course.id'}; 
1.110     www      2563:     if ($cid) {
                   2564:        my $now=time;
                   2565:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2566:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2567:                             $env{'course.'.$cid.'.num'}.
1.110     www      2568: 	        	    ':nohist_expirationdates:'.
                   2569:                             &escape($key).'='.$now,
1.620     albertel 2570:                             $env{'course.'.$cid.'.home'})
1.110     www      2571:     }
                   2572:     return 'ok';
1.14      www      2573: }
                   2574: 
1.109     www      2575: # ----------------------------------------------------- Devalidate Spreadsheets
                   2576: 
                   2577: sub devalidate {
1.325     www      2578:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2579:     my $cid=$env{'request.course.id'}; 
1.109     www      2580:     if ($cid) {
1.391     matthew  2581:         # delete the stored spreadsheets for
                   2582:         # - the student level sheet of this user in course's homespace
                   2583:         # - the assessment level sheet for this resource 
                   2584:         #   for this user in user's homespace
1.553     albertel 2585: 	# - current conditional state info
1.325     www      2586: 	my $key=$uname.':'.$udom.':';
1.109     www      2587:         my $status=
1.299     matthew  2588: 	    &del('nohist_calculatedsheets',
1.391     matthew  2589: 		 [$key.'studentcalc:'],
1.620     albertel 2590: 		 $env{'course.'.$cid.'.domain'},
                   2591: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2592: 		.' '.
                   2593: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2594: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2595:         unless ($status eq 'ok ok') {
                   2596:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2597:                     $uname.' at '.$udom.' for '.
1.109     www      2598: 		    $symb.': '.$status);
1.133     albertel 2599:         }
1.553     albertel 2600: 	&delenv('user.state.'.$cid);
1.109     www      2601:     }
                   2602: }
                   2603: 
1.265     albertel 2604: sub get_scalar {
                   2605:     my ($string,$end) = @_;
                   2606:     my $value;
                   2607:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2608: 	$value = $1;
                   2609:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2610: 	$value = $1;
                   2611:     }
                   2612:     return &unescape($value);
                   2613: }
                   2614: 
                   2615: sub array2str {
                   2616:   my (@array) = @_;
                   2617:   my $result=&arrayref2str(\@array);
                   2618:   $result=~s/^__ARRAY_REF__//;
                   2619:   $result=~s/__END_ARRAY_REF__$//;
                   2620:   return $result;
                   2621: }
                   2622: 
1.204     albertel 2623: sub arrayref2str {
                   2624:   my ($arrayref) = @_;
1.265     albertel 2625:   my $result='__ARRAY_REF__';
1.204     albertel 2626:   foreach my $elem (@$arrayref) {
1.265     albertel 2627:     if(ref($elem) eq 'ARRAY') {
                   2628:       $result.=&arrayref2str($elem).'&';
                   2629:     } elsif(ref($elem) eq 'HASH') {
                   2630:       $result.=&hashref2str($elem).'&';
                   2631:     } elsif(ref($elem)) {
                   2632:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2633:     } else {
                   2634:       $result.=&escape($elem).'&';
                   2635:     }
                   2636:   }
                   2637:   $result=~s/\&$//;
1.265     albertel 2638:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2639:   return $result;
                   2640: }
                   2641: 
1.168     albertel 2642: sub hash2str {
1.204     albertel 2643:   my (%hash) = @_;
                   2644:   my $result=&hashref2str(\%hash);
1.265     albertel 2645:   $result=~s/^__HASH_REF__//;
                   2646:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2647:   return $result;
                   2648: }
                   2649: 
                   2650: sub hashref2str {
                   2651:   my ($hashref)=@_;
1.265     albertel 2652:   my $result='__HASH_REF__';
1.800     albertel 2653:   foreach my $key (sort(keys(%$hashref))) {
                   2654:     if (ref($key) eq 'ARRAY') {
                   2655:       $result.=&arrayref2str($key).'=';
                   2656:     } elsif (ref($key) eq 'HASH') {
                   2657:       $result.=&hashref2str($key).'=';
                   2658:     } elsif (ref($key)) {
1.265     albertel 2659:       $result.='=';
1.800     albertel 2660:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2661:     } else {
1.800     albertel 2662: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2663:     }
                   2664: 
1.800     albertel 2665:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2666:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2667:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2668:       $result.=&hashref2str($hashref->{$key}).'&';
                   2669:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2670:        $result.='&';
1.800     albertel 2671:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2672:     } else {
1.800     albertel 2673:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2674:     }
                   2675:   }
1.168     albertel 2676:   $result=~s/\&$//;
1.265     albertel 2677:   $result .= '__END_HASH_REF__';
1.168     albertel 2678:   return $result;
                   2679: }
                   2680: 
                   2681: sub str2hash {
1.265     albertel 2682:     my ($string)=@_;
                   2683:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2684:     return %$hash;
                   2685: }
                   2686: 
                   2687: sub str2hashref {
1.168     albertel 2688:   my ($string) = @_;
1.265     albertel 2689: 
                   2690:   my %hash;
                   2691: 
                   2692:   if($string !~ /^__HASH_REF__/) {
                   2693:       if (! ($string eq '' || !defined($string))) {
                   2694: 	  $hash{'error'}='Not hash reference';
                   2695:       }
                   2696:       return (\%hash, $string);
                   2697:   }
                   2698: 
                   2699:   $string =~ s/^__HASH_REF__//;
                   2700: 
                   2701:   while($string !~ /^__END_HASH_REF__/) {
                   2702:       #key
                   2703:       my $key='';
                   2704:       if($string =~ /^__HASH_REF__/) {
                   2705:           ($key, $string)=&str2hashref($string);
                   2706:           if(defined($key->{'error'})) {
                   2707:               $hash{'error'}='Bad data';
                   2708:               return (\%hash, $string);
                   2709:           }
                   2710:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2711:           ($key, $string)=&str2arrayref($string);
                   2712:           if($key->[0] eq 'Array reference error') {
                   2713:               $hash{'error'}='Bad data';
                   2714:               return (\%hash, $string);
                   2715:           }
                   2716:       } else {
                   2717:           $string =~ s/^(.*?)=//;
1.267     albertel 2718: 	  $key=&unescape($1);
1.265     albertel 2719:       }
                   2720:       $string =~ s/^=//;
                   2721: 
                   2722:       #value
                   2723:       my $value='';
                   2724:       if($string =~ /^__HASH_REF__/) {
                   2725:           ($value, $string)=&str2hashref($string);
                   2726:           if(defined($value->{'error'})) {
                   2727:               $hash{'error'}='Bad data';
                   2728:               return (\%hash, $string);
                   2729:           }
                   2730:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2731:           ($value, $string)=&str2arrayref($string);
                   2732:           if($value->[0] eq 'Array reference error') {
                   2733:               $hash{'error'}='Bad data';
                   2734:               return (\%hash, $string);
                   2735:           }
                   2736:       } else {
                   2737: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2738:       }
                   2739:       $string =~ s/^&//;
                   2740: 
                   2741:       $hash{$key}=$value;
1.204     albertel 2742:   }
1.265     albertel 2743: 
                   2744:   $string =~ s/^__END_HASH_REF__//;
                   2745: 
                   2746:   return (\%hash, $string);
1.204     albertel 2747: }
                   2748: 
                   2749: sub str2array {
1.265     albertel 2750:     my ($string)=@_;
                   2751:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2752:     return @$array;
                   2753: }
                   2754: 
                   2755: sub str2arrayref {
1.204     albertel 2756:   my ($string) = @_;
1.265     albertel 2757:   my @array;
                   2758: 
                   2759:   if($string !~ /^__ARRAY_REF__/) {
                   2760:       if (! ($string eq '' || !defined($string))) {
                   2761: 	  $array[0]='Array reference error';
                   2762:       }
                   2763:       return (\@array, $string);
                   2764:   }
                   2765: 
                   2766:   $string =~ s/^__ARRAY_REF__//;
                   2767: 
                   2768:   while($string !~ /^__END_ARRAY_REF__/) {
                   2769:       my $value='';
                   2770:       if($string =~ /^__HASH_REF__/) {
                   2771:           ($value, $string)=&str2hashref($string);
                   2772:           if(defined($value->{'error'})) {
                   2773:               $array[0] ='Array reference error';
                   2774:               return (\@array, $string);
                   2775:           }
                   2776:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2777:           ($value, $string)=&str2arrayref($string);
                   2778:           if($value->[0] eq 'Array reference error') {
                   2779:               $array[0] ='Array reference error';
                   2780:               return (\@array, $string);
                   2781:           }
                   2782:       } else {
                   2783: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2784:       }
                   2785:       $string =~ s/^&//;
                   2786: 
                   2787:       push(@array, $value);
1.191     harris41 2788:   }
1.265     albertel 2789: 
                   2790:   $string =~ s/^__END_ARRAY_REF__//;
                   2791: 
                   2792:   return (\@array, $string);
1.168     albertel 2793: }
                   2794: 
1.167     albertel 2795: # -------------------------------------------------------------------Temp Store
                   2796: 
1.168     albertel 2797: sub tmpreset {
                   2798:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2799:   if (!$symb) {
                   2800:     $symb=&symbread();
1.620     albertel 2801:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2802:   }
                   2803:   $symb=escape($symb);
                   2804: 
1.620     albertel 2805:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2806:   $namespace=~s/\//\_/g;
                   2807:   $namespace=~s/\W//g;
                   2808: 
1.620     albertel 2809:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2810:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2811:   if ($domain eq 'public' && $stuname eq 'public') {
                   2812:       $stuname=$ENV{'REMOTE_ADDR'};
                   2813:   }
1.168     albertel 2814:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2815:   my %hash;
                   2816:   if (tie(%hash,'GDBM_File',
                   2817: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2818: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2819:     foreach my $key (keys %hash) {
1.180     albertel 2820:       if ($key=~ /:$symb/) {
1.168     albertel 2821: 	delete($hash{$key});
                   2822:       }
                   2823:     }
                   2824:   }
                   2825: }
                   2826: 
1.167     albertel 2827: sub tmpstore {
1.168     albertel 2828:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2829: 
                   2830:   if (!$symb) {
                   2831:     $symb=&symbread();
1.620     albertel 2832:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2833:   }
                   2834:   $symb=escape($symb);
                   2835: 
                   2836:   if (!$namespace) {
                   2837:     # I don't think we would ever want to store this for a course.
                   2838:     # it seems this will only be used if we don't have a course.
1.620     albertel 2839:     #$namespace=$env{'request.course.id'};
1.168     albertel 2840:     #if (!$namespace) {
1.620     albertel 2841:       $namespace=$env{'request.state'};
1.168     albertel 2842:     #}
                   2843:   }
                   2844:   $namespace=~s/\//\_/g;
                   2845:   $namespace=~s/\W//g;
1.620     albertel 2846:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2847:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2848:   if ($domain eq 'public' && $stuname eq 'public') {
                   2849:       $stuname=$ENV{'REMOTE_ADDR'};
                   2850:   }
1.168     albertel 2851:   my $now=time;
                   2852:   my %hash;
                   2853:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2854:   if (tie(%hash,'GDBM_File',
                   2855: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2856: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2857:     $hash{"version:$symb"}++;
                   2858:     my $version=$hash{"version:$symb"};
                   2859:     my $allkeys=''; 
                   2860:     foreach my $key (keys(%$storehash)) {
                   2861:       $allkeys.=$key.':';
1.591     albertel 2862:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2863:     }
                   2864:     $hash{"$version:$symb:timestamp"}=$now;
                   2865:     $allkeys.='timestamp';
                   2866:     $hash{"$version:keys:$symb"}=$allkeys;
                   2867:     if (untie(%hash)) {
                   2868:       return 'ok';
                   2869:     } else {
                   2870:       return "error:$!";
                   2871:     }
                   2872:   } else {
                   2873:     return "error:$!";
                   2874:   }
                   2875: }
1.167     albertel 2876: 
1.168     albertel 2877: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2878: 
1.168     albertel 2879: sub tmprestore {
                   2880:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2881: 
1.168     albertel 2882:   if (!$symb) {
                   2883:     $symb=&symbread();
1.620     albertel 2884:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2885:   }
                   2886:   $symb=escape($symb);
                   2887: 
1.620     albertel 2888:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2889: 
1.620     albertel 2890:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2891:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2892:   if ($domain eq 'public' && $stuname eq 'public') {
                   2893:       $stuname=$ENV{'REMOTE_ADDR'};
                   2894:   }
1.168     albertel 2895:   my %returnhash;
                   2896:   $namespace=~s/\//\_/g;
                   2897:   $namespace=~s/\W//g;
                   2898:   my %hash;
                   2899:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2900:   if (tie(%hash,'GDBM_File',
                   2901: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2902: 	  &GDBM_READER(),0640)) {
1.168     albertel 2903:     my $version=$hash{"version:$symb"};
                   2904:     $returnhash{'version'}=$version;
                   2905:     my $scope;
                   2906:     for ($scope=1;$scope<=$version;$scope++) {
                   2907:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2908:       my @keys=split(/:/,$vkeys);
                   2909:       my $key;
                   2910:       $returnhash{"$scope:keys"}=$vkeys;
                   2911:       foreach $key (@keys) {
1.591     albertel 2912: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2913: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2914:       }
                   2915:     }
1.168     albertel 2916:     if (!(untie(%hash))) {
                   2917:       return "error:$!";
                   2918:     }
                   2919:   } else {
                   2920:     return "error:$!";
                   2921:   }
                   2922:   return %returnhash;
1.167     albertel 2923: }
                   2924: 
1.9       www      2925: # ----------------------------------------------------------------------- Store
                   2926: 
                   2927: sub store {
1.124     www      2928:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2929:     my $home='';
                   2930: 
1.168     albertel 2931:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2932: 
1.213     www      2933:     $symb=&symbclean($symb);
1.122     albertel 2934:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2935: 
1.620     albertel 2936:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2937:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2938: 
                   2939:     &devalidate($symb,$stuname,$domain);
1.109     www      2940: 
                   2941:     $symb=escape($symb);
1.187     www      2942:     if (!$namespace) { 
1.620     albertel 2943:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2944:           return ''; 
                   2945:        } 
                   2946:     }
1.620     albertel 2947:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2948: 
                   2949:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2950:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2951: 
1.12      www      2952:     my $namevalue='';
1.800     albertel 2953:     foreach my $key (keys(%$storehash)) {
                   2954:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2955:     }
1.12      www      2956:     $namevalue=~s/\&$//;
1.187     www      2957:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2958:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2959: }
                   2960: 
1.47      www      2961: # -------------------------------------------------------------- Critical Store
                   2962: 
                   2963: sub cstore {
1.124     www      2964:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2965:     my $home='';
                   2966: 
1.168     albertel 2967:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2968: 
1.213     www      2969:     $symb=&symbclean($symb);
1.122     albertel 2970:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2971: 
1.620     albertel 2972:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2973:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2974: 
                   2975:     &devalidate($symb,$stuname,$domain);
1.109     www      2976: 
                   2977:     $symb=escape($symb);
1.187     www      2978:     if (!$namespace) { 
1.620     albertel 2979:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2980:           return ''; 
                   2981:        } 
                   2982:     }
1.620     albertel 2983:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2984: 
                   2985:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2986:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2987: 
1.47      www      2988:     my $namevalue='';
1.800     albertel 2989:     foreach my $key (keys(%$storehash)) {
                   2990:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2991:     }
1.47      www      2992:     $namevalue=~s/\&$//;
1.187     www      2993:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2994:     return critical
                   2995:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2996: }
                   2997: 
1.9       www      2998: # --------------------------------------------------------------------- Restore
                   2999: 
                   3000: sub restore {
1.124     www      3001:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3002:     my $home='';
                   3003: 
1.168     albertel 3004:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3005: 
1.122     albertel 3006:     if (!$symb) {
                   3007:       unless ($symb=escape(&symbread())) { return ''; }
                   3008:     } else {
1.213     www      3009:       $symb=&escape(&symbclean($symb));
1.122     albertel 3010:     }
1.188     www      3011:     if (!$namespace) { 
1.620     albertel 3012:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3013:           return ''; 
                   3014:        } 
                   3015:     }
1.620     albertel 3016:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3017:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3018:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3019:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3020: 
1.12      www      3021:     my %returnhash=();
1.800     albertel 3022:     foreach my $line (split(/\&/,$answer)) {
                   3023: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3024:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3025:     }
1.75      www      3026:     my $version;
                   3027:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3028:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3029:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3030:        }
1.75      www      3031:     }
1.13      www      3032:     return %returnhash;
1.34      www      3033: }
                   3034: 
                   3035: # ---------------------------------------------------------- Course Description
                   3036: 
                   3037: sub coursedescription {
1.731     albertel 3038:     my ($courseid,$args)=@_;
1.34      www      3039:     $courseid=~s/^\///;
1.49      www      3040:     $courseid=~s/\_/\//g;
1.34      www      3041:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3042:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3043:     my $normalid=$cdomain.'_'.$cnum;
                   3044:     # need to always cache even if we get errors otherwise we keep 
                   3045:     # trying and trying and trying to get the course description.
                   3046:     my %envhash=();
                   3047:     my %returnhash=();
1.731     albertel 3048:     
                   3049:     my $expiretime=600;
                   3050:     if ($env{'request.course.id'} eq $normalid) {
                   3051: 	$expiretime=120;
                   3052:     }
                   3053: 
                   3054:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3055:     if (!$args->{'freshen_cache'}
                   3056: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3057: 	foreach my $key (keys(%env)) {
                   3058: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3059: 	    my ($setting) = $1;
                   3060: 	    $returnhash{$setting} = $env{$key};
                   3061: 	}
                   3062: 	return %returnhash;
                   3063:     }
                   3064: 
                   3065:     # get the data agin
                   3066:     if (!$args->{'one_time'}) {
                   3067: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3068:     }
1.811     albertel 3069: 
1.34      www      3070:     if ($chome ne 'no_host') {
1.302     albertel 3071:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3072:        if (!exists($returnhash{'con_lost'})) {
                   3073:            $returnhash{'home'}= $chome;
                   3074: 	   $returnhash{'domain'} = $cdomain;
                   3075: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3076:            if (!defined($returnhash{'type'})) {
                   3077:                $returnhash{'type'} = 'Course';
                   3078:            }
1.130     albertel 3079:            while (my ($name,$value) = each %returnhash) {
1.53      www      3080:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3081:            }
1.270     www      3082:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3083:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3084: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3085:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3086:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3087:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3088:        }
                   3089:     }
1.731     albertel 3090:     if (!$args->{'one_time'}) {
                   3091: 	&appenv(%envhash);
                   3092:     }
1.302     albertel 3093:     return %returnhash;
1.461     www      3094: }
                   3095: 
                   3096: # -------------------------------------------------See if a user is privileged
                   3097: 
                   3098: sub privileged {
                   3099:     my ($username,$domain)=@_;
                   3100:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3101: 			&homeserver($username,$domain));
                   3102:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3103:     my $now=time;
                   3104:     if ($rolesdump ne '') {
1.800     albertel 3105:         foreach my $entry (split(/&/,$rolesdump)) {
                   3106: 	    if ($entry!~/^rolesdef_/) {
                   3107: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3108: 		$area=~s/\_\w\w$//;
                   3109: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3110: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3111: 		    my $active=1;
                   3112: 		    if ($tend) {
                   3113: 			if ($tend<$now) { $active=0; }
                   3114: 		    }
                   3115: 		    if ($tstart) {
                   3116: 			if ($tstart>$now) { $active=0; }
                   3117: 		    }
                   3118: 		    if ($active) { return 1; }
                   3119: 		}
                   3120: 	    }
                   3121: 	}
                   3122:     }
                   3123:     return 0;
1.9       www      3124: }
1.1       albertel 3125: 
1.103     harris41 3126: # -------------------------------------------------------- Get user privileges
1.11      www      3127: 
                   3128: sub rolesinit {
                   3129:     my ($domain,$username,$authhost)=@_;
                   3130:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3131:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3132:     my %allroles=();
1.678     raeburn  3133:     my %allgroups=();   
1.11      www      3134:     my $now=time;
1.743     albertel 3135:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3136:     my $group_privs;
1.11      www      3137: 
                   3138:     if ($rolesdump ne '') {
1.800     albertel 3139:         foreach my $entry (split(/&/,$rolesdump)) {
                   3140: 	  if ($entry!~/^rolesdef_/) {
                   3141:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3142: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3143:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3144: 	    if ($role=~/^cr/) { 
1.807     albertel 3145: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3146: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3147: 		    ($tend,$tstart)=split('_',$trest);
                   3148: 		} else {
                   3149: 		    $trole=$role;
                   3150: 		}
1.678     raeburn  3151:             } elsif ($role =~ m|^gr/|) {
                   3152:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3153:                 ($trole,$group_privs) = split(/\//,$trole);
                   3154:                 $group_privs = &unescape($group_privs);
1.587     albertel 3155: 	    } else {
                   3156: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3157: 	    }
1.743     albertel 3158: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3159: 					 $username);
                   3160: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3161:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3162:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3163:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3164: 		my $spec=$trole.'.'.$area;
                   3165: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3166: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3167:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3168:                 } elsif ($trole eq 'gr') {
                   3169:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3170: 		} else {
1.567     raeburn  3171:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3172: 		}
1.12      www      3173:             }
1.662     raeburn  3174:           }
1.191     harris41 3175:         }
1.743     albertel 3176:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3177:         $userroles{'user.adv'}    = $adv;
                   3178: 	$userroles{'user.author'} = $author;
1.620     albertel 3179:         $env{'user.adv'}=$adv;
1.11      www      3180:     }
1.743     albertel 3181:     return \%userroles;  
1.11      www      3182: }
                   3183: 
1.567     raeburn  3184: sub set_arearole {
                   3185:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3186: # log the associated role with the area
                   3187:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3188:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3189: }
                   3190: 
                   3191: sub custom_roleprivs {
                   3192:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3193:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3194:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3195:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3196:         my ($rdummy,$roledef)=
                   3197:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3198:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3199:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3200:             if (defined($syspriv)) {
                   3201:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3202:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3203:             }
                   3204:             if ($tdomain ne '') {
                   3205:                 if (defined($dompriv)) {
                   3206:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3207:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3208:                 }
                   3209:                 if (($trest ne '') && (defined($coursepriv))) {
                   3210:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3211:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3212:                 }
                   3213:             }
                   3214:         }
                   3215:     }
                   3216: }
                   3217: 
1.678     raeburn  3218: sub group_roleprivs {
                   3219:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3220:     my $access = 1;
                   3221:     my $now = time;
                   3222:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3223:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3224:     if ($access) {
1.811     albertel 3225:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3226:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3227:     }
                   3228: }
1.567     raeburn  3229: 
                   3230: sub standard_roleprivs {
                   3231:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3232:     if (defined($pr{$trole.':s'})) {
                   3233:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3234:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3235:     }
                   3236:     if ($tdomain ne '') {
                   3237:         if (defined($pr{$trole.':d'})) {
                   3238:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3239:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3240:         }
                   3241:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3242:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3243:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3244:         }
                   3245:     }
                   3246: }
                   3247: 
                   3248: sub set_userprivs {
1.678     raeburn  3249:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3250:     my $author=0;
                   3251:     my $adv=0;
1.678     raeburn  3252:     my %grouproles = ();
                   3253:     if (keys(%{$allgroups}) > 0) {
                   3254:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3255:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3256:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3257:                 $trole = $1;
                   3258:                 $area = $2;
1.681     raeburn  3259:                 $sec = $3;
                   3260:                 $extendedarea = $area.$sec;
                   3261:                 if (exists($$allgroups{$area})) {
                   3262:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3263:                         my $spec = $trole.'.'.$extendedarea;
                   3264:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3265:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3266:                     }
                   3267:                 }
                   3268:             }
                   3269:         }
                   3270:     }
1.800     albertel 3271:     foreach my $group (keys(%grouproles)) {
                   3272:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3273:     }
1.800     albertel 3274:     foreach my $role (keys(%{$allroles})) {
                   3275:         my %thesepriv;
                   3276:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3277:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3278:             if ($item ne '') {
                   3279:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3280:                 if ($restrictions eq '') {
                   3281:                     $thesepriv{$privilege}='F';
                   3282:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3283:                     $thesepriv{$privilege}.=$restrictions;
                   3284:                 }
                   3285:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3286:             }
                   3287:         }
                   3288:         my $thesestr='';
1.800     albertel 3289:         foreach my $priv (keys(%thesepriv)) {
                   3290: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3291: 	}
                   3292:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3293:     }
                   3294:     return ($author,$adv);
                   3295: }
                   3296: 
1.12      www      3297: # --------------------------------------------------------------- get interface
                   3298: 
                   3299: sub get {
1.131     albertel 3300:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3301:    my $items='';
1.800     albertel 3302:    foreach my $item (@$storearr) {
                   3303:        $items.=&escape($item).'&';
1.191     harris41 3304:    }
1.12      www      3305:    $items=~s/\&$//;
1.620     albertel 3306:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3307:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3308:    my $uhome=&homeserver($uname,$udomain);
                   3309: 
1.133     albertel 3310:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3311:    my @pairs=split(/\&/,$rep);
1.273     albertel 3312:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3313:      return @pairs;
                   3314:    }
1.15      www      3315:    my %returnhash=();
1.42      www      3316:    my $i=0;
1.800     albertel 3317:    foreach my $item (@$storearr) {
                   3318:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3319:       $i++;
1.191     harris41 3320:    }
1.15      www      3321:    return %returnhash;
1.27      www      3322: }
                   3323: 
                   3324: # --------------------------------------------------------------- del interface
                   3325: 
                   3326: sub del {
1.133     albertel 3327:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3328:    my $items='';
1.800     albertel 3329:    foreach my $item (@$storearr) {
                   3330:        $items.=&escape($item).'&';
1.191     harris41 3331:    }
1.27      www      3332:    $items=~s/\&$//;
1.620     albertel 3333:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3334:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3335:    my $uhome=&homeserver($uname,$udomain);
                   3336: 
                   3337:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3338: }
                   3339: 
                   3340: # -------------------------------------------------------------- dump interface
                   3341: 
                   3342: sub dump {
1.755     albertel 3343:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3344:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3345:     if (!$uname) { $uname=$env{'user.name'}; }
                   3346:     my $uhome=&homeserver($uname,$udomain);
                   3347:     if ($regexp) {
                   3348: 	$regexp=&escape($regexp);
                   3349:     } else {
                   3350: 	$regexp='.';
                   3351:     }
                   3352:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3353:     my @pairs=split(/\&/,$rep);
                   3354:     my %returnhash=();
                   3355:     foreach my $item (@pairs) {
                   3356: 	my ($key,$value)=split(/=/,$item,2);
                   3357: 	$key = &unescape($key);
                   3358: 	next if ($key =~ /^error: 2 /);
                   3359: 	$returnhash{$key}=&thaw_unescape($value);
                   3360:     }
                   3361:     return %returnhash;
1.407     www      3362: }
                   3363: 
1.717     albertel 3364: # --------------------------------------------------------- dumpstore interface
                   3365: 
                   3366: sub dumpstore {
                   3367:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3368:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3369:    if (!$uname) { $uname=$env{'user.name'}; }
                   3370:    my $uhome=&homeserver($uname,$udomain);
                   3371:    if ($regexp) {
                   3372:        $regexp=&escape($regexp);
                   3373:    } else {
                   3374:        $regexp='.';
                   3375:    }
                   3376:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3377:    my @pairs=split(/\&/,$rep);
                   3378:    my %returnhash=();
                   3379:    foreach my $item (@pairs) {
                   3380:        my ($key,$value)=split(/=/,$item,2);
                   3381:        next if ($key =~ /^error: 2 /);
                   3382:        $returnhash{$key}=&thaw_unescape($value);
                   3383:    }
                   3384:    return %returnhash;
1.717     albertel 3385: }
                   3386: 
1.407     www      3387: # -------------------------------------------------------------- keys interface
                   3388: 
                   3389: sub getkeys {
                   3390:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3391:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3392:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3393:    my $uhome=&homeserver($uname,$udomain);
                   3394:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3395:    my @keyarray=();
1.800     albertel 3396:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3397:       next if ($key =~ /^error: 2 /);
1.800     albertel 3398:       push(@keyarray,&unescape($key));
1.407     www      3399:    }
                   3400:    return @keyarray;
1.318     matthew  3401: }
                   3402: 
1.319     matthew  3403: # --------------------------------------------------------------- currentdump
                   3404: sub currentdump {
1.328     matthew  3405:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3406:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3407:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3408:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3409:    my $uhome = &homeserver($sname,$sdom);
                   3410:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3411:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3412:    #
1.318     matthew  3413:    my %returnhash=();
1.319     matthew  3414:    #
                   3415:    if ($rep eq "unknown_cmd") { 
                   3416:        # an old lond will not know currentdump
                   3417:        # Do a dump and make it look like a currentdump
1.822     albertel 3418:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3419:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3420:        my %hash = @tmp;
                   3421:        @tmp=();
1.424     matthew  3422:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3423:    } else {
                   3424:        my @pairs=split(/\&/,$rep);
1.800     albertel 3425:        foreach my $pair (@pairs) {
                   3426:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3427:            my ($symb,$param) = split(/:/,$key);
                   3428:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3429:                                                         &thaw_unescape($value);
1.319     matthew  3430:        }
1.191     harris41 3431:    }
1.12      www      3432:    return %returnhash;
1.424     matthew  3433: }
                   3434: 
                   3435: sub convert_dump_to_currentdump{
                   3436:     my %hash = %{shift()};
                   3437:     my %returnhash;
                   3438:     # Code ripped from lond, essentially.  The only difference
                   3439:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3440:     # we might run in to problems with parameter names =~ /^v\./
                   3441:     while (my ($key,$value) = each(%hash)) {
                   3442:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3443: 	$symb  = &unescape($symb);
                   3444: 	$param = &unescape($param);
1.424     matthew  3445:         next if ($v eq 'version' || $symb eq 'keys');
                   3446:         next if (exists($returnhash{$symb}) &&
                   3447:                  exists($returnhash{$symb}->{$param}) &&
                   3448:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3449:         $returnhash{$symb}->{$param}=$value;
                   3450:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3451:     }
                   3452:     #
                   3453:     # Remove all of the keys in the hashes which keep track of
                   3454:     # the version of the parameter.
                   3455:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3456:         # use a foreach because we are going to delete from the hash.
                   3457:         foreach my $key (keys(%$param_hash)) {
                   3458:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3459:         }
                   3460:     }
                   3461:     return \%returnhash;
1.12      www      3462: }
                   3463: 
1.627     albertel 3464: # ------------------------------------------------------ critical inc interface
                   3465: 
                   3466: sub cinc {
                   3467:     return &inc(@_,'critical');
                   3468: }
                   3469: 
1.449     matthew  3470: # --------------------------------------------------------------- inc interface
                   3471: 
                   3472: sub inc {
1.627     albertel 3473:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3474:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3475:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3476:     my $uhome=&homeserver($uname,$udomain);
                   3477:     my $items='';
                   3478:     if (! ref($store)) {
                   3479:         # got a single value, so use that instead
                   3480:         $items = &escape($store).'=&';
                   3481:     } elsif (ref($store) eq 'SCALAR') {
                   3482:         $items = &escape($$store).'=&';        
                   3483:     } elsif (ref($store) eq 'ARRAY') {
                   3484:         $items = join('=&',map {&escape($_);} @{$store});
                   3485:     } elsif (ref($store) eq 'HASH') {
                   3486:         while (my($key,$value) = each(%{$store})) {
                   3487:             $items.= &escape($key).'='.&escape($value).'&';
                   3488:         }
                   3489:     }
                   3490:     $items=~s/\&$//;
1.627     albertel 3491:     if ($critical) {
                   3492: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3493:     } else {
                   3494: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3495:     }
1.449     matthew  3496: }
                   3497: 
1.12      www      3498: # --------------------------------------------------------------- put interface
                   3499: 
                   3500: sub put {
1.134     albertel 3501:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3502:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3503:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3504:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3505:    my $items='';
1.800     albertel 3506:    foreach my $item (keys(%$storehash)) {
                   3507:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3508:    }
1.12      www      3509:    $items=~s/\&$//;
1.134     albertel 3510:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3511: }
                   3512: 
1.631     albertel 3513: # ------------------------------------------------------------ newput interface
                   3514: 
                   3515: sub newput {
                   3516:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3517:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3518:    if (!$uname) { $uname=$env{'user.name'}; }
                   3519:    my $uhome=&homeserver($uname,$udomain);
                   3520:    my $items='';
                   3521:    foreach my $key (keys(%$storehash)) {
                   3522:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3523:    }
                   3524:    $items=~s/\&$//;
                   3525:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3526: }
                   3527: 
                   3528: # ---------------------------------------------------------  putstore interface
                   3529: 
1.524     raeburn  3530: sub putstore {
1.715     albertel 3531:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3532:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3533:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3534:    my $uhome=&homeserver($uname,$udomain);
                   3535:    my $items='';
1.715     albertel 3536:    foreach my $key (keys(%$storehash)) {
                   3537:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3538:    }
1.715     albertel 3539:    $items=~s/\&$//;
1.716     albertel 3540:    my $esc_symb=&escape($symb);
                   3541:    my $esc_v=&escape($version);
1.715     albertel 3542:    my $reply =
1.716     albertel 3543:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3544: 	      $uhome);
                   3545:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3546:        # gfall back to way things use to be done
1.715     albertel 3547:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3548: 			    $uname);
1.524     raeburn  3549:    }
1.715     albertel 3550:    return $reply;
                   3551: }
                   3552: 
                   3553: sub old_putstore {
1.716     albertel 3554:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3555:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3556:     if (!$uname) { $uname=$env{'user.name'}; }
                   3557:     my $uhome=&homeserver($uname,$udomain);
                   3558:     my %newstorehash;
1.800     albertel 3559:     foreach my $item (keys(%$storehash)) {
                   3560: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3561: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3562:     }
                   3563:     my $items='';
                   3564:     my %allitems = ();
1.800     albertel 3565:     foreach my $item (keys(%newstorehash)) {
                   3566: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3567: 	    my $key = $1.':keys:'.$2;
                   3568: 	    $allitems{$key} .= $3.':';
                   3569: 	}
1.800     albertel 3570: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3571:     }
1.800     albertel 3572:     foreach my $item (keys(%allitems)) {
                   3573: 	$allitems{$item} =~ s/\:$//;
                   3574: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3575:     }
                   3576:     $items=~s/\&$//;
                   3577:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3578: }
                   3579: 
1.47      www      3580: # ------------------------------------------------------ critical put interface
                   3581: 
                   3582: sub cput {
1.134     albertel 3583:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3584:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3585:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3586:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3587:    my $items='';
1.800     albertel 3588:    foreach my $item (keys(%$storehash)) {
                   3589:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3590:    }
1.47      www      3591:    $items=~s/\&$//;
1.134     albertel 3592:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3593: }
                   3594: 
                   3595: # -------------------------------------------------------------- eget interface
                   3596: 
                   3597: sub eget {
1.133     albertel 3598:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3599:    my $items='';
1.800     albertel 3600:    foreach my $item (@$storearr) {
                   3601:        $items.=&escape($item).'&';
1.191     harris41 3602:    }
1.12      www      3603:    $items=~s/\&$//;
1.620     albertel 3604:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3605:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3606:    my $uhome=&homeserver($uname,$udomain);
                   3607:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3608:    my @pairs=split(/\&/,$rep);
                   3609:    my %returnhash=();
1.42      www      3610:    my $i=0;
1.800     albertel 3611:    foreach my $item (@$storearr) {
                   3612:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3613:       $i++;
1.191     harris41 3614:    }
1.12      www      3615:    return %returnhash;
                   3616: }
                   3617: 
1.667     albertel 3618: # ------------------------------------------------------------ tmpput interface
                   3619: sub tmpput {
1.802     raeburn  3620:     my ($storehash,$server,$context)=@_;
1.667     albertel 3621:     my $items='';
1.800     albertel 3622:     foreach my $item (keys(%$storehash)) {
                   3623: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3624:     }
                   3625:     $items=~s/\&$//;
1.802     raeburn  3626:     if (defined($context)) {
                   3627:         $items .= ':'.&escape($context);
                   3628:     }
1.667     albertel 3629:     return &reply("tmpput:$items",$server);
                   3630: }
                   3631: 
                   3632: # ------------------------------------------------------------ tmpget interface
                   3633: sub tmpget {
1.688     albertel 3634:     my ($token,$server)=@_;
                   3635:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3636:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3637:     my %returnhash;
                   3638:     foreach my $item (split(/\&/,$rep)) {
                   3639: 	my ($key,$value)=split(/=/,$item);
                   3640: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3641:     }
                   3642:     return %returnhash;
                   3643: }
                   3644: 
1.688     albertel 3645: # ------------------------------------------------------------ tmpget interface
                   3646: sub tmpdel {
                   3647:     my ($token,$server)=@_;
                   3648:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3649:     return &reply("tmpdel:$token",$server);
                   3650: }
                   3651: 
1.765     albertel 3652: # -------------------------------------------------- portfolio access checking
                   3653: 
                   3654: sub portfolio_access {
1.766     albertel 3655:     my ($requrl) = @_;
1.765     albertel 3656:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3657:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3658:     if ($result) {
                   3659:         my %setters;
                   3660:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3661:             my ($startblock,$endblock) =
                   3662:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3663:             if ($startblock && $endblock) {
                   3664:                 return 'B';
                   3665:             }
                   3666:         } else {
                   3667:             my ($startblock,$endblock) =
                   3668:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3669:             if ($startblock && $endblock) {
                   3670:                 return 'B';
                   3671:             }
                   3672:         }
                   3673:     }
1.765     albertel 3674:     if ($result eq 'ok') {
1.766     albertel 3675:        return 'F';
1.765     albertel 3676:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3677:        return 'A';
1.765     albertel 3678:     }
1.766     albertel 3679:     return '';
1.765     albertel 3680: }
                   3681: 
                   3682: sub get_portfolio_access {
1.767     albertel 3683:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3684: 
                   3685:     if (!ref($access_hash)) {
                   3686: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3687: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3688: 						   $file_name);
                   3689: 	$access_hash = $access_controls{$file_name};
                   3690:     }
                   3691: 
1.765     albertel 3692:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3693:     my $now = time;
                   3694:     if (ref($access_hash) eq 'HASH') {
                   3695:         foreach my $key (keys(%{$access_hash})) {
                   3696:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3697:             if ($start > $now) {
                   3698:                 next;
                   3699:             }
                   3700:             if ($end && $end<$now) {
                   3701:                 next;
                   3702:             }
                   3703:             if ($scope eq 'public') {
                   3704:                 $public = $key;
                   3705:                 last;
                   3706:             } elsif ($scope eq 'guest') {
                   3707:                 $guest = $key;
                   3708:             } elsif ($scope eq 'domains') {
                   3709:                 push(@domains,$key);
                   3710:             } elsif ($scope eq 'users') {
                   3711:                 push(@users,$key);
                   3712:             } elsif ($scope eq 'course') {
                   3713:                 push(@courses,$key);
                   3714:             } elsif ($scope eq 'group') {
                   3715:                 push(@groups,$key);
                   3716:             }
                   3717:         }
                   3718:         if ($public) {
                   3719:             return 'ok';
                   3720:         }
                   3721:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3722:             if ($guest) {
                   3723:                 return $guest;
                   3724:             }
                   3725:         } else {
                   3726:             if (@domains > 0) {
                   3727:                 foreach my $domkey (@domains) {
                   3728:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3729:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3730:                             return 'ok';
                   3731:                         }
                   3732:                     }
                   3733:                 }
                   3734:             }
                   3735:             if (@users > 0) {
                   3736:                 foreach my $userkey (@users) {
1.865     raeburn  3737:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3738:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3739:                             if (ref($item) eq 'HASH') {
                   3740:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3741:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3742:                                     return 'ok';
                   3743:                                 }
                   3744:                             }
                   3745:                         }
                   3746:                     } 
1.765     albertel 3747:                 }
                   3748:             }
                   3749:             my %roleshash;
                   3750:             my @courses_and_groups = @courses;
                   3751:             push(@courses_and_groups,@groups); 
                   3752:             if (@courses_and_groups > 0) {
                   3753:                 my (%allgroups,%allroles); 
                   3754:                 my ($start,$end,$role,$sec,$group);
                   3755:                 foreach my $envkey (%env) {
1.811     albertel 3756:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3757:                         my $cid = $2.'_'.$3; 
                   3758:                         if ($1 eq 'gr') {
                   3759:                             $group = $4;
                   3760:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3761:                         } else {
                   3762:                             if ($4 eq '') {
                   3763:                                 $sec = 'none';
                   3764:                             } else {
                   3765:                                 $sec = $4;
                   3766:                             }
                   3767:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3768:                         }
1.811     albertel 3769:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3770:                         my $cid = $2.'_'.$3;
                   3771:                         if ($4 eq '') {
                   3772:                             $sec = 'none';
                   3773:                         } else {
                   3774:                             $sec = $4;
                   3775:                         }
                   3776:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3777:                     }
                   3778:                 }
                   3779:                 if (keys(%allroles) == 0) {
                   3780:                     return;
                   3781:                 }
                   3782:                 foreach my $key (@courses_and_groups) {
                   3783:                     my %content = %{$$access_hash{$key}};
                   3784:                     my $cnum = $content{'number'};
                   3785:                     my $cdom = $content{'domain'};
                   3786:                     my $cid = $cdom.'_'.$cnum;
                   3787:                     if (!exists($allroles{$cid})) {
                   3788:                         next;
                   3789:                     }    
                   3790:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3791:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3792:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3793:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3794:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3795:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3796:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3797:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3798:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3799:                                         if (grep/^all$/,@sections) {
                   3800:                                             return 'ok';
                   3801:                                         } else {
                   3802:                                             if (grep/^$sec$/,@sections) {
                   3803:                                                 return 'ok';
                   3804:                                             }
                   3805:                                         }
                   3806:                                     }
                   3807:                                 }
                   3808:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3809:                                     if (grep/^none$/,@groups) {
                   3810:                                         return 'ok';
                   3811:                                     }
                   3812:                                 } else {
                   3813:                                     if (grep/^all$/,@groups) {
                   3814:                                         return 'ok';
                   3815:                                     } 
                   3816:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3817:                                         if (grep/^$group$/,@groups) {
                   3818:                                             return 'ok';
                   3819:                                         }
                   3820:                                     }
                   3821:                                 } 
                   3822:                             }
                   3823:                         }
                   3824:                     }
                   3825:                 }
                   3826:             }
                   3827:             if ($guest) {
                   3828:                 return $guest;
                   3829:             }
                   3830:         }
                   3831:     }
                   3832:     return;
                   3833: }
                   3834: 
                   3835: sub course_group_datechecker {
                   3836:     my ($dates,$now,$status) = @_;
                   3837:     my ($start,$end) = split(/\./,$dates);
                   3838:     if (!$start && !$end) {
                   3839:         return 'ok';
                   3840:     }
                   3841:     if (grep/^active$/,@{$status}) {
                   3842:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3843:             return 'ok';
                   3844:         }
                   3845:     }
                   3846:     if (grep/^previous$/,@{$status}) {
                   3847:         if ($end > $now ) {
                   3848:             return 'ok';
                   3849:         }
                   3850:     }
                   3851:     if (grep/^future$/,@{$status}) {
                   3852:         if ($start > $now) {
                   3853:             return 'ok';
                   3854:         }
                   3855:     }
                   3856:     return; 
                   3857: }
                   3858: 
                   3859: sub parse_portfolio_url {
                   3860:     my ($url) = @_;
                   3861: 
                   3862:     my ($type,$udom,$unum,$group,$file_name);
                   3863:     
1.823     albertel 3864:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3865: 	$type = 1;
                   3866:         $udom = $1;
                   3867:         $unum = $2;
                   3868:         $file_name = $3;
1.823     albertel 3869:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3870: 	$type = 2;
                   3871:         $udom = $1;
                   3872:         $unum = $2;
                   3873:         $group = $3;
                   3874:         $file_name = $3.'/'.$4;
                   3875:     }
                   3876:     if (wantarray) {
                   3877: 	return ($type,$udom,$unum,$file_name,$group);
                   3878:     }
                   3879:     return $type;
                   3880: }
                   3881: 
                   3882: sub is_portfolio_url {
                   3883:     my ($url) = @_;
                   3884:     return scalar(&parse_portfolio_url($url));
                   3885: }
                   3886: 
1.798     raeburn  3887: sub is_portfolio_file {
                   3888:     my ($file) = @_;
1.820     raeburn  3889:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3890:         return 1;
                   3891:     }
                   3892:     return;
                   3893: }
                   3894: 
                   3895: 
1.341     www      3896: # ---------------------------------------------- Custom access rule evaluation
                   3897: 
                   3898: sub customaccess {
                   3899:     my ($priv,$uri)=@_;
1.807     albertel 3900:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3901:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3902:     $udom = &LONCAPA::clean_domain($udom);
                   3903:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3904:     my $access=0;
1.800     albertel 3905:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 3906: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   3907: 	if ($type eq 'user') {
                   3908: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 3909: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 3910: 		if ($tdom) {
                   3911: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   3912: 		}
1.896     albertel 3913: 		if ($tuname) {
                   3914: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 3915: 		}
                   3916: 		$access=($effect eq 'allow');
                   3917: 		last;
                   3918: 	    }
                   3919: 	} else {
                   3920: 	    if ($role) {
                   3921: 		if ($role ne $urole) { next; }
                   3922: 	    }
                   3923: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3924: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   3925: 		if ($tdom) {
                   3926: 		    if ($tdom ne $udom) { next; }
                   3927: 		}
                   3928: 		if ($tcrs) {
                   3929: 		    if ($tcrs ne $ucrs) { next; }
                   3930: 		}
                   3931: 		if ($tsec) {
                   3932: 		    if ($tsec ne $usec) { next; }
                   3933: 		}
                   3934: 		$access=($effect eq 'allow');
                   3935: 		last;
                   3936: 	    }
                   3937: 	    if ($realm eq '' && $role eq '') {
                   3938: 		$access=($effect eq 'allow');
                   3939: 	    }
1.402     bowersj2 3940: 	}
1.341     www      3941:     }
                   3942:     return $access;
                   3943: }
                   3944: 
1.103     harris41 3945: # ------------------------------------------------- Check for a user privilege
1.12      www      3946: 
                   3947: sub allowed {
1.810     raeburn  3948:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3949:     my $ver_orguri=$uri;
1.439     www      3950:     $uri=&deversion($uri);
1.152     www      3951:     my $orguri=$uri;
1.52      www      3952:     $uri=&declutter($uri);
1.809     raeburn  3953: 
1.810     raeburn  3954:     if ($priv eq 'evb') {
                   3955: # Evade communication block restrictions for specified role in a course
                   3956:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3957:             return $1;
                   3958:         } else {
                   3959:             return;
                   3960:         }
                   3961:     }
                   3962: 
1.620     albertel 3963:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3964: # Free bre access to adm and meta resources
1.775     albertel 3965:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3966: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3967: 	&& ($priv eq 'bre')) {
1.14      www      3968: 	return 'F';
1.159     www      3969:     }
                   3970: 
1.545     banghart 3971: # Free bre access to user's own portfolio contents
1.714     raeburn  3972:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3973:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3974: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3975:         my %setters;
                   3976:         my ($startblock,$endblock) = 
                   3977:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3978:         if ($startblock && $endblock) {
                   3979:             return 'B';
                   3980:         } else {
                   3981:             return 'F';
                   3982:         }
1.545     banghart 3983:     }
                   3984: 
1.762     raeburn  3985: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3986:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3987:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3988:         if (exists($env{'request.course.id'})) {
                   3989:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3990:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3991:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3992:                 my $courseprivid=$env{'request.course.id'};
                   3993:                 $courseprivid=~s/\_/\//;
                   3994:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3995:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3996:                     return $1; 
1.762     raeburn  3997:                 } else {
                   3998:                     if ($env{'request.course.sec'}) {
                   3999:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4000:                     }
                   4001:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4002:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4003:                         return $2;
                   4004:                     }
1.714     raeburn  4005:                 }
                   4006:             }
                   4007:         }
                   4008:     }
                   4009: 
1.159     www      4010: # Free bre to public access
                   4011: 
                   4012:     if ($priv eq 'bre') {
1.238     www      4013:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4014: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4015:            return 'F'; 
                   4016:         }
1.238     www      4017:         if ($copyright eq 'priv') {
                   4018:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4019: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4020: 		return '';
                   4021:             }
                   4022:         }
                   4023:         if ($copyright eq 'domain') {
                   4024:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4025: 	    unless (($env{'user.domain'} eq $1) ||
                   4026:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4027: 		return '';
                   4028:             }
1.262     matthew  4029:         }
1.620     albertel 4030:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4031:             # Library role, so allow browsing of resources in this domain.
                   4032:             return 'F';
1.238     www      4033:         }
1.341     www      4034:         if ($copyright eq 'custom') {
                   4035: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4036:         }
1.14      www      4037:     }
1.264     matthew  4038:     # Domain coordinator is trying to create a course
1.620     albertel 4039:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4040:         # uri is the requested domain in this case.
                   4041:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4042:         # a role of dc for the domain in question.
1.620     albertel 4043:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4044:     }
1.29      www      4045: 
1.52      www      4046:     my $thisallowed='';
                   4047:     my $statecond=0;
                   4048:     my $courseprivid='';
                   4049: 
                   4050: # Course
                   4051: 
1.620     albertel 4052:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4053:        $thisallowed.=$1;
                   4054:     }
1.29      www      4055: 
1.52      www      4056: # Domain
                   4057: 
1.620     albertel 4058:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4059:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4060:        $thisallowed.=$1;
                   4061:     }
1.52      www      4062: 
                   4063: # Course: uri itself is a course
1.66      www      4064:     my $courseuri=$uri;
                   4065:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4066:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4067: 
1.620     albertel 4068:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4069:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4070:        $thisallowed.=$1;
                   4071:     }
1.29      www      4072: 
1.665     albertel 4073: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4074: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4075:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4076: 	$thisallowed='';
1.671     raeburn  4077:         my ($match)=&is_on_map($uri);
                   4078:         if ($match) {
                   4079:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4080:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4081:                 $thisallowed.=$1;
                   4082:             }
                   4083:         } else {
1.705     albertel 4084:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4085:             if ($refuri) {
                   4086:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4087:                     $thisallowed='F';
1.671     raeburn  4088:                 } else {
                   4089:                     $refuri=&declutter($refuri);
                   4090:                     my ($match) = &is_on_map($refuri);
                   4091:                     if ($match) {
                   4092:                         $thisallowed='F';
                   4093:                     }
1.669     raeburn  4094:                 }
1.671     raeburn  4095:             }
                   4096:         }
1.314     www      4097:     }
1.492     albertel 4098: 
1.766     albertel 4099:     if ($priv eq 'bre'
                   4100: 	&& $thisallowed ne 'F' 
                   4101: 	&& $thisallowed ne '2'
                   4102: 	&& &is_portfolio_url($uri)) {
                   4103: 	$thisallowed = &portfolio_access($uri);
                   4104:     }
                   4105:     
1.52      www      4106: # Full access at system, domain or course-wide level? Exit.
1.29      www      4107: 
                   4108:     if ($thisallowed=~/F/) {
                   4109: 	return 'F';
                   4110:     }
                   4111: 
1.52      www      4112: # If this is generating or modifying users, exit with special codes
1.29      www      4113: 
1.643     www      4114:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4115: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4116: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4117: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4118: 	    unless ($auname) { return $thisallowed; }
                   4119: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4120: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4121: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4122: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4123: 	}
1.52      www      4124: 	return $thisallowed;
                   4125:     }
                   4126: #
1.103     harris41 4127: # Gathered so far: system, domain and course wide privileges
1.52      www      4128: #
                   4129: # Course: See if uri or referer is an individual resource that is part of 
                   4130: # the course
                   4131: 
1.620     albertel 4132:     if ($env{'request.course.id'}) {
1.232     www      4133: 
1.620     albertel 4134:        $courseprivid=$env{'request.course.id'};
                   4135:        if ($env{'request.course.sec'}) {
                   4136:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4137:        }
                   4138:        $courseprivid=~s/\_/\//;
                   4139:        my $checkreferer=1;
1.232     www      4140:        my ($match,$cond)=&is_on_map($uri);
                   4141:        if ($match) {
                   4142:            $statecond=$cond;
1.620     albertel 4143:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4144:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4145:                $thisallowed.=$1;
                   4146:                $checkreferer=0;
                   4147:            }
1.29      www      4148:        }
1.83      www      4149:        
1.148     www      4150:        if ($checkreferer) {
1.620     albertel 4151: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4152:             unless ($refuri) {
1.800     albertel 4153:                 foreach my $key (keys(%env)) {
                   4154: 		    if ($key=~/^httpref\..*\*/) {
                   4155: 			my $pattern=$key;
1.156     www      4156:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4157:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4158:                         $pattern=~s/\//\\\//g;
1.152     www      4159:                         if ($orguri=~/$pattern/) {
1.800     albertel 4160: 			    $refuri=$env{$key};
1.148     www      4161:                         }
                   4162:                     }
1.191     harris41 4163:                 }
1.148     www      4164:             }
1.232     www      4165: 
1.148     www      4166:          if ($refuri) { 
1.152     www      4167: 	  $refuri=&declutter($refuri);
1.232     www      4168:           my ($match,$cond)=&is_on_map($refuri);
                   4169:             if ($match) {
                   4170:               my $refstatecond=$cond;
1.620     albertel 4171:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4172:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4173:                   $thisallowed.=$1;
1.53      www      4174:                   $uri=$refuri;
                   4175:                   $statecond=$refstatecond;
1.52      www      4176:               }
                   4177:           }
1.148     www      4178:         }
1.29      www      4179:        }
1.52      www      4180:    }
1.29      www      4181: 
1.52      www      4182: #
1.103     harris41 4183: # Gathered now: all privileges that could apply, and condition number
1.52      www      4184: # 
                   4185: #
                   4186: # Full or no access?
                   4187: #
1.29      www      4188: 
1.52      www      4189:     if ($thisallowed=~/F/) {
                   4190: 	return 'F';
                   4191:     }
1.29      www      4192: 
1.52      www      4193:     unless ($thisallowed) {
                   4194:         return '';
                   4195:     }
1.29      www      4196: 
1.52      www      4197: # Restrictions exist, deal with them
                   4198: #
                   4199: #   C:according to course preferences
                   4200: #   R:according to resource settings
                   4201: #   L:unless locked
                   4202: #   X:according to user session state
                   4203: #
                   4204: 
                   4205: # Possibly locked functionality, check all courses
1.54      www      4206: # Locks might take effect only after 10 minutes cache expiration for other
                   4207: # courses, and 2 minutes for current course
1.52      www      4208: 
                   4209:     my $envkey;
                   4210:     if ($thisallowed=~/L/) {
1.620     albertel 4211:         foreach $envkey (keys %env) {
1.54      www      4212:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4213:                my $courseid=$2;
                   4214:                my $roleid=$1.'.'.$2;
1.92      www      4215:                $courseid=~s/^\///;
1.54      www      4216:                my $expiretime=600;
1.620     albertel 4217:                if ($env{'request.role'} eq $roleid) {
1.54      www      4218: 		  $expiretime=120;
                   4219:                }
                   4220: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4221:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4222:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4223: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4224:                }
1.620     albertel 4225:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4226:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4227: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4228:                        &log($env{'user.domain'},$env{'user.name'},
                   4229:                             $env{'user.home'},
1.57      www      4230:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4231:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4232:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4233: 		       return '';
                   4234:                    }
                   4235:                }
1.620     albertel 4236:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4237:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4238: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4239:                        &log($env{'user.domain'},$env{'user.name'},
                   4240:                             $env{'user.home'},
1.57      www      4241:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4242:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4243:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4244: 		       return '';
                   4245:                    }
                   4246:                }
                   4247: 	   }
1.29      www      4248:        }
1.52      www      4249:     }
                   4250:    
                   4251: #
                   4252: # Rest of the restrictions depend on selected course
                   4253: #
                   4254: 
1.620     albertel 4255:     unless ($env{'request.course.id'}) {
1.766     albertel 4256: 	if ($thisallowed eq 'A') {
                   4257: 	    return 'A';
1.814     raeburn  4258:         } elsif ($thisallowed eq 'B') {
                   4259:             return 'B';
1.766     albertel 4260: 	} else {
                   4261: 	    return '1';
                   4262: 	}
1.52      www      4263:     }
1.29      www      4264: 
1.52      www      4265: #
                   4266: # Now user is definitely in a course
                   4267: #
1.53      www      4268: 
                   4269: 
                   4270: # Course preferences
                   4271: 
                   4272:    if ($thisallowed=~/C/) {
1.620     albertel 4273:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4274:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4275:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4276: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4277: 	   if ($priv ne 'pch') { 
                   4278: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4279: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4280: 			$env{'request.course.id'});
                   4281: 	   }
1.237     www      4282:            return '';
                   4283:        }
                   4284: 
1.620     albertel 4285:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4286: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4287: 	   if ($priv ne 'pch') { 
                   4288: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4289: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4290: 			$env{'request.course.id'});
                   4291: 	   }
1.54      www      4292:            return '';
                   4293:        }
1.53      www      4294:    }
                   4295: 
                   4296: # Resource preferences
                   4297: 
                   4298:    if ($thisallowed=~/R/) {
1.620     albertel 4299:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4300:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4301: 	   if ($priv ne 'pch') { 
                   4302: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4303: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4304: 	   }
                   4305: 	   return '';
1.54      www      4306:        }
1.53      www      4307:    }
1.30      www      4308: 
1.246     www      4309: # Restricted by state or randomout?
1.30      www      4310: 
1.52      www      4311:    if ($thisallowed=~/X/) {
1.620     albertel 4312:       if ($env{'acc.randomout'}) {
1.579     albertel 4313: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4314:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4315:             return ''; 
                   4316:          }
1.247     www      4317:       }
                   4318:       if (&condval($statecond)) {
1.52      www      4319: 	 return '2';
                   4320:       } else {
                   4321:          return '';
                   4322:       }
                   4323:    }
1.30      www      4324: 
1.766     albertel 4325:     if ($thisallowed eq 'A') {
                   4326: 	return 'A';
1.814     raeburn  4327:     } elsif ($thisallowed eq 'B') {
                   4328:         return 'B';
1.766     albertel 4329:     }
1.52      www      4330:    return 'F';
1.232     www      4331: }
                   4332: 
1.710     albertel 4333: sub split_uri_for_cond {
                   4334:     my $uri=&deversion(&declutter(shift));
                   4335:     my @uriparts=split(/\//,$uri);
                   4336:     my $filename=pop(@uriparts);
                   4337:     my $pathname=join('/',@uriparts);
                   4338:     return ($pathname,$filename);
                   4339: }
1.232     www      4340: # --------------------------------------------------- Is a resource on the map?
                   4341: 
                   4342: sub is_on_map {
1.710     albertel 4343:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4344:     #Trying to find the conditional for the file
1.620     albertel 4345:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4346: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4347:     if ($match) {
1.289     bowersj2 4348: 	return (1,$1);
                   4349:     } else {
1.434     www      4350: 	return (0,0);
1.289     bowersj2 4351:     }
1.12      www      4352: }
                   4353: 
1.427     www      4354: # --------------------------------------------------------- Get symb from alias
                   4355: 
                   4356: sub get_symb_from_alias {
                   4357:     my $symb=shift;
                   4358:     my ($map,$resid,$url)=&decode_symb($symb);
                   4359: # Already is a symb
                   4360:     if ($url) { return $symb; }
                   4361: # Must be an alias
                   4362:     my $aliassymb='';
                   4363:     my %bighash;
1.620     albertel 4364:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4365:                             &GDBM_READER(),0640)) {
                   4366:         my $rid=$bighash{'mapalias_'.$symb};
                   4367: 	if ($rid) {
                   4368: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4369: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4370: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4371: 	}
                   4372:         untie %bighash;
                   4373:     }
                   4374:     return $aliassymb;
                   4375: }
                   4376: 
1.12      www      4377: # ----------------------------------------------------------------- Define Role
                   4378: 
                   4379: sub definerole {
                   4380:   if (allowed('mcr','/')) {
                   4381:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4382:     foreach my $role (split(':',$sysrole)) {
                   4383: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4384:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4385:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4386: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4387:                return "refused:s:$crole&$cqual"; 
                   4388:             }
                   4389:         }
1.191     harris41 4390:     }
1.800     albertel 4391:     foreach my $role (split(':',$domrole)) {
                   4392: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4393:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4394:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4395: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4396:                return "refused:d:$crole&$cqual"; 
                   4397:             }
                   4398:         }
1.191     harris41 4399:     }
1.800     albertel 4400:     foreach my $role (split(':',$courole)) {
                   4401: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4402:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4403:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4404: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4405:                return "refused:c:$crole&$cqual"; 
                   4406:             }
                   4407:         }
1.191     harris41 4408:     }
1.620     albertel 4409:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4410:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4411: 	        "rolesdef_$rolename=".
                   4412:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4413:     return reply($command,$env{'user.home'});
1.12      www      4414:   } else {
                   4415:     return 'refused';
                   4416:   }
1.105     harris41 4417: }
                   4418: 
                   4419: # ---------------- Make a metadata query against the network of library servers
                   4420: 
                   4421: sub metadata_query {
1.244     matthew  4422:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4423:     my %rhash;
1.845     albertel 4424:     my %libserv = &all_library();
1.244     matthew  4425:     my @server_list = (defined($server_array) ? @$server_array
                   4426:                                               : keys(%libserv) );
                   4427:     for my $server (@server_list) {
1.118     harris41 4428: 	unless ($custom or $customshow) {
                   4429: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4430: 	    $rhash{$server}=$reply;
                   4431: 	}
                   4432: 	else {
                   4433: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4434: 			     &escape($custom).':'.&escape($customshow),
                   4435: 			     $server);
                   4436: 	    $rhash{$server}=$reply;
                   4437: 	}
1.112     harris41 4438:     }
1.118     harris41 4439:     return \%rhash;
1.240     www      4440: }
                   4441: 
                   4442: # ----------------------------------------- Send log queries and wait for reply
                   4443: 
                   4444: sub log_query {
                   4445:     my ($uname,$udom,$query,%filters)=@_;
                   4446:     my $uhome=&homeserver($uname,$udom);
                   4447:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4448:     my $uhost=&hostname($uhome);
1.800     albertel 4449:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4450:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4451:                        $uhome);
1.479     albertel 4452:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4453:     return get_query_reply($queryid);
                   4454: }
                   4455: 
1.818     raeburn  4456: # -------------------------- Update MySQL table for portfolio file
                   4457: 
                   4458: sub update_portfolio_table {
1.821     raeburn  4459:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4460:     my $homeserver = &homeserver($uname,$udom);
                   4461:     my $queryid=
1.821     raeburn  4462:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4463:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4464:     my $reply = &get_query_reply($queryid);
                   4465:     return $reply;
                   4466: }
                   4467: 
1.899     raeburn  4468: # -------------------------- Update MySQL allusers table
                   4469: 
                   4470: sub update_allusers_table {
                   4471:     my ($uname,$udom,$names) = @_;
                   4472:     my $homeserver = &homeserver($uname,$udom);
                   4473:     my $queryid=
                   4474:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4475:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4476:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4477:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4478:                'generation='.&escape($names->{'generation'}).'%%'.
                   4479:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4480:                'id='.&escape($names->{'id'}),$homeserver);
                   4481:     my $reply = &get_query_reply($queryid);
                   4482:     return $reply;
                   4483: }
                   4484: 
1.508     raeburn  4485: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4486: 
                   4487: sub fetch_enrollment_query {
1.511     raeburn  4488:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4489:     my $homeserver;
1.547     raeburn  4490:     my $maxtries = 1;
1.508     raeburn  4491:     if ($context eq 'automated') {
                   4492:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4493:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4494:     } else {
                   4495:         $homeserver = &homeserver($cnum,$dom);
                   4496:     }
1.838     albertel 4497:     my $host=&hostname($homeserver);
1.506     raeburn  4498:     my $cmd = '';
1.800     albertel 4499:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4500:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4501:     }
                   4502:     $cmd =~ s/%%$//;
                   4503:     $cmd = &escape($cmd);
                   4504:     my $query = 'fetchenrollment';
1.620     albertel 4505:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4506:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4507:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4508:         return 'error: '.$queryid;
                   4509:     }
1.506     raeburn  4510:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4511:     my $tries = 1;
                   4512:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4513:         $reply = &get_query_reply($queryid);
                   4514:         $tries ++;
                   4515:     }
1.526     raeburn  4516:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4517:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4518:     } else {
1.901     albertel 4519:         my @responses = split(/:/,$reply);
1.515     raeburn  4520:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4521:             foreach my $line (@responses) {
                   4522:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4523:                 $$replyref{$key} = $value;
                   4524:             }
                   4525:         } else {
1.506     raeburn  4526:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4527:             foreach my $line (@responses) {
                   4528:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4529:                 $$replyref{$key} = $value;
                   4530:                 if ($value > 0) {
1.800     albertel 4531:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4532:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4533:                         my $destname = $pathname.'/'.$filename;
                   4534:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4535:                         if ($xml_classlist =~ /^error/) {
                   4536:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4537:                         } else {
1.506     raeburn  4538:                             if ( open(FILE,">$destname") ) {
                   4539:                                 print FILE &unescape($xml_classlist);
                   4540:                                 close(FILE);
1.526     raeburn  4541:                             } else {
                   4542:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4543:                             }
                   4544:                         }
                   4545:                     }
                   4546:                 }
                   4547:             }
                   4548:         }
                   4549:         return 'ok';
                   4550:     }
                   4551:     return 'error';
                   4552: }
                   4553: 
1.242     www      4554: sub get_query_reply {
                   4555:     my $queryid=shift;
1.240     www      4556:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4557:     my $reply='';
                   4558:     for (1..100) {
                   4559: 	sleep 2;
                   4560:         if (-e $replyfile.'.end') {
1.448     albertel 4561: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4562: 		$reply = join('',<$fh>);
                   4563: 		close($fh);
1.240     www      4564: 	   } else { return 'error: reply_file_error'; }
1.242     www      4565:            return &unescape($reply);
                   4566: 	}
1.240     www      4567:     }
1.242     www      4568:     return 'timeout:'.$queryid;
1.240     www      4569: }
                   4570: 
                   4571: sub courselog_query {
1.241     www      4572: #
                   4573: # possible filters:
                   4574: # url: url or symb
                   4575: # username
                   4576: # domain
                   4577: # action: view, submit, grade
                   4578: # start: timestamp
                   4579: # end: timestamp
                   4580: #
1.240     www      4581:     my (%filters)=@_;
1.620     albertel 4582:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4583:     if ($filters{'url'}) {
                   4584: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4585:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4586:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4587:     }
1.620     albertel 4588:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4589:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4590:     return &log_query($cname,$cdom,'courselog',%filters);
                   4591: }
                   4592: 
                   4593: sub userlog_query {
1.858     raeburn  4594: #
                   4595: # possible filters:
                   4596: # action: log check role
                   4597: # start: timestamp
                   4598: # end: timestamp
                   4599: #
1.240     www      4600:     my ($uname,$udom,%filters)=@_;
                   4601:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4602: }
                   4603: 
1.506     raeburn  4604: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4605: 
                   4606: sub auto_run {
1.508     raeburn  4607:     my ($cnum,$cdom) = @_;
1.876     raeburn  4608:     my $response = 0;
                   4609:     my $settings;
                   4610:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4611:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4612:         $settings = $domconfig{'autoenroll'};
                   4613:         if ($settings->{'run'} eq '1') {
                   4614:             $response = 1;
                   4615:         }
                   4616:     } else {
                   4617:         my $homeserver = &homeserver($cnum,$cdom);
                   4618:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4619:     }
1.506     raeburn  4620:     return $response;
                   4621: }
1.776     albertel 4622: 
1.506     raeburn  4623: sub auto_get_sections {
1.508     raeburn  4624:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4625:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4626:     my @secs = ();
1.511     raeburn  4627:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4628:     unless ($response eq 'refused') {
1.901     albertel 4629:         @secs = split(/:/,$response);
1.506     raeburn  4630:     }
                   4631:     return @secs;
                   4632: }
1.776     albertel 4633: 
1.506     raeburn  4634: sub auto_new_course {
1.508     raeburn  4635:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4636:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4637:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4638:     return $response;
                   4639: }
1.776     albertel 4640: 
1.506     raeburn  4641: sub auto_validate_courseID {
1.508     raeburn  4642:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4643:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4644:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4645:     return $response;
                   4646: }
1.776     albertel 4647: 
1.506     raeburn  4648: sub auto_create_password {
1.873     raeburn  4649:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4650:     my ($homeserver,$response);
1.506     raeburn  4651:     my $create_passwd = 0;
                   4652:     my $authchk = '';
1.873     raeburn  4653:     if ($udom =~ /^$match_domain$/) {
                   4654:         $homeserver = &domain($udom,'primary');
                   4655:     }
                   4656:     if ($homeserver eq '') {
                   4657:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4658:             $homeserver = &homeserver($cnum,$cdom);
                   4659:         }
                   4660:     }
                   4661:     if ($homeserver eq '') {
                   4662:         $authchk = 'nodomain';
1.506     raeburn  4663:     } else {
1.873     raeburn  4664:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4665:         if ($response eq 'refused') {
                   4666:             $authchk = 'refused';
                   4667:         } else {
1.901     albertel 4668:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4669:         }
1.506     raeburn  4670:     }
                   4671:     return ($authparam,$create_passwd,$authchk);
                   4672: }
                   4673: 
1.706     raeburn  4674: sub auto_photo_permission {
                   4675:     my ($cnum,$cdom,$students) = @_;
                   4676:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4677:     my ($outcome,$perm_reqd,$conditions) = 
                   4678: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4679:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4680: 	return (undef,undef);
                   4681:     }
1.706     raeburn  4682:     return ($outcome,$perm_reqd,$conditions);
                   4683: }
                   4684: 
                   4685: sub auto_checkphotos {
                   4686:     my ($uname,$udom,$pid) = @_;
                   4687:     my $homeserver = &homeserver($uname,$udom);
                   4688:     my ($result,$resulttype);
                   4689:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4690: 				   &escape($uname).':'.&escape($pid),
                   4691: 				   $homeserver));
1.709     albertel 4692:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4693: 	return (undef,undef);
                   4694:     }
1.706     raeburn  4695:     if ($outcome) {
                   4696:         ($result,$resulttype) = split(/:/,$outcome);
                   4697:     } 
                   4698:     return ($result,$resulttype);
                   4699: }
                   4700: 
                   4701: sub auto_photochoice {
                   4702:     my ($cnum,$cdom) = @_;
                   4703:     my $homeserver = &homeserver($cnum,$cdom);
                   4704:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4705: 						       &escape($cdom),
                   4706: 						       $homeserver)));
1.709     albertel 4707:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4708: 	return (undef,undef);
                   4709:     }
1.706     raeburn  4710:     return ($update,$comment);
                   4711: }
                   4712: 
                   4713: sub auto_photoupdate {
                   4714:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4715:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4716:     my $host=&hostname($homeserver);
1.706     raeburn  4717:     my $cmd = '';
                   4718:     my $maxtries = 1;
1.800     albertel 4719:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4720:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4721:     }
                   4722:     $cmd =~ s/%%$//;
                   4723:     $cmd = &escape($cmd);
                   4724:     my $query = 'institutionalphotos';
                   4725:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4726:     unless ($queryid=~/^\Q$host\E\_/) {
                   4727:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4728:         return 'error: '.$queryid;
                   4729:     }
                   4730:     my $reply = &get_query_reply($queryid);
                   4731:     my $tries = 1;
                   4732:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4733:         $reply = &get_query_reply($queryid);
                   4734:         $tries ++;
                   4735:     }
                   4736:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4737:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4738:     } else {
                   4739:         my @responses = split(/:/,$reply);
                   4740:         my $outcome = shift(@responses); 
                   4741:         foreach my $item (@responses) {
                   4742:             my ($key,$value) = split(/=/,$item);
                   4743:             $$photo{$key} = $value;
                   4744:         }
                   4745:         return $outcome;
                   4746:     }
                   4747:     return 'error';
                   4748: }
                   4749: 
1.521     raeburn  4750: sub auto_instcode_format {
1.793     albertel 4751:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4752: 	$cat_order) = @_;
1.521     raeburn  4753:     my $courses = '';
1.772     raeburn  4754:     my @homeservers;
1.521     raeburn  4755:     if ($caller eq 'global') {
1.841     albertel 4756: 	my %servers = &get_servers($codedom,'library');
                   4757: 	foreach my $tryserver (keys(%servers)) {
                   4758: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4759: 		push(@homeservers,$tryserver);
                   4760: 	    }
1.584     raeburn  4761:         }
1.521     raeburn  4762:     } else {
1.772     raeburn  4763:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4764:     }
1.793     albertel 4765:     foreach my $code (keys(%{$instcodes})) {
                   4766:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4767:     }
                   4768:     chop($courses);
1.772     raeburn  4769:     my $ok_response = 0;
                   4770:     my $response;
                   4771:     while (@homeservers > 0 && $ok_response == 0) {
                   4772:         my $server = shift(@homeservers); 
                   4773:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4774:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4775:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4776: 		split(/:/,$response);
1.772     raeburn  4777:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4778:             push(@{$codetitles},&str2array($codetitles_str));
                   4779:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4780:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4781:             $ok_response = 1;
                   4782:         }
                   4783:     }
                   4784:     if ($ok_response) {
1.521     raeburn  4785:         return 'ok';
1.772     raeburn  4786:     } else {
                   4787:         return $response;
1.521     raeburn  4788:     }
                   4789: }
                   4790: 
1.792     raeburn  4791: sub auto_instcode_defaults {
                   4792:     my ($domain,$returnhash,$code_order) = @_;
                   4793:     my @homeservers;
1.841     albertel 4794: 
                   4795:     my %servers = &get_servers($domain,'library');
                   4796:     foreach my $tryserver (keys(%servers)) {
                   4797: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4798: 	    push(@homeservers,$tryserver);
                   4799: 	}
1.792     raeburn  4800:     }
1.841     albertel 4801: 
1.792     raeburn  4802:     my $response;
1.841     albertel 4803:     foreach my $server (@homeservers) {
1.792     raeburn  4804:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4805:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4806: 	
                   4807: 	foreach my $pair (split(/\&/,$response)) {
                   4808: 	    my ($name,$value)=split(/\=/,$pair);
                   4809: 	    if ($name eq 'code_order') {
                   4810: 		@{$code_order} = split(/\&/,&unescape($value));
                   4811: 	    } else {
                   4812: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4813: 	    }
                   4814: 	}
                   4815: 	return 'ok';
1.792     raeburn  4816:     }
1.841     albertel 4817: 
                   4818:     return $response;
1.792     raeburn  4819: } 
                   4820: 
1.777     albertel 4821: sub auto_validate_class_sec {
1.773     raeburn  4822:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4823:     my $homeserver = &homeserver($cnum,$cdom);
                   4824:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4825:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4826:     return $response;
                   4827: }
                   4828: 
1.679     raeburn  4829: # ------------------------------------------------------- Course Group routines
                   4830: 
                   4831: sub get_coursegroups {
1.809     raeburn  4832:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4833:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4834: }
                   4835: 
1.679     raeburn  4836: sub modify_coursegroup {
                   4837:     my ($cdom,$cnum,$groupsettings) = @_;
                   4838:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4839: }
                   4840: 
1.809     raeburn  4841: sub toggle_coursegroup_status {
                   4842:     my ($cdom,$cnum,$group,$action) = @_;
                   4843:     my ($from_namespace,$to_namespace);
                   4844:     if ($action eq 'delete') {
                   4845:         $from_namespace = 'coursegroups';
                   4846:         $to_namespace = 'deleted_groups';
                   4847:     } else {
                   4848:         $from_namespace = 'deleted_groups';
                   4849:         $to_namespace = 'coursegroups';
                   4850:     }
                   4851:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4852:     if (my $tmp = &error(%curr_group)) {
                   4853:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4854:         return ('read error',$tmp);
                   4855:     } else {
                   4856:         my %savedsettings = %curr_group; 
1.809     raeburn  4857:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4858:         my $deloutcome;
                   4859:         if ($result eq 'ok') {
1.809     raeburn  4860:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4861:         } else {
                   4862:             return ('write error',$result);
                   4863:         }
                   4864:         if ($deloutcome eq 'ok') {
                   4865:             return 'ok';
                   4866:         } else {
                   4867:             return ('delete error',$deloutcome);
                   4868:         }
                   4869:     }
                   4870: }
                   4871: 
1.679     raeburn  4872: sub modify_group_roles {
                   4873:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4874:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4875:     my $role = 'gr/'.&escape($userprivs);
                   4876:     my ($uname,$udom) = split(/:/,$user);
                   4877:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4878:     if ($result eq 'ok') {
                   4879:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4880:     }
1.679     raeburn  4881:     return $result;
                   4882: }
                   4883: 
                   4884: sub modify_coursegroup_membership {
                   4885:     my ($cdom,$cnum,$membership) = @_;
                   4886:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4887:     return $result;
                   4888: }
                   4889: 
1.682     raeburn  4890: sub get_active_groups {
                   4891:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4892:     my $now = time;
                   4893:     my %groups = ();
                   4894:     foreach my $key (keys(%env)) {
1.811     albertel 4895:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4896:             my ($start,$end) = split(/\./,$env{$key});
                   4897:             if (($end!=0) && ($end<$now)) { next; }
                   4898:             if (($start!=0) && ($start>$now)) { next; }
                   4899:             if ($1 eq $cdom && $2 eq $cnum) {
                   4900:                 $groups{$3} = $env{$key} ;
                   4901:             }
                   4902:         }
                   4903:     }
                   4904:     return %groups;
                   4905: }
                   4906: 
1.683     raeburn  4907: sub get_group_membership {
                   4908:     my ($cdom,$cnum,$group) = @_;
                   4909:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4910: }
                   4911: 
                   4912: sub get_users_groups {
                   4913:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4914:     my @usersgroups;
1.683     raeburn  4915:     my $cachetime=1800;
                   4916: 
                   4917:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4918:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4919:     if (defined($cached)) {
1.734     albertel 4920:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4921:     } else {  
                   4922:         $grouplist = '';
1.816     raeburn  4923:         my $courseurl = &courseid_to_courseurl($courseid);
                   4924:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4925:         my $access_end = $env{'course.'.$courseid.
                   4926:                               '.default_enrollment_end_date'};
                   4927:         my $now = time;
                   4928:         foreach my $key (keys(%roleshash)) {
                   4929:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4930:                 my $group = $1;
                   4931:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4932:                     my $start = $2;
                   4933:                     my $end = $1;
                   4934:                     if ($start == -1) { next; } # deleted from group
                   4935:                     if (($start!=0) && ($start>$now)) { next; }
                   4936:                     if (($end!=0) && ($end<$now)) {
                   4937:                         if ($access_end && $access_end < $now) {
                   4938:                             if ($access_end - $end < 86400) {
                   4939:                                 push(@usersgroups,$group);
1.733     raeburn  4940:                             }
                   4941:                         }
1.817     raeburn  4942:                         next;
1.733     raeburn  4943:                     }
1.817     raeburn  4944:                     push(@usersgroups,$group);
1.683     raeburn  4945:                 }
                   4946:             }
                   4947:         }
1.817     raeburn  4948:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4949:         $grouplist = join(':',@usersgroups);
                   4950:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4951:     }
1.733     raeburn  4952:     return @usersgroups;
1.683     raeburn  4953: }
                   4954: 
                   4955: sub devalidate_getgroups_cache {
                   4956:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4957:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4958: 
1.683     raeburn  4959:     my $hashid="$udom:$uname:$courseid";
                   4960:     &devalidate_cache_new('getgroups',$hashid);
                   4961: }
                   4962: 
1.12      www      4963: # ------------------------------------------------------------------ Plain Text
                   4964: 
                   4965: sub plaintext {
1.742     raeburn  4966:     my ($short,$type,$cid) = @_;
1.758     albertel 4967:     if ($short =~ /^cr/) {
                   4968: 	return (split('/',$short))[-1];
                   4969:     }
1.742     raeburn  4970:     if (!defined($cid)) {
                   4971:         $cid = $env{'request.course.id'};
                   4972:     }
                   4973:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4974:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4975:                                           '.plaintext'});
                   4976:     }
                   4977:     my %rolenames = (
                   4978:                       Course => 'std',
                   4979:                       Group => 'alt1',
                   4980:                     );
                   4981:     if (defined($type) && 
                   4982:          defined($rolenames{$type}) && 
                   4983:          defined($prp{$short}{$rolenames{$type}})) {
                   4984:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4985:     } else {
                   4986:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4987:     }
1.12      www      4988: }
                   4989: 
                   4990: # ----------------------------------------------------------------- Assign Role
                   4991: 
                   4992: sub assignrole {
1.357     www      4993:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4994:     my $mrole;
                   4995:     if ($role =~ /^cr\//) {
1.393     www      4996:         my $cwosec=$url;
1.811     albertel 4997:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4998: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4999:            &logthis('Refused custom assignrole: '.
                   5000:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5001: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5002:            return 'refused'; 
                   5003:         }
1.21      www      5004:         $mrole='cr';
1.678     raeburn  5005:     } elsif ($role =~ /^gr\//) {
                   5006:         my $cwogrp=$url;
1.811     albertel 5007:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5008:         unless (&allowed('mdg',$cwogrp)) {
                   5009:             &logthis('Refused group assignrole: '.
                   5010:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5011:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5012:             return 'refused';
                   5013:         }
                   5014:         $mrole='gr';
1.21      www      5015:     } else {
1.82      www      5016:         my $cwosec=$url;
1.811     albertel 5017:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5018:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5019:            &logthis('Refused assignrole: '.
                   5020:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5021: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5022:            return 'refused'; 
                   5023:         }
1.21      www      5024:         $mrole=$role;
                   5025:     }
1.620     albertel 5026:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5027:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5028:     if ($end) { $command.='_'.$end; }
1.21      www      5029:     if ($start) {
                   5030: 	if ($end) { 
1.81      www      5031:            $command.='_'.$start; 
1.21      www      5032:         } else {
1.81      www      5033:            $command.='_0_'.$start;
1.21      www      5034:         }
                   5035:     }
1.739     raeburn  5036:     my $origstart = $start;
                   5037:     my $origend = $end;
1.357     www      5038: # actually delete
                   5039:     if ($deleteflag) {
1.373     www      5040: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5041: # modify command to delete the role
1.620     albertel 5042:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5043:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5044: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5045: # set start and finish to negative values for userrolelog
                   5046:            $start=-1;
                   5047:            $end=-1;
                   5048:         }
                   5049:     }
                   5050: # send command
1.349     www      5051:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5052: # log new user role if status is ok
1.349     www      5053:     if ($answer eq 'ok') {
1.663     raeburn  5054: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5055: # for course roles, perform group memberships changes triggered by role change.
                   5056:         unless ($role =~ /^gr/) {
                   5057:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5058:                                              $origstart);
                   5059:         }
1.349     www      5060:     }
                   5061:     return $answer;
1.169     harris41 5062: }
                   5063: 
                   5064: # -------------------------------------------------- Modify user authentication
1.197     www      5065: # Overrides without validation
                   5066: 
1.169     harris41 5067: sub modifyuserauth {
                   5068:     my ($udom,$uname,$umode,$upass)=@_;
                   5069:     my $uhome=&homeserver($uname,$udom);
1.197     www      5070:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5071:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5072:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5073:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5074:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5075: 		     &escape($upass),$uhome);
1.620     albertel 5076:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5077:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5078:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5079:     &log($udom,,$uname,$uhome,
1.620     albertel 5080:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5081:                                      $env{'user.name'}.', '.$umode.
1.197     www      5082:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5083:     unless ($reply eq 'ok') {
1.197     www      5084:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5085: 	return 'error: '.$reply;
                   5086:     }   
1.170     harris41 5087:     return 'ok';
1.80      www      5088: }
                   5089: 
1.81      www      5090: # --------------------------------------------------------------- Modify a user
1.80      www      5091: 
1.81      www      5092: sub modifyuser {
1.206     matthew  5093:     my ($udom,    $uname, $uid,
                   5094:         $umode,   $upass, $first,
                   5095:         $middle,  $last,  $gene,
1.387     www      5096:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5097:     $udom= &LONCAPA::clean_domain($udom);
                   5098:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5099:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5100:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5101: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5102:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5103:                                      ' desiredhome not specified'). 
1.620     albertel 5104:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5105:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5106:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5107: # ----------------------------------------------------------------- Create User
1.406     albertel 5108:     if (($uhome eq 'no_host') && 
                   5109: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5110:         my $unhome='';
1.844     albertel 5111:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5112:             $unhome = $desiredhome;
1.620     albertel 5113: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5114: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5115:         } else { # load balancing routine for determining $unhome
1.81      www      5116:             my $loadm=10000000;
1.841     albertel 5117: 	    my %servers = &get_servers($udom,'library');
                   5118: 	    foreach my $tryserver (keys(%servers)) {
                   5119: 		my $answer=reply('load',$tryserver);
                   5120: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5121: 		    $loadm=$answer;
                   5122: 		    $unhome=$tryserver;
                   5123: 		}
1.80      www      5124: 	    }
                   5125:         }
                   5126:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5127: 	    return 'error: unable to find a home server for '.$uname.
                   5128:                    ' in domain '.$udom;
1.80      www      5129:         }
                   5130:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5131:                          &escape($upass),$unhome);
                   5132: 	unless ($reply eq 'ok') {
                   5133:             return 'error: '.$reply;
                   5134:         }   
1.230     stredwic 5135:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5136:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5137: 	    return 'error: unable verify users home machine.';
1.80      www      5138:         }
1.209     matthew  5139:     }   # End of creation of new user
1.80      www      5140: # ---------------------------------------------------------------------- Add ID
                   5141:     if ($uid) {
                   5142:        $uid=~tr/A-Z/a-z/;
                   5143:        my %uidhash=&idrget($udom,$uname);
1.196     www      5144:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5145:          && (!$forceid)) {
1.80      www      5146: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5147: 	      return 'error: user id "'.$uid.'" does not match '.
                   5148:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5149:           }
                   5150:        } else {
                   5151: 	  &idput($udom,($uname => $uid));
                   5152:        }
                   5153:     }
                   5154: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5155:     my @tmp=&get('environment',
1.899     raeburn  5156: 		   ['firstname','middlename','lastname','generation','id',
                   5157:                     'permanentemail'],
1.134     albertel 5158: 		   $udom,$uname);
1.313     matthew  5159:     my %names;
                   5160:     if ($tmp[0] =~ m/^error:.*/) { 
                   5161:         %names=(); 
                   5162:     } else {
                   5163:         %names = @tmp;
                   5164:     }
1.388     www      5165: #
                   5166: # Make sure to not trash student environment if instructor does not bother
                   5167: # to supply name and email information
                   5168: #
                   5169:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5170:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5171:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5172:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5173:     if ($email) {
                   5174:        $email=~s/[^\w\@\.\-\,]//gs;
                   5175:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5176: 			   $names{'critnotification'} = $email;
                   5177: 			   $names{'permanentemail'} = $email; }
                   5178:     }
1.899     raeburn  5179:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5180:     my $reply = &put('environment', \%names, $udom,$uname);
                   5181:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5182:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5183:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5184:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5185:              $umode.', '.$first.', '.$middle.', '.
                   5186: 	     $last.', '.$gene.' by '.
1.620     albertel 5187:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5188:     return 'ok';
1.80      www      5189: }
                   5190: 
1.81      www      5191: # -------------------------------------------------------------- Modify student
1.80      www      5192: 
1.81      www      5193: sub modifystudent {
                   5194:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5195:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5196:     if (!$cid) {
1.620     albertel 5197: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5198: 	    return 'not_in_class';
                   5199: 	}
1.80      www      5200:     }
                   5201: # --------------------------------------------------------------- Make the user
1.81      www      5202:     my $reply=&modifyuser
1.209     matthew  5203: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5204:          $desiredhome,$email);
1.80      www      5205:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5206:     # This will cause &modify_student_enrollment to get the uid from the
                   5207:     # students environment
                   5208:     $uid = undef if (!$forceid);
1.455     albertel 5209:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5210: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5211:     return $reply;
                   5212: }
                   5213: 
                   5214: sub modify_student_enrollment {
1.515     raeburn  5215:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5216:     my ($cdom,$cnum,$chome);
                   5217:     if (!$cid) {
1.620     albertel 5218: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5219: 	    return 'not_in_class';
                   5220: 	}
1.620     albertel 5221: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5222: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5223:     } else {
                   5224: 	($cdom,$cnum)=split(/_/,$cid);
                   5225:     }
1.620     albertel 5226:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5227:     if (!$chome) {
1.457     raeburn  5228: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5229:     }
1.455     albertel 5230:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5231:     # Make sure the user exists
1.81      www      5232:     my $uhome=&homeserver($uname,$udom);
                   5233:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5234: 	return 'error: no such user';
                   5235:     }
1.297     matthew  5236:     # Get student data if we were not given enough information
                   5237:     if (!defined($first)  || $first  eq '' || 
                   5238:         !defined($last)   || $last   eq '' || 
                   5239:         !defined($uid)    || $uid    eq '' || 
                   5240:         !defined($middle) || $middle eq '' || 
                   5241:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5242:         # They did not supply us with enough data to enroll the student, so
                   5243:         # we need to pick up more information.
1.297     matthew  5244:         my %tmp = &get('environment',
1.294     matthew  5245:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5246:                        ,$udom,$uname);
                   5247: 
1.800     albertel 5248:         #foreach my $key (keys(%tmp)) {
                   5249:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5250:         #}
1.294     matthew  5251:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5252:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5253:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5254:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5255:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5256:     }
1.556     albertel 5257:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5258:     my $reply=cput('classlist',
                   5259: 		   {"$uname:$udom" => 
1.515     raeburn  5260: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5261: 		   $cdom,$cnum);
1.81      www      5262:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5263: 	return 'error: '.$reply;
1.652     albertel 5264:     } else {
                   5265: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5266:     }
1.297     matthew  5267:     # Add student role to user
1.83      www      5268:     my $uurl='/'.$cid;
1.81      www      5269:     $uurl=~s/\_/\//g;
                   5270:     if ($usec) {
                   5271: 	$uurl.='/'.$usec;
                   5272:     }
                   5273:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5274: }
                   5275: 
1.556     albertel 5276: sub format_name {
                   5277:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5278:     my $name;
                   5279:     if ($first ne 'lastname') {
                   5280: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5281:     } else {
                   5282: 	if ($lastname=~/\S/) {
                   5283: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5284: 	    $name=~s/\s+,/,/;
                   5285: 	} else {
                   5286: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5287: 	}
                   5288:     }
                   5289:     $name=~s/^\s+//;
                   5290:     $name=~s/\s+$//;
                   5291:     $name=~s/\s+/ /g;
                   5292:     return $name;
                   5293: }
                   5294: 
1.84      www      5295: # ------------------------------------------------- Write to course preferences
                   5296: 
                   5297: sub writecoursepref {
                   5298:     my ($courseid,%prefs)=@_;
                   5299:     $courseid=~s/^\///;
                   5300:     $courseid=~s/\_/\//g;
                   5301:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5302:     my $chome=homeserver($cnum,$cdomain);
                   5303:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5304: 	return 'error: no such course';
                   5305:     }
                   5306:     my $cstring='';
1.800     albertel 5307:     foreach my $pref (keys(%prefs)) {
                   5308: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5309:     }
1.84      www      5310:     $cstring=~s/\&$//;
                   5311:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5312: }
                   5313: 
                   5314: # ---------------------------------------------------------- Make/modify course
                   5315: 
                   5316: sub createcourse {
1.741     raeburn  5317:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5318:         $course_owner,$crstype)=@_;
1.84      www      5319:     $url=&declutter($url);
                   5320:     my $cid='';
1.264     matthew  5321:     unless (&allowed('ccc',$udom)) {
1.84      www      5322:         return 'refused';
                   5323:     }
                   5324: # ------------------------------------------------------------------- Create ID
1.674     www      5325:    my $uname=int(1+rand(9)).
                   5326:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5327:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5328:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5329: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5330:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5331:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5332:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5333:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5334:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5335:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5336:            return 'error: unable to generate unique course-ID';
                   5337:        } 
                   5338:    }
1.264     matthew  5339: # ------------------------------------------------ Check supplied server name
1.620     albertel 5340:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5341:     if (! &is_library($course_server)) {
1.264     matthew  5342:         return 'error:bad server name '.$course_server;
                   5343:     }
1.84      www      5344: # ------------------------------------------------------------- Make the course
                   5345:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5346:                       $course_server);
1.84      www      5347:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5348:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5349:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5350: 	return 'error: no such course';
                   5351:     }
1.271     www      5352: # ----------------------------------------------------------------- Course made
1.516     raeburn  5353: # log existence
                   5354:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5355:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5356:                   &escape($crstype),$uhome);
1.358     www      5357:     &flushcourselogs();
                   5358: # set toplevel url
1.271     www      5359:     my $topurl=$url;
                   5360:     unless ($nonstandard) {
                   5361: # ------------------------------------------ For standard courses, make top url
                   5362:         my $mapurl=&clutter($url);
1.278     www      5363:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5364:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5365: <map>
                   5366: <resource id="1" type="start"></resource>
                   5367: <resource id="2" src="$mapurl"></resource>
                   5368: <resource id="3" type="finish"></resource>
                   5369: <link index="1" from="1" to="2"></link>
                   5370: <link index="2" from="2" to="3"></link>
                   5371: </map>
                   5372: ENDINITMAP
                   5373:         $topurl=&declutter(
1.638     albertel 5374:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5375:                           );
                   5376:     }
                   5377: # ----------------------------------------------------------- Write preferences
1.84      www      5378:     &writecoursepref($udom.'_'.$uname,
                   5379:                      ('description' => $description,
1.271     www      5380:                       'url'         => $topurl));
1.84      www      5381:     return '/'.$udom.'/'.$uname;
                   5382: }
                   5383: 
1.813     albertel 5384: sub is_course {
                   5385:     my ($cdom,$cnum) = @_;
                   5386:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5387: 				undef,'.');
                   5388:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5389:         return 1;
                   5390:     }
                   5391:     return 0;
                   5392: }
                   5393: 
1.21      www      5394: # ---------------------------------------------------------- Assign Custom Role
                   5395: 
                   5396: sub assigncustomrole {
1.357     www      5397:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5398:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5399:                        $end,$start,$deleteflag);
1.21      www      5400: }
                   5401: 
                   5402: # ----------------------------------------------------------------- Revoke Role
                   5403: 
                   5404: sub revokerole {
1.357     www      5405:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5406:     my $now=time;
1.357     www      5407:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5408: }
                   5409: 
                   5410: # ---------------------------------------------------------- Revoke Custom Role
                   5411: 
                   5412: sub revokecustomrole {
1.357     www      5413:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5414:     my $now=time;
1.357     www      5415:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5416:            $deleteflag);
1.17      www      5417: }
                   5418: 
1.533     banghart 5419: # ------------------------------------------------------------ Disk usage
1.535     albertel 5420: sub diskusage {
1.533     banghart 5421:     my ($udom,$uname,$directoryRoot)=@_;
                   5422:     $directoryRoot =~ s/\/$//;
1.535     albertel 5423:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5424:     return $listing;
1.512     banghart 5425: }
                   5426: 
1.566     banghart 5427: sub is_locked {
                   5428:     my ($file_name, $domain, $user) = @_;
                   5429:     my @check;
                   5430:     my $is_locked;
                   5431:     push @check, $file_name;
1.613     albertel 5432:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5433: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5434:     my ($tmp)=keys(%locked);
                   5435:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5436:     
1.566     banghart 5437:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5438:         $is_locked = 'false';
                   5439:         foreach my $entry (@{$locked{$file_name}}) {
                   5440:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5441:                $is_locked = 'true';
                   5442:                last;
1.745     raeburn  5443:            }
                   5444:        }
1.566     banghart 5445:     } else {
                   5446:         $is_locked = 'false';
                   5447:     }
                   5448: }
                   5449: 
1.759     albertel 5450: sub declutter_portfile {
                   5451:     my ($file) = @_;
1.833     albertel 5452:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5453:     return $file;
                   5454: }
                   5455: 
1.559     banghart 5456: # ------------------------------------------------------------- Mark as Read Only
                   5457: 
                   5458: sub mark_as_readonly {
                   5459:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5460:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5461:     my ($tmp)=keys(%current_permissions);
                   5462:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5463:     foreach my $file (@{$files}) {
1.759     albertel 5464: 	$file = &declutter_portfile($file);
1.561     banghart 5465:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5466:     }
1.613     albertel 5467:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5468:     return;
                   5469: }
                   5470: 
1.572     banghart 5471: # ------------------------------------------------------------Save Selected Files
                   5472: 
                   5473: sub save_selected_files {
                   5474:     my ($user, $path, @files) = @_;
                   5475:     my $filename = $user."savedfiles";
1.573     banghart 5476:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5477:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5478:     foreach my $file (@files) {
1.620     albertel 5479:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5480:     }
                   5481:     foreach my $file (@other_files) {
1.574     banghart 5482:         print (OUT $file."\n");
1.572     banghart 5483:     }
1.574     banghart 5484:     close (OUT);
1.572     banghart 5485:     return 'ok';
                   5486: }
                   5487: 
1.574     banghart 5488: sub clear_selected_files {
                   5489:     my ($user) = @_;
                   5490:     my $filename = $user."savedfiles";
                   5491:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5492:     print (OUT undef);
                   5493:     close (OUT);
                   5494:     return ("ok");    
                   5495: }
                   5496: 
1.572     banghart 5497: sub files_in_path {
                   5498:     my ($user, $path) = @_;
                   5499:     my $filename = $user."savedfiles";
                   5500:     my %return_files;
1.574     banghart 5501:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5502:     while (my $line_in = <IN>) {
1.574     banghart 5503:         chomp ($line_in);
                   5504:         my @paths_and_file = split (m!/!, $line_in);
                   5505:         my $file_part = pop (@paths_and_file);
                   5506:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5507:         $path_part.='/';
                   5508:         my $path_and_file = $path_part.$file_part;
                   5509:         if ($path_part eq $path) {
                   5510:             $return_files{$file_part}= 'selected';
                   5511:         }
                   5512:     }
1.574     banghart 5513:     close (IN);
                   5514:     return (\%return_files);
1.572     banghart 5515: }
                   5516: 
                   5517: # called in portfolio select mode, to show files selected NOT in current directory
                   5518: sub files_not_in_path {
                   5519:     my ($user, $path) = @_;
                   5520:     my $filename = $user."savedfiles";
                   5521:     my @return_files;
                   5522:     my $path_part;
1.800     albertel 5523:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5524:     while (my $line = <IN>) {
1.572     banghart 5525:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5526:         my @paths_and_file = split(m|/|, $line);
                   5527:         my $file_part = pop(@paths_and_file);
                   5528:         chomp($file_part);
                   5529:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5530:         $path_part .= '/';
                   5531:         my $path_and_file = $path_part.$file_part;
                   5532:         if ($path_part ne $path) {
1.800     albertel 5533:             push(@return_files, ($path_and_file));
1.572     banghart 5534:         }
                   5535:     }
1.800     albertel 5536:     close(OUT);
1.574     banghart 5537:     return (@return_files);
1.572     banghart 5538: }
                   5539: 
1.745     raeburn  5540: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5541: 
1.745     raeburn  5542: sub get_portfile_permissions {
                   5543:     my ($domain,$user) = @_;
1.613     albertel 5544:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5545:     my ($tmp)=keys(%current_permissions);
                   5546:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5547:     return \%current_permissions;
                   5548: }
                   5549: 
                   5550: #---------------------------------------------Get portfolio file access controls
                   5551: 
1.749     raeburn  5552: sub get_access_controls {
1.745     raeburn  5553:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5554:     my %access;
                   5555:     my $real_file = $file;
                   5556:     $file =~ s/\.meta$//;
1.745     raeburn  5557:     if (defined($file)) {
1.749     raeburn  5558:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5559:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5560:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5561:             }
                   5562:         }
1.745     raeburn  5563:     } else {
1.749     raeburn  5564:         foreach my $key (keys(%{$current_permissions})) {
                   5565:             if ($key =~ /\0accesscontrol$/) {
                   5566:                 if (defined($group)) {
                   5567:                     if ($key !~ m-^\Q$group\E/-) {
                   5568:                         next;
                   5569:                     }
                   5570:                 }
                   5571:                 my ($fullpath) = split(/\0/,$key);
                   5572:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5573:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5574:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5575:                     }
                   5576:                 }
                   5577:             }
                   5578:         }
                   5579:     }
                   5580:     return %access;
                   5581: }
                   5582: 
                   5583: sub modify_access_controls {
                   5584:     my ($file_name,$changes,$domain,$user)=@_;
                   5585:     my ($outcome,$deloutcome);
                   5586:     my %store_permissions;
                   5587:     my %new_values;
                   5588:     my %new_control;
                   5589:     my %translation;
                   5590:     my @deletions = ();
                   5591:     my $now = time;
                   5592:     if (exists($$changes{'activate'})) {
                   5593:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5594:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5595:             my $numnew = scalar(@newitems);
                   5596:             for (my $i=0; $i<$numnew; $i++) {
                   5597:                 my $newkey = $newitems[$i];
                   5598:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5599:                 if ($newkey =~ /^\d+:/) { 
                   5600:                     $newkey =~ s/^(\d+)/$newid/;
                   5601:                     $translation{$1} = $newid;
                   5602:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5603:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5604:                     $translation{$1} = $newid;
                   5605:                 }
1.749     raeburn  5606:                 $new_values{$file_name."\0".$newkey} = 
                   5607:                                           $$changes{'activate'}{$newitems[$i]};
                   5608:                 $new_control{$newkey} = $now;
                   5609:             }
                   5610:         }
                   5611:     }
                   5612:     my %todelete;
                   5613:     my %changed_items;
                   5614:     foreach my $action ('delete','update') {
                   5615:         if (exists($$changes{$action})) {
                   5616:             if (ref($$changes{$action}) eq 'HASH') {
                   5617:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5618:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5619:                     if ($action eq 'delete') { 
                   5620:                         $todelete{$itemnum} = 1;
                   5621:                     } else {
                   5622:                         $changed_items{$itemnum} = $key;
                   5623:                     }
                   5624:                 }
1.745     raeburn  5625:             }
                   5626:         }
1.749     raeburn  5627:     }
                   5628:     # get lock on access controls for file.
                   5629:     my $lockhash = {
                   5630:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5631:                                                        ':'.$env{'user.domain'},
                   5632:                    }; 
                   5633:     my $tries = 0;
                   5634:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5635:    
                   5636:     while (($gotlock ne 'ok') && $tries <3) {
                   5637:         $tries ++;
                   5638:         sleep 1;
                   5639:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5640:     }
                   5641:     if ($gotlock eq 'ok') {
                   5642:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5643:         my ($tmp)=keys(%curr_permissions);
                   5644:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5645:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5646:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5647:             if (ref($curr_controls) eq 'HASH') {
                   5648:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5649:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5650:                     if (defined($todelete{$itemnum})) {
                   5651:                         push(@deletions,$file_name."\0".$control_item);
                   5652:                     } else {
                   5653:                         if (defined($changed_items{$itemnum})) {
                   5654:                             $new_control{$changed_items{$itemnum}} = $now;
                   5655:                             push(@deletions,$file_name."\0".$control_item);
                   5656:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5657:                         } else {
                   5658:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5659:                         }
                   5660:                     }
1.745     raeburn  5661:                 }
                   5662:             }
                   5663:         }
1.749     raeburn  5664:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5665:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5666:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5667:         #  remove lock
                   5668:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5669:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5670:         my ($file,$group);
                   5671:         if (&is_course($domain,$user)) {
                   5672:             ($group,$file) = split(/\//,$file_name,2);
                   5673:         } else {
                   5674:             $file = $file_name;
                   5675:         }
                   5676:         my $sqlresult =
                   5677:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5678:                                     $group);
1.749     raeburn  5679:     } else {
                   5680:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5681:     }
1.749     raeburn  5682:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5683: }
                   5684: 
1.827     raeburn  5685: sub make_public_indefinitely {
                   5686:     my ($requrl) = @_;
                   5687:     my $now = time;
                   5688:     my $action = 'activate';
                   5689:     my $aclnum = 0;
                   5690:     if (&is_portfolio_url($requrl)) {
                   5691:         my (undef,$udom,$unum,$file_name,$group) =
                   5692:             &parse_portfolio_url($requrl);
                   5693:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5694:         my %access_controls = &get_access_controls($current_perms,
                   5695:                                                    $group,$file_name);
                   5696:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5697:             my ($num,$scope,$end,$start) = 
                   5698:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5699:             if ($scope eq 'public') {
                   5700:                 if ($start <= $now && $end == 0) {
                   5701:                     $action = 'none';
                   5702:                 } else {
                   5703:                     $action = 'update';
                   5704:                     $aclnum = $num;
                   5705:                 }
                   5706:                 last;
                   5707:             }
                   5708:         }
                   5709:         if ($action eq 'none') {
                   5710:              return 'ok';
                   5711:         } else {
                   5712:             my %changes;
                   5713:             my $newend = 0;
                   5714:             my $newstart = $now;
                   5715:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5716:             $changes{$action}{$newkey} = {
                   5717:                 type => 'public',
                   5718:                 time => {
                   5719:                     start => $newstart,
                   5720:                     end   => $newend,
                   5721:                 },
                   5722:             };
                   5723:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5724:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5725:             return $outcome;
                   5726:         }
                   5727:     } else {
                   5728:         return 'invalid';
                   5729:     }
                   5730: }
                   5731: 
1.745     raeburn  5732: #------------------------------------------------------Get Marked as Read Only
                   5733: 
                   5734: sub get_marked_as_readonly {
                   5735:     my ($domain,$user,$what,$group) = @_;
                   5736:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5737:     my @readonly_files;
1.629     banghart 5738:     my $cmp1=$what;
                   5739:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5740:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5741:         if (defined($group)) {
                   5742:             if ($file_name !~ m-^\Q$group\E/-) {
                   5743:                 next;
                   5744:             }
                   5745:         }
1.561     banghart 5746:         if (ref($value) eq "ARRAY"){
                   5747:             foreach my $stored_what (@{$value}) {
1.629     banghart 5748:                 my $cmp2=$stored_what;
1.759     albertel 5749:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5750:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5751:                 }
1.629     banghart 5752:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5753:                     push(@readonly_files, $file_name);
1.745     raeburn  5754:                     last;
1.563     banghart 5755:                 } elsif (!defined($what)) {
                   5756:                     push(@readonly_files, $file_name);
1.745     raeburn  5757:                     last;
1.561     banghart 5758:                 }
                   5759:             }
1.745     raeburn  5760:         }
1.561     banghart 5761:     }
                   5762:     return @readonly_files;
                   5763: }
1.577     banghart 5764: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5765: 
1.577     banghart 5766: sub get_marked_as_readonly_hash {
1.745     raeburn  5767:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5768:     my %readonly_files;
1.745     raeburn  5769:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5770:         if (defined($group)) {
                   5771:             if ($file_name !~ m-^\Q$group\E/-) {
                   5772:                 next;
                   5773:             }
                   5774:         }
1.577     banghart 5775:         if (ref($value) eq "ARRAY"){
                   5776:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5777:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5778:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5779:                         if ($lock_descriptor eq 'graded') {
                   5780:                             $readonly_files{$file_name} = 'graded';
                   5781:                         } elsif ($lock_descriptor eq 'handback') {
                   5782:                             $readonly_files{$file_name} = 'handback';
                   5783:                         } else {
                   5784:                             if (!exists($readonly_files{$file_name})) {
                   5785:                                 $readonly_files{$file_name} = 'locked';
                   5786:                             }
                   5787:                         }
1.745     raeburn  5788:                     }
1.750     banghart 5789:                 } 
1.577     banghart 5790:             }
                   5791:         } 
                   5792:     }
                   5793:     return %readonly_files;
                   5794: }
1.559     banghart 5795: # ------------------------------------------------------------ Unmark as Read Only
                   5796: 
                   5797: sub unmark_as_readonly {
1.629     banghart 5798:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5799:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5800:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5801:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5802:     my $symb_crs = $what;
                   5803:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5804:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5805:     my ($tmp)=keys(%current_permissions);
                   5806:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5807:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5808:     foreach my $file (@readonly_files) {
1.759     albertel 5809: 	my $clean_file = &declutter_portfile($file);
                   5810: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5811: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5812:         my @new_locks;
                   5813:         my @del_keys;
                   5814:         if (ref($current_locks) eq "ARRAY"){
                   5815:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5816:                 my $compare=$locker;
1.749     raeburn  5817:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5818:                     $compare=join('',@{$locker});
1.746     raeburn  5819:                     if ($compare ne $symb_crs) {
                   5820:                         push(@new_locks, $locker);
                   5821:                     }
1.563     banghart 5822:                 }
                   5823:             }
1.650     albertel 5824:             if (scalar(@new_locks) > 0) {
1.563     banghart 5825:                 $current_permissions{$file} = \@new_locks;
                   5826:             } else {
                   5827:                 push(@del_keys, $file);
1.613     albertel 5828:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5829:                 delete($current_permissions{$file});
1.563     banghart 5830:             }
                   5831:         }
1.561     banghart 5832:     }
1.613     albertel 5833:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5834:     return;
                   5835: }
1.512     banghart 5836: 
1.17      www      5837: # ------------------------------------------------------------ Directory lister
                   5838: 
                   5839: sub dirlist {
1.253     stredwic 5840:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5841: 
1.18      www      5842:     $uri=~s/^\///;
                   5843:     $uri=~s/\/$//;
1.253     stredwic 5844:     my ($udom, $uname);
                   5845:     (undef,$udom,$uname)=split(/\//,$uri);
                   5846:     if(defined($userdomain)) {
                   5847:         $udom = $userdomain;
                   5848:     }
                   5849:     if(defined($username)) {
                   5850:         $uname = $username;
                   5851:     }
                   5852: 
                   5853:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5854:     if(defined($alternateDirectoryRoot)) {
                   5855:         $dirRoot = $alternateDirectoryRoot;
                   5856:         $dirRoot =~ s/\/$//;
1.751     banghart 5857:     }
1.253     stredwic 5858: 
                   5859:     if($udom) {
                   5860:         if($uname) {
1.800     albertel 5861:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5862: 				 &homeserver($uname,$udom));
1.605     matthew  5863:             my @listing_results;
                   5864:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5865:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5866: 				  &homeserver($uname,$udom));
1.605     matthew  5867:                 @listing_results = split(/:/,$listing);
                   5868:             } else {
                   5869:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5870:             }
                   5871:             return @listing_results;
1.253     stredwic 5872:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5873:             my %allusers;
1.841     albertel 5874: 	    my %servers = &get_servers($udom,'library');
                   5875: 	    foreach my $tryserver (keys(%servers)) {
                   5876: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5877: 				     $udom, $tryserver);
                   5878: 		my @listing_results;
                   5879: 		if ($listing eq 'unknown_cmd') {
                   5880: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5881: 				      $udom, $tryserver);
                   5882: 		    @listing_results = split(/:/,$listing);
                   5883: 		} else {
                   5884: 		    @listing_results =
                   5885: 			map { &unescape($_); } split(/:/,$listing);
                   5886: 		}
                   5887: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5888: 		    $listing_results[0] ne 'empty'       &&
                   5889: 		    $listing_results[0] ne 'con_lost') {
                   5890: 		    foreach my $line (@listing_results) {
                   5891: 			my ($entry) = split(/&/,$line,2);
                   5892: 			$allusers{$entry} = 1;
                   5893: 		    }
                   5894: 		}
1.253     stredwic 5895:             }
                   5896:             my $alluserstr='';
1.800     albertel 5897:             foreach my $user (sort(keys(%allusers))) {
                   5898:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5899:             }
                   5900:             $alluserstr=~s/:$//;
                   5901:             return split(/:/,$alluserstr);
                   5902:         } else {
1.800     albertel 5903:             return ('missing user name');
1.253     stredwic 5904:         }
                   5905:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5906:         my @all_domains = sort(&all_domains());
                   5907:          foreach my $domain (@all_domains) {
                   5908:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5909:          }
                   5910:          return @all_domains;
                   5911:      } else {
1.800     albertel 5912:         return ('missing domain');
1.275     stredwic 5913:     }
                   5914: }
                   5915: 
                   5916: # --------------------------------------------- GetFileTimestamp
                   5917: # This function utilizes dirlist and returns the date stamp for
                   5918: # when it was last modified.  It will also return an error of -1
                   5919: # if an error occurs
                   5920: 
1.410     matthew  5921: ##
                   5922: ## FIXME: This subroutine assumes its caller knows something about the
                   5923: ## directory structure of the home server for the student ($root).
                   5924: ## Not a good assumption to make.  Since this is for looking up files
                   5925: ## in user directories, the full path should be constructed by lond, not
                   5926: ## whatever machine we request data from.
                   5927: ##
1.275     stredwic 5928: sub GetFileTimestamp {
                   5929:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5930:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5931:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5932:     my $subdir=$studentName.'__';
                   5933:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5934:     my $proname="$studentDomain/$subdir/$studentName";
                   5935:     $proname .= '/'.$filename;
1.375     matthew  5936:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5937:                                               $studentName, $root);
1.275     stredwic 5938:     my @stats = split('&', $fileStat);
                   5939:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5940:         # @stats contains first the filename, then the stat output
                   5941:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5942:     } else {
                   5943:         return -1;
1.253     stredwic 5944:     }
1.26      www      5945: }
                   5946: 
1.712     albertel 5947: sub stat_file {
                   5948:     my ($uri) = @_;
1.787     albertel 5949:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5950: 
1.712     albertel 5951:     my ($udom,$uname,$file,$dir);
                   5952:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5953: 	($udom,$uname,$file) =
1.811     albertel 5954: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5955: 	$file = 'userfiles/'.$file;
1.740     www      5956: 	$dir = &propath($udom,$uname);
1.712     albertel 5957:     }
                   5958:     if ($uri =~ m-^/res/-) {
                   5959: 	($udom,$uname) = 
1.807     albertel 5960: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5961: 	$file = $uri;
                   5962:     }
                   5963: 
                   5964:     if (!$udom || !$uname || !$file) {
                   5965: 	# unable to handle the uri
                   5966: 	return ();
                   5967:     }
                   5968: 
                   5969:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5970:     my @stats = split('&', $result);
1.721     banghart 5971:     
1.712     albertel 5972:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5973: 	shift(@stats); #filename is first
                   5974: 	return @stats;
                   5975:     }
                   5976:     return ();
                   5977: }
                   5978: 
1.26      www      5979: # -------------------------------------------------------- Value of a Condition
                   5980: 
1.713     albertel 5981: # gets the value of a specific preevaluated condition
                   5982: #    stored in the string  $env{user.state.<cid>}
                   5983: # or looks up a condition reference in the bighash and if if hasn't
                   5984: # already been evaluated recurses into docondval to get the value of
                   5985: # the condition, then memoizing it to 
                   5986: #   $env{user.state.<cid>.<condition>}
1.40      www      5987: sub directcondval {
                   5988:     my $number=shift;
1.620     albertel 5989:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5990: 	&Apache::lonuserstate::evalstate();
                   5991:     }
1.713     albertel 5992:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5993: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5994:     } elsif ($number =~ /^_/) {
                   5995: 	my $sub_condition;
                   5996: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5997: 		&GDBM_READER(),0640)) {
                   5998: 	    $sub_condition=$bighash{'conditions'.$number};
                   5999: 	    untie(%bighash);
                   6000: 	}
                   6001: 	my $value = &docondval($sub_condition);
                   6002: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6003: 	return $value;
                   6004:     }
1.620     albertel 6005:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6006:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6007:     } else {
                   6008:        return 2;
                   6009:     }
                   6010: }
                   6011: 
1.713     albertel 6012: # get the collection of conditions for this resource
1.26      www      6013: sub condval {
                   6014:     my $condidx=shift;
1.54      www      6015:     my $allpathcond='';
1.713     albertel 6016:     foreach my $cond (split(/\|/,$condidx)) {
                   6017: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6018: 	    $allpathcond.=
                   6019: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6020: 	}
1.191     harris41 6021:     }
1.54      www      6022:     $allpathcond=~s/\|$//;
1.713     albertel 6023:     return &docondval($allpathcond);
                   6024: }
                   6025: 
                   6026: #evaluates an expression of conditions
                   6027: sub docondval {
                   6028:     my ($allpathcond) = @_;
                   6029:     my $result=0;
                   6030:     if ($env{'request.course.id'}
                   6031: 	&& defined($allpathcond)) {
                   6032: 	my $operand='|';
                   6033: 	my @stack;
                   6034: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6035: 	    if ($chunk eq '(') {
                   6036: 		push @stack,($operand,$result);
                   6037: 	    } elsif ($chunk eq ')') {
                   6038: 		my $before=pop @stack;
                   6039: 		if (pop @stack eq '&') {
                   6040: 		    $result=$result>$before?$before:$result;
                   6041: 		} else {
                   6042: 		    $result=$result>$before?$result:$before;
                   6043: 		}
                   6044: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6045: 		$operand=$chunk;
                   6046: 	    } else {
                   6047: 		my $new=directcondval($chunk);
                   6048: 		if ($operand eq '&') {
                   6049: 		    $result=$result>$new?$new:$result;
                   6050: 		} else {
                   6051: 		    $result=$result>$new?$result:$new;
                   6052: 		}
                   6053: 	    }
                   6054: 	}
1.26      www      6055:     }
                   6056:     return $result;
1.421     albertel 6057: }
                   6058: 
                   6059: # ---------------------------------------------------- Devalidate courseresdata
                   6060: 
                   6061: sub devalidatecourseresdata {
                   6062:     my ($coursenum,$coursedomain)=@_;
                   6063:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6064:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6065: }
                   6066: 
1.763     www      6067: 
1.200     www      6068: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6069: #
                   6070: #  Parameters:
                   6071: #      $coursenum    - Number of the course.
                   6072: #      $coursedomain - Domain at which the course was created.
                   6073: #  Returns:
                   6074: #     A hash of the course parameters along (I think) with timestamps
                   6075: #     and version info.
1.877     foxr     6076: 
1.624     albertel 6077: sub get_courseresdata {
                   6078:     my ($coursenum,$coursedomain)=@_;
1.200     www      6079:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6080:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6081:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6082:     my %dumpreply;
1.417     albertel 6083:     unless (defined($cached)) {
1.624     albertel 6084: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6085: 	$result=\%dumpreply;
1.251     albertel 6086: 	my ($tmp) = keys(%dumpreply);
                   6087: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6088: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6089: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6090: 	    return $tmp;
1.416     albertel 6091: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6092: 	    $result=undef;
1.599     albertel 6093: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6094: 	}
                   6095:     }
1.624     albertel 6096:     return $result;
                   6097: }
                   6098: 
1.633     albertel 6099: sub devalidateuserresdata {
                   6100:     my ($uname,$udom)=@_;
                   6101:     my $hashid="$udom:$uname";
                   6102:     &devalidate_cache_new('userres',$hashid);
                   6103: }
                   6104: 
1.624     albertel 6105: sub get_userresdata {
                   6106:     my ($uname,$udom)=@_;
                   6107:     #most student don\'t have any data set, check if there is some data
                   6108:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6109: 
                   6110:     my $hashid="$udom:$uname";
                   6111:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6112:     if (!defined($cached)) {
                   6113: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6114: 	$result=\%resourcedata;
                   6115: 	&do_cache_new('userres',$hashid,$result,600);
                   6116:     }
                   6117:     my ($tmp)=keys(%$result);
                   6118:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6119: 	return $result;
                   6120:     }
                   6121:     #error 2 occurs when the .db doesn't exist
                   6122:     if ($tmp!~/error: 2 /) {
1.672     albertel 6123: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6124: 		 " Trying to get resource data for ".
                   6125: 		 $uname." at ".$udom.": ".
                   6126: 		 $tmp."</font>");
                   6127:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6128: 	#&EXT_cache_set($udom,$uname);
                   6129: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6130: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6131:     }
                   6132:     return $tmp;
                   6133: }
1.879     foxr     6134: #----------------------------------------------- resdata - return resource data
                   6135: #  Purpose:
                   6136: #    Return resource data for either users or for a course.
                   6137: #  Parameters:
                   6138: #     $name      - Course/user name.
                   6139: #     $domain    - Name of the domain the user/course is registered on.
                   6140: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6141: #     @which     - Array of names of resources desired.
                   6142: #  Returns:
                   6143: #     The value of the first reasource in @which that is found in the
                   6144: #     resource hash.
                   6145: #  Exceptional Conditions:
                   6146: #     If the $type passed in is not valid (not the string 'course' or 
                   6147: #     'user', an undefined  reference is returned.
                   6148: #     If none of the resources are found, an undef is returned
1.624     albertel 6149: sub resdata {
                   6150:     my ($name,$domain,$type,@which)=@_;
                   6151:     my $result;
                   6152:     if ($type eq 'course') {
                   6153: 	$result=&get_courseresdata($name,$domain);
                   6154:     } elsif ($type eq 'user') {
                   6155: 	$result=&get_userresdata($name,$domain);
                   6156:     }
                   6157:     if (!ref($result)) { return $result; }    
1.251     albertel 6158:     foreach my $item (@which) {
1.417     albertel 6159: 	if (defined($result->{$item})) {
                   6160: 	    return $result->{$item};
1.251     albertel 6161: 	}
1.250     albertel 6162:     }
1.291     albertel 6163:     return undef;
1.200     www      6164: }
                   6165: 
1.379     matthew  6166: #
                   6167: # EXT resource caching routines
                   6168: #
                   6169: 
                   6170: sub clear_EXT_cache_status {
1.383     albertel 6171:     &delenv('cache.EXT.');
1.379     matthew  6172: }
                   6173: 
                   6174: sub EXT_cache_status {
                   6175:     my ($target_domain,$target_user) = @_;
1.383     albertel 6176:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6177:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6178:         # We know already the user has no data
                   6179:         return 1;
                   6180:     } else {
                   6181:         return 0;
                   6182:     }
                   6183: }
                   6184: 
                   6185: sub EXT_cache_set {
                   6186:     my ($target_domain,$target_user) = @_;
1.383     albertel 6187:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6188:     #&appenv($cachename => time);
1.379     matthew  6189: }
                   6190: 
1.28      www      6191: # --------------------------------------------------------- Value of a Variable
1.58      www      6192: sub EXT {
1.715     albertel 6193: 
1.395     albertel 6194:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6195:     unless ($varname) { return ''; }
1.218     albertel 6196:     #get real user name/domain, courseid and symb
                   6197:     my $courseid;
1.359     albertel 6198:     my $publicuser;
1.427     www      6199:     if ($symbparm) {
                   6200: 	$symbparm=&get_symb_from_alias($symbparm);
                   6201:     }
1.218     albertel 6202:     if (!($uname && $udom)) {
1.790     albertel 6203:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6204:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6205:     } else {
1.620     albertel 6206: 	$courseid=$env{'request.course.id'};
1.218     albertel 6207:     }
1.48      www      6208:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6209:     my $rest;
1.320     albertel 6210:     if (defined($therest[0])) {
1.48      www      6211:        $rest=join('.',@therest);
                   6212:     } else {
                   6213:        $rest='';
                   6214:     }
1.320     albertel 6215: 
1.57      www      6216:     my $qualifierrest=$qualifier;
                   6217:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6218:     my $spacequalifierrest=$space;
                   6219:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6220:     if ($realm eq 'user') {
1.48      www      6221: # --------------------------------------------------------------- user.resource
                   6222: 	if ($space eq 'resource') {
1.651     albertel 6223: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6224: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6225: 		 &&
1.744     albertel 6226: 		 ($symbparm eq &symbread()) ) {	
                   6227: 		# if we are in the middle of processing the resource the
                   6228: 		# get the value we are planning on committing
                   6229:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6230:                     return $Apache::lonhomework::results{$qualifierrest};
                   6231:                 } else {
                   6232:                     return $Apache::lonhomework::history{$qualifierrest};
                   6233:                 }
1.335     albertel 6234: 	    } else {
1.359     albertel 6235: 		my %restored;
1.620     albertel 6236: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6237: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6238: 		} else {
                   6239: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6240: 		}
1.335     albertel 6241: 		return $restored{$qualifierrest};
                   6242: 	    }
1.48      www      6243: # ----------------------------------------------------------------- user.access
                   6244:         } elsif ($space eq 'access') {
1.218     albertel 6245: 	    # FIXME - not supporting calls for a specific user
1.48      www      6246:             return &allowed($qualifier,$rest);
                   6247: # ------------------------------------------ user.preferences, user.environment
                   6248:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6249: 	    if (($uname eq $env{'user.name'}) &&
                   6250: 		($udom eq $env{'user.domain'})) {
                   6251: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6252: 	    } else {
1.359     albertel 6253: 		my %returnhash;
                   6254: 		if (!$publicuser) {
                   6255: 		    %returnhash=&userenvironment($udom,$uname,
                   6256: 						 $qualifierrest);
                   6257: 		}
1.218     albertel 6258: 		return $returnhash{$qualifierrest};
                   6259: 	    }
1.48      www      6260: # ----------------------------------------------------------------- user.course
                   6261:         } elsif ($space eq 'course') {
1.218     albertel 6262: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6263:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6264: # ------------------------------------------------------------------- user.role
                   6265:         } elsif ($space eq 'role') {
1.218     albertel 6266: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6267:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6268:             if ($qualifier eq 'value') {
                   6269: 		return $role;
                   6270:             } elsif ($qualifier eq 'extent') {
                   6271:                 return $where;
                   6272:             }
                   6273: # ----------------------------------------------------------------- user.domain
                   6274:         } elsif ($space eq 'domain') {
1.218     albertel 6275:             return $udom;
1.48      www      6276: # ------------------------------------------------------------------- user.name
                   6277:         } elsif ($space eq 'name') {
1.218     albertel 6278:             return $uname;
1.48      www      6279: # ---------------------------------------------------- Any other user namespace
1.29      www      6280:         } else {
1.359     albertel 6281: 	    my %reply;
                   6282: 	    if (!$publicuser) {
                   6283: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6284: 	    }
                   6285: 	    return $reply{$qualifierrest};
1.48      www      6286:         }
1.236     www      6287:     } elsif ($realm eq 'query') {
                   6288: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6289:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6290: 						[$spacequalifierrest]);
1.620     albertel 6291: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6292:    } elsif ($realm eq 'request') {
1.48      www      6293: # ------------------------------------------------------------- request.browser
                   6294:         if ($space eq 'browser') {
1.430     www      6295: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6296: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6297: 		    return 1;
                   6298: 		} else {
                   6299: 		    return 0;
                   6300: 		}
                   6301: 	    } else {
1.620     albertel 6302: 		return $env{'browser.'.$qualifier};
1.430     www      6303: 	    }
1.57      www      6304: # ------------------------------------------------------------ request.filename
                   6305:         } else {
1.620     albertel 6306:             return $env{'request.'.$spacequalifierrest};
1.29      www      6307:         }
1.28      www      6308:     } elsif ($realm eq 'course') {
1.48      www      6309: # ---------------------------------------------------------- course.description
1.620     albertel 6310:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6311:     } elsif ($realm eq 'resource') {
1.165     www      6312: 
1.620     albertel 6313: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6314: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6315: 	}
1.693     albertel 6316: 
                   6317: 	if ($space eq 'title') {
                   6318: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6319: 	    return &gettitle($symbparm);
                   6320: 	}
                   6321: 	
                   6322: 	if ($space eq 'map') {
                   6323: 	    my ($map) = &decode_symb($symbparm);
                   6324: 	    return &symbread($map);
                   6325: 	}
1.905     albertel 6326: 	if ($space eq 'filename') {
                   6327: 	    if ($symbparm) {
                   6328: 		return &clutter((&decode_symb($symbparm))[2]);
                   6329: 	    }
                   6330: 	    return &hreflocation('',$env{'request.filename'});
                   6331: 	}
1.693     albertel 6332: 
                   6333: 	my ($section, $group, @groups);
1.593     albertel 6334: 	my ($courselevelm,$courselevel);
1.539     albertel 6335: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6336: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6337: 
1.218     albertel 6338: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6339: 
1.60      www      6340: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6341: 	    my $symbp=$symbparm;
1.735     albertel 6342: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6343: 
                   6344: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6345: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6346: 
1.620     albertel 6347: 	    if (($env{'user.name'} eq $uname) &&
                   6348: 		($env{'user.domain'} eq $udom)) {
                   6349: 		$section=$env{'request.course.sec'};
1.733     raeburn  6350:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6351:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6352: 	    } else {
1.539     albertel 6353: 		if (! defined($usection)) {
1.551     albertel 6354: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6355: 		} else {
                   6356: 		    $section = $usection;
                   6357: 		}
1.733     raeburn  6358:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6359: 	    }
                   6360: 
                   6361: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6362: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6363: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6364: 
1.593     albertel 6365: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6366: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6367: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6368: 
1.60      www      6369: # ----------------------------------------------------------- first, check user
1.624     albertel 6370: 
                   6371: 	    my $userreply=&resdata($uname,$udom,'user',
                   6372: 				       ($courselevelr,$courselevelm,
                   6373: 					$courselevel));
                   6374: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6375: 
1.594     albertel 6376: # ------------------------------------------------ second, check some of course
1.684     raeburn  6377:             my $coursereply;
1.691     raeburn  6378:             if (@groups > 0) {
                   6379:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6380:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6381:                 if (defined($coursereply)) { return $coursereply; }
                   6382:             }
1.96      www      6383: 
1.684     raeburn  6384: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6385: 				     $env{'course.'.$courseid.'.domain'},
                   6386: 				     'course',
                   6387: 				     ($seclevelr,$seclevelm,$seclevel,
                   6388: 				      $courselevelr));
1.287     albertel 6389: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6390: 
1.60      www      6391: # ------------------------------------------------------ third, check map parms
1.218     albertel 6392: 	    my %parmhash=();
                   6393: 	    my $thisparm='';
                   6394: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6395: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6396: 		    &GDBM_READER(),0640)) {
1.218     albertel 6397: 		$thisparm=$parmhash{$symbparm};
                   6398: 		untie(%parmhash);
                   6399: 	    }
                   6400: 	    if ($thisparm) { return $thisparm; }
                   6401: 	}
1.594     albertel 6402: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6403: 
1.218     albertel 6404: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6405: 	my $filename;
                   6406: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6407: 	if ($symbparm) {
1.409     www      6408: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6409: 	} else {
1.620     albertel 6410: 	    $filename=$env{'request.filename'};
1.282     albertel 6411: 	}
                   6412: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6413: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6414: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6415: 	if (defined($metadata)) { return $metadata; }
1.142     www      6416: 
1.594     albertel 6417: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6418: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6419: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6420: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6421: 				     $env{'course.'.$courseid.'.domain'},
                   6422: 				     'course',
                   6423: 				     ($courselevelm,$courselevel));
1.593     albertel 6424: 	    if (defined($coursereply)) { return $coursereply; }
                   6425: 	}
1.145     www      6426: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6427: 	unless ($space eq '0') {
1.336     albertel 6428: 	    my @parts=split(/_/,$space);
                   6429: 	    my $id=pop(@parts);
                   6430: 	    my $part=join('_',@parts);
                   6431: 	    if ($part eq '') { $part='0'; }
                   6432: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6433: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6434: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6435: 	}
1.395     albertel 6436: 	if ($recurse) { return undef; }
                   6437: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6438: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6439: 
1.48      www      6440: # ---------------------------------------------------- Any other user namespace
                   6441:     } elsif ($realm eq 'environment') {
                   6442: # ----------------------------------------------------------------- environment
1.620     albertel 6443: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6444: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6445: 	} else {
1.770     albertel 6446: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6447: 		return '';
                   6448: 	    }
1.219     albertel 6449: 	    my %returnhash=&userenvironment($udom,$uname,
                   6450: 					    $spacequalifierrest);
                   6451: 	    return $returnhash{$spacequalifierrest};
                   6452: 	}
1.28      www      6453:     } elsif ($realm eq 'system') {
1.48      www      6454: # ----------------------------------------------------------------- system.time
                   6455: 	if ($space eq 'time') {
                   6456: 	    return time;
                   6457:         }
1.696     albertel 6458:     } elsif ($realm eq 'server') {
                   6459: # ----------------------------------------------------------------- system.time
                   6460: 	if ($space eq 'name') {
                   6461: 	    return $ENV{'SERVER_NAME'};
                   6462:         }
1.28      www      6463:     }
1.48      www      6464:     return '';
1.61      www      6465: }
                   6466: 
1.691     raeburn  6467: sub check_group_parms {
                   6468:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6469:     my @groupitems = ();
                   6470:     my $resultitem;
                   6471:     my @levels = ($symbparm,$mapparm,$what);
                   6472:     foreach my $group (@{$groups}) {
                   6473:         foreach my $level (@levels) {
                   6474:              my $item = $courseid.'.['.$group.'].'.$level;
                   6475:              push(@groupitems,$item);
                   6476:         }
                   6477:     }
                   6478:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6479:                             $env{'course.'.$courseid.'.domain'},
                   6480:                                      'course',@groupitems);
                   6481:     return $coursereply;
                   6482: }
                   6483: 
                   6484: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6485:     my ($courseid,@groups) = @_;
                   6486:     @groups = sort(@groups);
1.691     raeburn  6487:     return @groups;
                   6488: }
                   6489: 
1.395     albertel 6490: sub packages_tab_default {
                   6491:     my ($uri,$varname)=@_;
                   6492:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6493: 
                   6494:     my (@extension,@specifics,$do_default);
                   6495:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6496: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6497: 	if ($pack_type eq 'default') {
                   6498: 	    $do_default=1;
                   6499: 	} elsif ($pack_type eq 'extension') {
                   6500: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6501: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6502: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6503: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6504: 	}
                   6505:     }
                   6506:     # first look for a package that matches the requested part id
                   6507:     foreach my $package (@specifics) {
                   6508: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6509: 	next if ($pack_part ne $part);
                   6510: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6511: 	    return $packagetab{"$pack_type&$name&default"};
                   6512: 	}
                   6513:     }
                   6514:     # look for any possible matching non extension_ package
                   6515:     foreach my $package (@specifics) {
                   6516: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6517: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6518: 	    return $packagetab{"$pack_type&$name&default"};
                   6519: 	}
1.585     albertel 6520: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6521: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6522: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6523: 	}
                   6524:     }
1.738     albertel 6525:     # look for any posible extension_ match
                   6526:     foreach my $package (@extension) {
                   6527: 	my ($package,$pack_type)=@{$package};
                   6528: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6529: 	    return $packagetab{"$pack_type&$name&default"};
                   6530: 	}
                   6531: 	if (defined($packagetab{$package."&$name&default"})) {
                   6532: 	    return $packagetab{$package."&$name&default"};
                   6533: 	}
                   6534:     }
                   6535:     # look for a global default setting
                   6536:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6537: 	return $packagetab{"default&$name&default"};
                   6538:     }
1.395     albertel 6539:     return undef;
                   6540: }
                   6541: 
1.334     albertel 6542: sub add_prefix_and_part {
                   6543:     my ($prefix,$part)=@_;
                   6544:     my $keyroot;
                   6545:     if (defined($prefix) && $prefix !~ /^__/) {
                   6546: 	# prefix that has a part already
                   6547: 	$keyroot=$prefix;
                   6548:     } elsif (defined($prefix)) {
                   6549: 	# prefix that is missing a part
                   6550: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6551:     } else {
                   6552: 	# no prefix at all
                   6553: 	if (defined($part)) { $keyroot='_'.$part; }
                   6554:     }
                   6555:     return $keyroot;
                   6556: }
                   6557: 
1.71      www      6558: # ---------------------------------------------------------------- Get metadata
                   6559: 
1.599     albertel 6560: my %metaentry;
1.71      www      6561: sub metadata {
1.176     www      6562:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6563:     $uri=&declutter($uri);
1.288     albertel 6564:     # if it is a non metadata possible uri return quickly
1.529     albertel 6565:     if (($uri eq '') || 
                   6566: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6567: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6568:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6569: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6570: 	return undef;
1.288     albertel 6571:     }
1.73      www      6572:     my $filename=$uri;
                   6573:     $uri=~s/\.meta$//;
1.172     www      6574: #
                   6575: # Is the metadata already cached?
1.177     www      6576: # Look at timestamp of caching
1.172     www      6577: # Everything is cached by the main uri, libraries are never directly cached
                   6578: #
1.428     albertel 6579:     if (!defined($liburi)) {
1.599     albertel 6580: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6581: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6582:     }
                   6583:     {
1.172     www      6584: #
                   6585: # Is this a recursive call for a library?
                   6586: #
1.599     albertel 6587: #	if (! exists($metacache{$uri})) {
                   6588: #	    $metacache{$uri}={};
                   6589: #	}
1.171     www      6590:         if ($liburi) {
                   6591: 	    $liburi=&declutter($liburi);
                   6592:             $filename=$liburi;
1.401     bowersj2 6593:         } else {
1.599     albertel 6594: 	    &devalidate_cache_new('meta',$uri);
                   6595: 	    undef(%metaentry);
1.401     bowersj2 6596: 	}
1.140     www      6597:         my %metathesekeys=();
1.73      www      6598:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6599: 	my $metastring;
1.768     albertel 6600: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6601: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6602: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6603: 	    $metastring=&getfile($file);
1.489     albertel 6604: 	}
1.208     albertel 6605:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6606:         my $token;
1.140     www      6607:         undef %metathesekeys;
1.71      www      6608:         while ($token=$parser->get_token) {
1.339     albertel 6609: 	    if ($token->[0] eq 'S') {
                   6610: 		if (defined($token->[2]->{'package'})) {
1.172     www      6611: #
                   6612: # This is a package - get package info
                   6613: #
1.339     albertel 6614: 		    my $package=$token->[2]->{'package'};
                   6615: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6616: 		    if (defined($token->[2]->{'id'})) { 
                   6617: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6618: 		    }
1.599     albertel 6619: 		    if ($metaentry{':packages'}) {
                   6620: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6621: 		    } else {
1.599     albertel 6622: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6623: 		    }
1.736     albertel 6624: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6625: 			my $part=$keyroot;
                   6626: 			$part=~s/^\_//;
1.736     albertel 6627: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6628: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6629: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6630: 			    # ignore package.tab specified default values
                   6631:                             # here &package_tab_default() will fetch those
                   6632: 			    if ($subp eq 'default') { next; }
1.736     albertel 6633: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6634: 			    my $unikey;
                   6635: 			    if ($pack =~ /_0$/) {
                   6636: 				$unikey='parameter_0_'.$name;
                   6637: 				$part=0;
                   6638: 			    } else {
                   6639: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6640: 			    }
1.339     albertel 6641: 			    if ($subp eq 'display') {
                   6642: 				$value.=' [Part: '.$part.']';
                   6643: 			    }
1.599     albertel 6644: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6645: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6646: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6647: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6648: 			    }
1.599     albertel 6649: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6650: 				$metaentry{':'.$unikey}=
                   6651: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6652: 			    }
1.339     albertel 6653: 			}
                   6654: 		    }
                   6655: 		} else {
1.172     www      6656: #
                   6657: # This is not a package - some other kind of start tag
1.339     albertel 6658: #
                   6659: 		    my $entry=$token->[1];
                   6660: 		    my $unikey;
                   6661: 		    if ($entry eq 'import') {
                   6662: 			$unikey='';
                   6663: 		    } else {
                   6664: 			$unikey=$entry;
                   6665: 		    }
                   6666: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6667: 
                   6668: 		    if (defined($token->[2]->{'id'})) { 
                   6669: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6670: 		    }
1.175     www      6671: 
1.339     albertel 6672: 		    if ($entry eq 'import') {
1.175     www      6673: #
                   6674: # Importing a library here
1.339     albertel 6675: #
                   6676: 			if ($depthcount<20) {
                   6677: 			    my $location=$parser->get_text('/import');
                   6678: 			    my $dir=$filename;
                   6679: 			    $dir=~s|[^/]*$||;
                   6680: 			    $location=&filelocation($dir,$location);
1.736     albertel 6681: 			    my $metadata = 
                   6682: 				&metadata($uri,'keys', $location,$unikey,
                   6683: 					  $depthcount+1);
                   6684: 			    foreach my $meta (split(',',$metadata)) {
                   6685: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6686: 				$metathesekeys{$meta}=1;
1.339     albertel 6687: 			    }
                   6688: 			}
                   6689: 		    } else { 
                   6690: 			
                   6691: 			if (defined($token->[2]->{'name'})) { 
                   6692: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6693: 			}
                   6694: 			$metathesekeys{$unikey}=1;
1.736     albertel 6695: 			foreach my $param (@{$token->[3]}) {
                   6696: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6697: 				$token->[2]->{$param};
1.339     albertel 6698: 			}
                   6699: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6700: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6701: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6702: 		 # only ws inside the tag, and not in default, so use default
                   6703: 		 # as value
1.599     albertel 6704: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6705: 			} elsif ( $internaltext =~ /\S/ ) {
                   6706: 		  # something interesting inside the tag
                   6707: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6708: 			} else {
1.908     albertel 6709: 		  # no interesting values, don't set a default
1.339     albertel 6710: 			}
1.172     www      6711: # end of not-a-package not-a-library import
1.339     albertel 6712: 		    }
1.172     www      6713: # end of not-a-package start tag
1.339     albertel 6714: 		}
1.172     www      6715: # the next is the end of "start tag"
1.339     albertel 6716: 	    }
                   6717: 	}
1.483     albertel 6718: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6719: 	$extension = lc($extension);
                   6720: 	if ($extension eq 'htm') { $extension='html'; }
                   6721: 
1.737     albertel 6722: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6723: 	    #no specific packages #how's our extension
                   6724: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6725: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6726: 					 \%metathesekeys);
                   6727: 	}
1.883     albertel 6728: 
                   6729: 	if (!exists($metaentry{':packages'})
                   6730: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6731: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6732: 		#no specific packages well let's get default then
                   6733: 		if ($key!~/^default&/) { next; }
1.488     albertel 6734: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6735: 					     \%metathesekeys);
                   6736: 	    }
                   6737: 	}
1.338     www      6738: # are there custom rights to evaluate
1.599     albertel 6739: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6740: 
1.338     www      6741:     #
                   6742:     # Importing a rights file here
1.339     albertel 6743:     #
                   6744: 	    unless ($depthcount) {
1.599     albertel 6745: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6746: 		my $dir=$filename;
                   6747: 		$dir=~s|[^/]*$||;
                   6748: 		$location=&filelocation($dir,$location);
1.736     albertel 6749: 		my $rights_metadata =
                   6750: 		    &metadata($uri,'keys',$location,'_rights',
                   6751: 			      $depthcount+1);
                   6752: 		foreach my $rights (split(',',$rights_metadata)) {
                   6753: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6754: 		    $metathesekeys{$rights}=1;
1.339     albertel 6755: 		}
                   6756: 	    }
                   6757: 	}
1.737     albertel 6758: 	# uniqifiy package listing
                   6759: 	my %seen;
                   6760: 	my @uniq_packages =
                   6761: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6762: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6763: 
                   6764: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6765: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6766: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6767: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6768: # this is the end of "was not already recently cached
1.71      www      6769:     }
1.599     albertel 6770:     return $metaentry{':'.$what};
1.261     albertel 6771: }
                   6772: 
1.488     albertel 6773: sub metadata_create_package_def {
1.483     albertel 6774:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6775:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6776:     if ($subp eq 'default') { next; }
                   6777:     
1.599     albertel 6778:     if (defined($metaentry{':packages'})) {
                   6779: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6780:     } else {
1.599     albertel 6781: 	$metaentry{':packages'}=$package;
1.483     albertel 6782:     }
                   6783:     my $value=$packagetab{$key};
                   6784:     my $unikey;
                   6785:     $unikey='parameter_0_'.$name;
1.599     albertel 6786:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6787:     $$metathesekeys{$unikey}=1;
1.599     albertel 6788:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6789: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6790:     }
1.599     albertel 6791:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6792: 	$metaentry{':'.$unikey}=
                   6793: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6794:     }
                   6795: }
                   6796: 
1.261     albertel 6797: sub metadata_generate_part0 {
                   6798:     my ($metadata,$metacache,$uri) = @_;
                   6799:     my %allnames;
1.737     albertel 6800:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6801: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6802: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6803: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6804: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6805: 	    $allnames{$name}=$part;
                   6806: 	  }
                   6807: 	}
                   6808:     }
                   6809:     foreach my $name (keys(%allnames)) {
                   6810:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6811:       my $key=":parameter_0_$name";
1.261     albertel 6812:       $$metacache{"$key.part"}='0';
                   6813:       $$metacache{"$key.name"}=$name;
1.428     albertel 6814:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6815: 					   $allnames{$name}.'_'.$name.
                   6816: 					   '.type'};
1.428     albertel 6817:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6818: 			     '.display'};
1.644     www      6819:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6820:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6821:       $$metacache{"$key.display"}=$olddis;
                   6822:     }
1.71      www      6823: }
                   6824: 
1.764     albertel 6825: # ------------------------------------------------------ Devalidate title cache
                   6826: 
                   6827: sub devalidate_title_cache {
                   6828:     my ($url)=@_;
                   6829:     if (!$env{'request.course.id'}) { return; }
                   6830:     my $symb=&symbread($url);
                   6831:     if (!$symb) { return; }
                   6832:     my $key=$env{'request.course.id'}."\0".$symb;
                   6833:     &devalidate_cache_new('title',$key);
                   6834: }
                   6835: 
1.301     www      6836: # ------------------------------------------------- Get the title of a resource
                   6837: 
                   6838: sub gettitle {
                   6839:     my $urlsymb=shift;
                   6840:     my $symb=&symbread($urlsymb);
1.534     albertel 6841:     if ($symb) {
1.620     albertel 6842: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6843: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6844: 	if (defined($cached)) { 
                   6845: 	    return $result;
                   6846: 	}
1.534     albertel 6847: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6848: 	my $title='';
1.907     albertel 6849: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   6850: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   6851: 	} else {
                   6852: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6853: 		    &GDBM_READER(),0640)) {
                   6854: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6855: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   6856: 		untie(%bighash);
                   6857: 	    }
1.534     albertel 6858: 	}
                   6859: 	$title=~s/\&colon\;/\:/gs;
                   6860: 	if ($title) {
1.599     albertel 6861: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6862: 	}
                   6863: 	$urlsymb=$url;
                   6864:     }
                   6865:     my $title=&metadata($urlsymb,'title');
                   6866:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6867:     return $title;
1.301     www      6868: }
1.613     albertel 6869: 
1.614     albertel 6870: sub get_slot {
                   6871:     my ($which,$cnum,$cdom)=@_;
                   6872:     if (!$cnum || !$cdom) {
1.790     albertel 6873: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6874: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6875: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6876:     }
1.703     albertel 6877:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6878:     my %slotinfo;
                   6879:     if (exists($remembered{$key})) {
                   6880: 	$slotinfo{$which} = $remembered{$key};
                   6881:     } else {
                   6882: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6883: 	&Apache::lonhomework::showhash(%slotinfo);
                   6884: 	my ($tmp)=keys(%slotinfo);
                   6885: 	if ($tmp=~/^error:/) { return (); }
                   6886: 	$remembered{$key} = $slotinfo{$which};
                   6887:     }
1.616     albertel 6888:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6889: 	return %{$slotinfo{$which}};
                   6890:     }
                   6891:     return $slotinfo{$which};
1.614     albertel 6892: }
1.31      www      6893: # ------------------------------------------------- Update symbolic store links
                   6894: 
                   6895: sub symblist {
                   6896:     my ($mapname,%newhash)=@_;
1.438     www      6897:     $mapname=&deversion(&declutter($mapname));
1.31      www      6898:     my %hash;
1.620     albertel 6899:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6900:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6901:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6902: 	    foreach my $url (keys %newhash) {
                   6903: 		next if ($url eq 'last_known'
                   6904: 			 && $env{'form.no_update_last_known'});
                   6905: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6906: 						    $newhash{$url}->[1],
                   6907: 						    $newhash{$url}->[0]);
1.191     harris41 6908:             }
1.31      www      6909:             if (untie(%hash)) {
                   6910: 		return 'ok';
                   6911:             }
                   6912:         }
                   6913:     }
                   6914:     return 'error';
1.212     www      6915: }
                   6916: 
                   6917: # --------------------------------------------------------------- Verify a symb
                   6918: 
                   6919: sub symbverify {
1.510     www      6920:     my ($symb,$thisurl)=@_;
                   6921:     my $thisfn=$thisurl;
1.439     www      6922:     $thisfn=&declutter($thisfn);
1.215     www      6923: # direct jump to resource in page or to a sequence - will construct own symbs
                   6924:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6925: # check URL part
1.409     www      6926:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6927: 
1.431     www      6928:     unless ($url eq $thisfn) { return 0; }
1.213     www      6929: 
1.216     www      6930:     $symb=&symbclean($symb);
1.510     www      6931:     $thisurl=&deversion($thisurl);
1.439     www      6932:     $thisfn=&deversion($thisfn);
1.213     www      6933: 
                   6934:     my %bighash;
                   6935:     my $okay=0;
1.431     www      6936: 
1.620     albertel 6937:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6938:                             &GDBM_READER(),0640)) {
1.510     www      6939:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6940:         unless ($ids) { 
1.510     www      6941:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6942:         }
                   6943:         if ($ids) {
                   6944: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6945: 	    foreach my $id (split(/\,/,$ids)) {
                   6946: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6947:                if (
                   6948:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6949:    eq $symb) { 
1.620     albertel 6950: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6951: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6952: 		       $okay=1; 
                   6953: 		   }
                   6954: 	       }
1.216     www      6955: 	   }
                   6956:         }
1.213     www      6957: 	untie(%bighash);
                   6958:     }
                   6959:     return $okay;
1.31      www      6960: }
                   6961: 
1.210     www      6962: # --------------------------------------------------------------- Clean-up symb
                   6963: 
                   6964: sub symbclean {
                   6965:     my $symb=shift;
1.568     albertel 6966:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6967: # remove version from map
                   6968:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6969: 
1.210     www      6970: # remove version from URL
                   6971:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6972: 
1.507     www      6973: # remove wrapper
                   6974: 
1.510     www      6975:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6976:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6977:     return $symb;
1.409     www      6978: }
                   6979: 
                   6980: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6981: 
                   6982: sub encode_symb {
                   6983:     my ($map,$resid,$url)=@_;
                   6984:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6985: }
1.409     www      6986: 
                   6987: sub decode_symb {
1.568     albertel 6988:     my $symb=shift;
                   6989:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6990:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6991:     return (&fixversion($map),$resid,&fixversion($url));
                   6992: }
                   6993: 
                   6994: sub fixversion {
                   6995:     my $fn=shift;
1.609     banghart 6996:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6997:     my %bighash;
                   6998:     my $uri=&clutter($fn);
1.620     albertel 6999:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7000: # is this cached?
1.599     albertel 7001:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7002:     if (defined($cached)) { return $result; }
                   7003: # unfortunately not cached, or expired
1.620     albertel 7004:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7005: 	    &GDBM_READER(),0640)) {
                   7006:  	if ($bighash{'version_'.$uri}) {
                   7007:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7008:  	    unless (($version eq 'mostrecent') || 
                   7009: 		    ($version==&getversion($uri))) {
1.440     www      7010:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7011:  	    }
                   7012:  	}
                   7013:  	untie %bighash;
1.413     www      7014:     }
1.599     albertel 7015:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7016: }
                   7017: 
                   7018: sub deversion {
                   7019:     my $url=shift;
                   7020:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7021:     return $url;
1.210     www      7022: }
                   7023: 
1.31      www      7024: # ------------------------------------------------------ Return symb list entry
                   7025: 
                   7026: sub symbread {
1.249     www      7027:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7028:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7029:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7030: # no filename provided? try from environment
1.44      www      7031:     unless ($thisfn) {
1.620     albertel 7032:         if ($env{'request.symb'}) {
                   7033: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7034: 	}
1.620     albertel 7035: 	$thisfn=$env{'request.filename'};
1.44      www      7036:     }
1.569     albertel 7037:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7038: # is that filename actually a symb? Verify, clean, and return
                   7039:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7040: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7041: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7042: 	}
1.242     www      7043:     }
1.44      www      7044:     $thisfn=declutter($thisfn);
1.31      www      7045:     my %hash;
1.37      www      7046:     my %bighash;
                   7047:     my $syval='';
1.620     albertel 7048:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7049:         my $targetfn = $thisfn;
1.609     banghart 7050:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7051:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7052:         }
1.687     albertel 7053: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7054: 	    $targetfn=$1;
                   7055: 	}
1.620     albertel 7056:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7057:                       &GDBM_READER(),0640)) {
1.481     raeburn  7058: 	    $syval=$hash{$targetfn};
1.37      www      7059:             untie(%hash);
                   7060:         }
                   7061: # ---------------------------------------------------------- There was an entry
                   7062:         if ($syval) {
1.601     albertel 7063: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7064: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7065: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7066: 		    #return $env{$cache_str}='';
1.601     albertel 7067: 		#}    
                   7068: 		#$syval.=$1;
                   7069: 	    #}
1.37      www      7070:         } else {
                   7071: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7072:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7073:                             &GDBM_READER(),0640)) {
1.37      www      7074: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7075:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7076:               unless ($ids) { 
                   7077:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7078:               }
                   7079:               unless ($ids) {
                   7080: # alias?
                   7081: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7082:               }
1.37      www      7083:               if ($ids) {
                   7084: # ------------------------------------------------------------------- Has ID(s)
                   7085:                  my @possibilities=split(/\,/,$ids);
1.39      www      7086:                  if ($#possibilities==0) {
                   7087: # ----------------------------------------------- There is only one possibility
1.37      www      7088: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7089: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7090: 						    $resid,$thisfn);
1.249     www      7091:                  } elsif (!$donotrecurse) {
1.39      www      7092: # ------------------------------------------ There is more than one possibility
                   7093:                      my $realpossible=0;
1.800     albertel 7094:                      foreach my $id (@possibilities) {
                   7095: 			 my $file=$bighash{'src_'.$id};
1.39      www      7096:                          if (&allowed('bre',$file)) {
1.800     albertel 7097:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7098:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7099: 				$realpossible++;
1.626     albertel 7100:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7101: 						    $resid,$thisfn);
1.39      www      7102:                             }
                   7103: 			 }
1.191     harris41 7104:                      }
1.39      www      7105: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7106:                  } else {
                   7107:                      $syval='';
1.37      www      7108:                  }
                   7109: 	      }
                   7110:               untie(%bighash)
1.481     raeburn  7111:            }
1.31      www      7112:         }
1.62      www      7113:         if ($syval) {
1.620     albertel 7114: 	    return $env{$cache_str}=$syval;
1.62      www      7115:         }
1.31      www      7116:     }
1.44      www      7117:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7118:     return $env{$cache_str}='';
1.31      www      7119: }
                   7120: 
                   7121: # ---------------------------------------------------------- Return random seed
                   7122: 
1.32      www      7123: sub numval {
                   7124:     my $txt=shift;
                   7125:     $txt=~tr/A-J/0-9/;
                   7126:     $txt=~tr/a-j/0-9/;
                   7127:     $txt=~tr/K-T/0-9/;
                   7128:     $txt=~tr/k-t/0-9/;
                   7129:     $txt=~tr/U-Z/0-5/;
                   7130:     $txt=~tr/u-z/0-5/;
                   7131:     $txt=~s/\D//g;
1.564     albertel 7132:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7133:     return int($txt);
1.368     albertel 7134: }
                   7135: 
1.484     albertel 7136: sub numval2 {
                   7137:     my $txt=shift;
                   7138:     $txt=~tr/A-J/0-9/;
                   7139:     $txt=~tr/a-j/0-9/;
                   7140:     $txt=~tr/K-T/0-9/;
                   7141:     $txt=~tr/k-t/0-9/;
                   7142:     $txt=~tr/U-Z/0-5/;
                   7143:     $txt=~tr/u-z/0-5/;
                   7144:     $txt=~s/\D//g;
                   7145:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7146:     my $total;
                   7147:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7148:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7149:     return int($total);
                   7150: }
                   7151: 
1.575     albertel 7152: sub numval3 {
                   7153:     use integer;
                   7154:     my $txt=shift;
                   7155:     $txt=~tr/A-J/0-9/;
                   7156:     $txt=~tr/a-j/0-9/;
                   7157:     $txt=~tr/K-T/0-9/;
                   7158:     $txt=~tr/k-t/0-9/;
                   7159:     $txt=~tr/U-Z/0-5/;
                   7160:     $txt=~tr/u-z/0-5/;
                   7161:     $txt=~s/\D//g;
                   7162:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7163:     my $total;
                   7164:     foreach my $val (@txts) { $total+=$val; }
                   7165:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7166:     return $total;
                   7167: }
                   7168: 
1.675     albertel 7169: sub digest {
                   7170:     my ($data)=@_;
                   7171:     my $digest=&Digest::MD5::md5($data);
                   7172:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7173:     my ($e,$f);
                   7174:     {
                   7175:         use integer;
                   7176:         $e=($a+$b);
                   7177:         $f=($c+$d);
                   7178:         if ($_64bit) {
                   7179:             $e=(($e<<32)>>32);
                   7180:             $f=(($f<<32)>>32);
                   7181:         }
                   7182:     }
                   7183:     if (wantarray) {
                   7184: 	return ($e,$f);
                   7185:     } else {
                   7186: 	my $g;
                   7187: 	{
                   7188: 	    use integer;
                   7189: 	    $g=($e+$f);
                   7190: 	    if ($_64bit) {
                   7191: 		$g=(($g<<32)>>32);
                   7192: 	    }
                   7193: 	}
                   7194: 	return $g;
                   7195:     }
                   7196: }
                   7197: 
1.368     albertel 7198: sub latest_rnd_algorithm_id {
1.675     albertel 7199:     return '64bit5';
1.366     albertel 7200: }
1.32      www      7201: 
1.503     albertel 7202: sub get_rand_alg {
                   7203:     my ($courseid)=@_;
1.790     albertel 7204:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7205:     if ($courseid) {
1.620     albertel 7206: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7207:     }
                   7208:     return &latest_rnd_algorithm_id();
                   7209: }
                   7210: 
1.562     albertel 7211: sub validCODE {
                   7212:     my ($CODE)=@_;
                   7213:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7214:     return 0;
                   7215: }
                   7216: 
1.491     albertel 7217: sub getCODE {
1.620     albertel 7218:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7219:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7220: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7221: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7222: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7223:     }
                   7224:     return undef;
                   7225: }
                   7226: 
1.31      www      7227: sub rndseed {
1.155     albertel 7228:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7229:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7230:     if (!defined($symb)) {
1.366     albertel 7231: 	unless ($symb=$wsymb) { return time; }
                   7232:     }
                   7233:     if (!$courseid) { $courseid=$wcourseid; }
                   7234:     if (!$domain) { $domain=$wdomain; }
                   7235:     if (!$username) { $username=$wusername }
1.503     albertel 7236:     my $which=&get_rand_alg();
1.803     albertel 7237: 
1.491     albertel 7238:     if (defined(&getCODE())) {
1.675     albertel 7239: 	if ($which eq '64bit5') {
                   7240: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7241: 	} elsif ($which eq '64bit4') {
1.575     albertel 7242: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7243: 	} else {
                   7244: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7245: 	}
1.675     albertel 7246:     } elsif ($which eq '64bit5') {
                   7247: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7248:     } elsif ($which eq '64bit4') {
                   7249: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7250:     } elsif ($which eq '64bit3') {
                   7251: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7252:     } elsif ($which eq '64bit2') {
                   7253: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7254:     } elsif ($which eq '64bit') {
                   7255: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7256:     }
                   7257:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7258: }
                   7259: 
                   7260: sub rndseed_32bit {
                   7261:     my ($symb,$courseid,$domain,$username)=@_;
                   7262:     {
                   7263: 	use integer;
                   7264: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7265: 	my $symbseed=numval($symb) << 22;
                   7266: 	my $namechck=unpack("%32C*",$username) << 17;
                   7267: 	my $nameseed=numval($username) << 12;
                   7268: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7269: 	my $courseseed=unpack("%32C*",$courseid);
                   7270: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7271: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7272: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7273: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7274: 	return $num;
                   7275:     }
                   7276: }
                   7277: 
                   7278: sub rndseed_64bit {
                   7279:     my ($symb,$courseid,$domain,$username)=@_;
                   7280:     {
                   7281: 	use integer;
                   7282: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7283: 	my $symbseed=numval($symb) << 10;
                   7284: 	my $namechck=unpack("%32S*",$username);
                   7285: 	
                   7286: 	my $nameseed=numval($username) << 21;
                   7287: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7288: 	my $courseseed=unpack("%32S*",$courseid);
                   7289: 	
                   7290: 	my $num1=$symbchck+$symbseed+$namechck;
                   7291: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7292: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7293: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7294: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7295: 	return "$num1,$num2";
1.155     albertel 7296:     }
1.366     albertel 7297: }
                   7298: 
1.443     albertel 7299: sub rndseed_64bit2 {
                   7300:     my ($symb,$courseid,$domain,$username)=@_;
                   7301:     {
                   7302: 	use integer;
                   7303: 	# strings need to be an even # of cahracters long, it it is odd the
                   7304:         # last characters gets thrown away
                   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;
1.501     albertel 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.803     albertel 7317: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7318: 	return "$num1,$num2";
                   7319:     }
                   7320: }
                   7321: 
                   7322: sub rndseed_64bit3 {
                   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=numval2($symb) << 10;
                   7330: 	my $namechck=unpack("%32S*",$username.' ');
                   7331: 	
                   7332: 	my $nameseed=numval2($username) << 21;
1.443     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 :$num1:$num2:$_64bit");
1.564     albertel 7340: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7341: 	
1.503     albertel 7342: 	return "$num1:$num2";
1.443     albertel 7343:     }
                   7344: }
                   7345: 
1.575     albertel 7346: sub rndseed_64bit4 {
                   7347:     my ($symb,$courseid,$domain,$username)=@_;
                   7348:     {
                   7349: 	use integer;
                   7350: 	# strings need to be an even # of cahracters long, it it is odd the
                   7351:         # last characters gets thrown away
                   7352: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7353: 	my $symbseed=numval3($symb) << 10;
                   7354: 	my $namechck=unpack("%32S*",$username.' ');
                   7355: 	
                   7356: 	my $nameseed=numval3($username) << 21;
                   7357: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7358: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7359: 	
                   7360: 	my $num1=$symbchck+$symbseed+$namechck;
                   7361: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7362: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7363: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7364: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7365: 	
                   7366: 	return "$num1:$num2";
                   7367:     }
                   7368: }
                   7369: 
1.675     albertel 7370: sub rndseed_64bit5 {
                   7371:     my ($symb,$courseid,$domain,$username)=@_;
                   7372:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7373:     return "$num1:$num2";
                   7374: }
                   7375: 
1.366     albertel 7376: sub rndseed_CODE_64bit {
                   7377:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7378:     {
1.366     albertel 7379: 	use integer;
1.443     albertel 7380: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7381: 	my $symbseed=numval2($symb);
1.491     albertel 7382: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7383: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7384: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7385: 	my $num1=$symbseed+$CODEchck;
                   7386: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7387: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7388: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7389: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7390: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7391: 	return "$num1:$num2";
1.366     albertel 7392:     }
                   7393: }
                   7394: 
1.575     albertel 7395: sub rndseed_CODE_64bit4 {
                   7396:     my ($symb,$courseid,$domain,$username)=@_;
                   7397:     {
                   7398: 	use integer;
                   7399: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7400: 	my $symbseed=numval3($symb);
                   7401: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7402: 	my $CODEseed=numval3(&getCODE());
                   7403: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7404: 	my $num1=$symbseed+$CODEchck;
                   7405: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7406: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7407: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7408: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7409: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7410: 	return "$num1:$num2";
                   7411:     }
                   7412: }
                   7413: 
1.675     albertel 7414: sub rndseed_CODE_64bit5 {
                   7415:     my ($symb,$courseid,$domain,$username)=@_;
                   7416:     my $code = &getCODE();
                   7417:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7418:     return "$num1:$num2";
                   7419: }
                   7420: 
1.366     albertel 7421: sub setup_random_from_rndseed {
                   7422:     my ($rndseed)=@_;
1.503     albertel 7423:     if ($rndseed =~/([,:])/) {
                   7424: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7425: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7426:     } else {
                   7427: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7428:     }
1.36      albertel 7429: }
                   7430: 
1.474     albertel 7431: sub latest_receipt_algorithm_id {
1.835     albertel 7432:     return 'receipt3';
1.474     albertel 7433: }
                   7434: 
1.480     www      7435: sub recunique {
                   7436:     my $fucourseid=shift;
                   7437:     my $unique;
1.835     albertel 7438:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7439: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7440: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7441:     } else {
                   7442: 	$unique=$perlvar{'lonReceipt'};
                   7443:     }
                   7444:     return unpack("%32C*",$unique);
                   7445: }
                   7446: 
                   7447: sub recprefix {
                   7448:     my $fucourseid=shift;
                   7449:     my $prefix;
1.835     albertel 7450:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7451: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7452: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7453:     } else {
                   7454: 	$prefix=$perlvar{'lonHostID'};
                   7455:     }
                   7456:     return unpack("%32C*",$prefix);
                   7457: }
                   7458: 
1.76      www      7459: sub ireceipt {
1.474     albertel 7460:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7461: 
                   7462:     my $return =&recprefix($fucourseid).'-';
                   7463: 
                   7464:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7465: 	$env{'request.state'} eq 'construct') {
                   7466: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7467: 	return $return;
                   7468:     }
                   7469: 
1.76      www      7470:     my $cuname=unpack("%32C*",$funame);
                   7471:     my $cudom=unpack("%32C*",$fudom);
                   7472:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7473:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7474:     my $cunique=&recunique($fucourseid);
1.474     albertel 7475:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7476:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7477: 
1.790     albertel 7478: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7479: 			       
                   7480: 	$return.= ($cunique%$cuname+
                   7481: 		   $cunique%$cudom+
                   7482: 		   $cusymb%$cuname+
                   7483: 		   $cusymb%$cudom+
                   7484: 		   $cucourseid%$cuname+
                   7485: 		   $cucourseid%$cudom+
                   7486: 		   $cpart%$cuname+
                   7487: 		   $cpart%$cudom);
                   7488:     } else {
                   7489: 	$return.= ($cunique%$cuname+
                   7490: 		   $cunique%$cudom+
                   7491: 		   $cusymb%$cuname+
                   7492: 		   $cusymb%$cudom+
                   7493: 		   $cucourseid%$cuname+
                   7494: 		   $cucourseid%$cudom);
                   7495:     }
                   7496:     return $return;
1.76      www      7497: }
                   7498: 
                   7499: sub receipt {
1.474     albertel 7500:     my ($part)=@_;
1.790     albertel 7501:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7502:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7503: }
1.260     ng       7504: 
1.790     albertel 7505: sub whichuser {
                   7506:     my ($passedsymb)=@_;
                   7507:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7508:     if (defined($env{'form.grade_symb'})) {
                   7509: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7510: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7511: 	if (!$allowed &&
                   7512: 	    exists($env{'request.course.sec'}) &&
                   7513: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7514: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7515: 			      '/'.$env{'request.course.sec'});
                   7516: 	}
                   7517: 	if ($allowed) {
                   7518: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7519: 	    $courseid=$tmp_courseid;
                   7520: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7521: 	    ($name)=&get_env_multiple('form.grade_username');
                   7522: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7523: 	}
                   7524:     }
                   7525:     if (!$passedsymb) {
                   7526: 	$symb=&symbread();
                   7527:     } else {
                   7528: 	$symb=$passedsymb;
                   7529:     }
                   7530:     $courseid=$env{'request.course.id'};
                   7531:     $domain=$env{'user.domain'};
                   7532:     $name=$env{'user.name'};
                   7533:     if ($name eq 'public' && $domain eq 'public') {
                   7534: 	if (!defined($env{'form.username'})) {
                   7535: 	    $env{'form.username'}.=time.rand(10000000);
                   7536: 	}
                   7537: 	$name.=$env{'form.username'};
                   7538:     }
                   7539:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7540: 
                   7541: }
                   7542: 
1.36      albertel 7543: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7544: # returns either the contents of the file or 
                   7545: # -1 if the file doesn't exist
1.481     raeburn  7546: #
                   7547: # if the target is a file that was uploaded via DOCS, 
                   7548: # a check will be made to see if a current copy exists on the local server,
                   7549: # if it does this will be served, otherwise a copy will be retrieved from
                   7550: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7551: # the local server.   
1.472     albertel 7552: 
1.36      albertel 7553: sub getfile {
1.538     albertel 7554:     my ($file) = @_;
1.609     banghart 7555:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7556:     &repcopy($file);
                   7557:     return &readfile($file);
                   7558: }
                   7559: 
                   7560: sub repcopy_userfile {
                   7561:     my ($file)=@_;
1.609     banghart 7562:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7563:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7564:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7565: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7566:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7567:     if (-e "$file") {
1.828     www      7568: # we already have a local copy, check it out
1.538     albertel 7569: 	my @fileinfo = stat($file);
1.828     www      7570: 	my $rtncode;
                   7571: 	my $info;
1.538     albertel 7572: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7573: 	if ($lwpresp ne 'ok') {
1.828     www      7574: # there is no such file anymore, even though we had a local copy
1.482     albertel 7575: 	    if ($rtncode eq '404') {
1.538     albertel 7576: 		unlink($file);
1.482     albertel 7577: 	    }
                   7578: 	    return -1;
                   7579: 	}
                   7580: 	if ($info < $fileinfo[9]) {
1.828     www      7581: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7582: 	    return 'ok';
1.828     www      7583: 	} else {
                   7584: # the file is outdated, get rid of it
                   7585: 	    unlink($file);
1.482     albertel 7586: 	}
1.828     www      7587:     }
                   7588: # one way or the other, at this point, we don't have the file
                   7589: # construct the correct path for the file
                   7590:     my @parts = ($cdom,$cnum); 
                   7591:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7592: 	push @parts, split(/\//,$1);
                   7593:     }
                   7594:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7595:     foreach my $part (@parts) {
                   7596: 	$path .= '/'.$part;
                   7597: 	if (!-e $path) {
                   7598: 	    mkdir($path,0770);
1.482     albertel 7599: 	}
                   7600:     }
1.828     www      7601: # now the path exists for sure
                   7602: # get a user agent
                   7603:     my $ua=new LWP::UserAgent;
                   7604:     my $transferfile=$file.'.in.transfer';
                   7605: # FIXME: this should flock
                   7606:     if (-e $transferfile) { return 'ok'; }
                   7607:     my $request;
                   7608:     $uri=~s/^\///;
1.838     albertel 7609:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7610:     my $response=$ua->request($request,$transferfile);
                   7611: # did it work?
                   7612:     if ($response->is_error()) {
                   7613: 	unlink($transferfile);
                   7614: 	&logthis("Userfile repcopy failed for $uri");
                   7615: 	return -1;
                   7616:     }
                   7617: # worked, rename the transfer file
                   7618:     rename($transferfile,$file);
1.607     raeburn  7619:     return 'ok';
1.481     raeburn  7620: }
                   7621: 
1.517     albertel 7622: sub tokenwrapper {
                   7623:     my $uri=shift;
1.552     albertel 7624:     $uri=~s|^http\://([^/]+)||;
                   7625:     $uri=~s|^/||;
1.620     albertel 7626:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7627:     my $token=$1;
1.552     albertel 7628:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7629:     if ($udom && $uname && $file) {
                   7630: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7631:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7632:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7633:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7634:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7635:     } else {
                   7636:         return '/adm/notfound.html';
                   7637:     }
                   7638: }
                   7639: 
1.828     www      7640: # call with reqtype HEAD: get last modification time
                   7641: # call with reqtype GET: get the file contents
                   7642: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7643: #
1.481     raeburn  7644: sub getuploaded {
                   7645:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7646:     $uri=~s/^\///;
1.838     albertel 7647:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7648:     my $ua=new LWP::UserAgent;
                   7649:     my $request=new HTTP::Request($reqtype,$uri);
                   7650:     my $response=$ua->request($request);
                   7651:     $$rtncode = $response->code;
1.482     albertel 7652:     if (! $response->is_success()) {
                   7653: 	return 'failed';
                   7654:     }      
                   7655:     if ($reqtype eq 'HEAD') {
1.486     www      7656: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7657:     } elsif ($reqtype eq 'GET') {
                   7658: 	$$info = $response->content;
1.472     albertel 7659:     }
1.482     albertel 7660:     return 'ok';
1.36      albertel 7661: }
                   7662: 
1.481     raeburn  7663: sub readfile {
                   7664:     my $file = shift;
                   7665:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7666:     my $fh;
                   7667:     open($fh,"<$file");
                   7668:     my $a='';
1.800     albertel 7669:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7670:     return $a;
                   7671: }
                   7672: 
1.36      albertel 7673: sub filelocation {
1.590     banghart 7674:     my ($dir,$file) = @_;
                   7675:     my $location;
                   7676:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7677: 
                   7678:     if ($file =~ m-^/adm/-) {
                   7679: 	$file=~s-^/adm/wrapper/-/-;
                   7680: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7681:     }
1.882     albertel 7682: 
1.590     banghart 7683:     if ($file=~m:^/~:) { # is a contruction space reference
                   7684:         $location = $file;
                   7685:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7686:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7687: 	# is a correct contruction space reference
                   7688:         $location = $file;
1.609     banghart 7689:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7690:         my ($udom,$uname,$filename)=
1.811     albertel 7691:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7692:         my $home=&homeserver($uname,$udom);
                   7693:         my $is_me=0;
                   7694:         my @ids=&current_machine_ids();
                   7695:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7696:         if ($is_me) {
1.740     www      7697:   	    $location=&propath($udom,$uname).
1.590     banghart 7698:   	      '/userfiles/'.$filename;
                   7699:         } else {
                   7700:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7701:   	      $udom.'/'.$uname.'/'.$filename;
                   7702:         }
1.882     albertel 7703:     } elsif ($file =~ m-^/adm/-) {
                   7704: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7705:     } else {
                   7706:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7707:         $file=~s:^/res/:/:;
                   7708:         if ( !( $file =~ m:^/:) ) {
                   7709:             $location = $dir. '/'.$file;
                   7710:         } else {
                   7711:             $location = '/home/httpd/html/res'.$file;
                   7712:         }
1.59      albertel 7713:     }
1.590     banghart 7714:     $location=~s://+:/:g; # remove duplicate /
                   7715:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7716:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7717:     return $location;
1.46      www      7718: }
1.36      albertel 7719: 
1.46      www      7720: sub hreflocation {
                   7721:     my ($dir,$file)=@_;
1.460     albertel 7722:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7723: 	$file=filelocation($dir,$file);
1.700     albertel 7724:     } elsif ($file=~m-^/adm/-) {
                   7725: 	$file=~s-^/adm/wrapper/-/-;
                   7726: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7727:     }
                   7728:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7729: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7730:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7731: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7732:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7733: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7734: 	    -/uploaded/$1/$2/-x;
1.46      www      7735:     }
1.462     albertel 7736:     return $file;
1.465     albertel 7737: }
                   7738: 
                   7739: sub current_machine_domains {
1.853     albertel 7740:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7741: }
                   7742: 
                   7743: sub machine_domains {
                   7744:     my ($hostname) = @_;
1.465     albertel 7745:     my @domains;
1.838     albertel 7746:     my %hostname = &all_hostnames();
1.465     albertel 7747:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7748: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7749: 	if ($hostname eq $name) {
1.844     albertel 7750: 	    push(@domains,&host_domain($id));
1.465     albertel 7751: 	}
                   7752:     }
                   7753:     return @domains;
                   7754: }
                   7755: 
                   7756: sub current_machine_ids {
1.853     albertel 7757:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7758: }
                   7759: 
                   7760: sub machine_ids {
                   7761:     my ($hostname) = @_;
                   7762:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7763:     my @ids;
1.888     albertel 7764:     my %name_to_host = &all_names();
1.889     albertel 7765:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7766: 	return @{ $name_to_host{$hostname} };
                   7767:     }
                   7768:     return;
1.31      www      7769: }
                   7770: 
1.824     raeburn  7771: sub additional_machine_domains {
                   7772:     my @domains;
                   7773:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7774:     while( my $line = <$fh>) {
                   7775:         $line =~ s/\s//g;
                   7776:         push(@domains,$line);
                   7777:     }
                   7778:     return @domains;
                   7779: }
                   7780: 
                   7781: sub default_login_domain {
                   7782:     my $domain = $perlvar{'lonDefDomain'};
                   7783:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7784:     foreach my $posdom (&current_machine_domains(),
                   7785:                         &additional_machine_domains()) {
                   7786:         if (lc($posdom) eq lc($testdomain)) {
                   7787:             $domain=$posdom;
                   7788:             last;
                   7789:         }
                   7790:     }
                   7791:     return $domain;
                   7792: }
                   7793: 
1.31      www      7794: # ------------------------------------------------------------- Declutters URLs
                   7795: 
                   7796: sub declutter {
                   7797:     my $thisfn=shift;
1.569     albertel 7798:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7799:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7800:     $thisfn=~s/^\///;
1.697     albertel 7801:     $thisfn=~s|^adm/wrapper/||;
                   7802:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7803:     $thisfn=~s/^res\///;
1.235     www      7804:     $thisfn=~s/\?.+$//;
1.268     www      7805:     return $thisfn;
                   7806: }
                   7807: 
                   7808: # ------------------------------------------------------------- Clutter up URLs
                   7809: 
                   7810: sub clutter {
                   7811:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7812:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7813: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7814:        $thisfn='/res'.$thisfn; 
                   7815:     }
1.694     albertel 7816:     if ($thisfn !~m|/adm|) {
1.695     albertel 7817: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7818: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7819: 	} else {
                   7820: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7821: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7822: 	    if ($embstyle eq 'ssi'
                   7823: 		|| ($embstyle eq 'hdn')
                   7824: 		|| ($embstyle eq 'rat')
                   7825: 		|| ($embstyle eq 'prv')
                   7826: 		|| ($embstyle eq 'ign')) {
                   7827: 		#do nothing with these
                   7828: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7829: 		|| ($embstyle eq 'emb')
                   7830: 		|| ($embstyle eq 'wrp')) {
                   7831: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7832: 	    } elsif ($embstyle eq 'unk'
                   7833: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7834: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7835: 	    } else {
1.718     www      7836: #		&logthis("Got a blank emb style");
1.695     albertel 7837: 	    }
1.694     albertel 7838: 	}
                   7839:     }
1.31      www      7840:     return $thisfn;
1.12      www      7841: }
                   7842: 
1.787     albertel 7843: sub clutter_with_no_wrapper {
                   7844:     my $uri = &clutter(shift);
                   7845:     if ($uri =~ m-^/adm/-) {
                   7846: 	$uri =~ s-^/adm/wrapper/-/-;
                   7847: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7848:     }
                   7849:     return $uri;
                   7850: }
                   7851: 
1.557     albertel 7852: sub freeze_escape {
                   7853:     my ($value)=@_;
                   7854:     if (ref($value)) {
                   7855: 	$value=&nfreeze($value);
                   7856: 	return '__FROZEN__'.&escape($value);
                   7857:     }
                   7858:     return &escape($value);
                   7859: }
                   7860: 
1.11      www      7861: 
1.557     albertel 7862: sub thaw_unescape {
                   7863:     my ($value)=@_;
                   7864:     if ($value =~ /^__FROZEN__/) {
                   7865: 	substr($value,0,10,undef);
                   7866: 	$value=&unescape($value);
                   7867: 	return &thaw($value);
                   7868:     }
                   7869:     return &unescape($value);
                   7870: }
                   7871: 
1.436     albertel 7872: sub correct_line_ends {
                   7873:     my ($result)=@_;
                   7874:     $$result =~s/\r\n/\n/mg;
                   7875:     $$result =~s/\r/\n/mg;
1.415     albertel 7876: }
1.1       albertel 7877: # ================================================================ Main Program
                   7878: 
1.184     www      7879: sub goodbye {
1.204     albertel 7880:    &logthis("Starting Shut down");
1.443     albertel 7881: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7882:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7883: #converted
1.599     albertel 7884: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7885:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7886: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7887: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7888: #1.1 only
1.870     albertel 7889: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7890: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7891: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7892: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7893:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7894:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7895:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7896:    &flushcourselogs();
                   7897:    &logthis("Shutting down");
                   7898: }
                   7899: 
1.852     albertel 7900: sub get_dns {
1.869     albertel 7901:     my ($url,$func,$ignore_cache) = @_;
                   7902:     if (!$ignore_cache) {
                   7903: 	my ($content,$cached)=
                   7904: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7905: 	if ($cached) {
                   7906: 	    &$func($content);
                   7907: 	    return;
                   7908: 	}
                   7909:     }
                   7910: 
                   7911:     my %alldns;
1.852     albertel 7912:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7913:     foreach my $dns (<$config>) {
                   7914: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7915: 	$alldns{$1} = 1;
                   7916:     }
                   7917:     while (%alldns) {
                   7918: 	my ($dns) = keys(%alldns);
                   7919: 	delete($alldns{$dns});
1.852     albertel 7920: 	my $ua=new LWP::UserAgent;
                   7921: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7922: 	my $response=$ua->request($request);
                   7923: 	next if ($response->is_error());
                   7924: 	my @content = split("\n",$response->content);
1.869     albertel 7925: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7926: 	&$func(\@content);
1.869     albertel 7927: 	return;
1.852     albertel 7928:     }
                   7929:     close($config);
1.871     albertel 7930:     my $which = (split('/',$url))[3];
                   7931:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7932:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7933:     my @content = <$config>;
                   7934:     &$func(\@content);
                   7935:     return;
1.852     albertel 7936: }
1.327     albertel 7937: # ------------------------------------------------------------ Read domain file
                   7938: {
1.852     albertel 7939:     my $loaded;
1.846     albertel 7940:     my %domain;
                   7941: 
1.852     albertel 7942:     sub parse_domain_tab {
                   7943: 	my ($lines) = @_;
                   7944: 	foreach my $line (@$lines) {
                   7945: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7946: 
1.846     albertel 7947: 	    chomp($line);
1.852     albertel 7948: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7949: 	    my %this_domain;
                   7950: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7951: 			       'lang_def', 'city', 'longi', 'lati',
                   7952: 			       'primary') {
                   7953: 		$this_domain{$field} = shift(@elements);
                   7954: 	    }
                   7955: 	    $domain{$name} = \%this_domain;
1.852     albertel 7956: 	}
                   7957:     }
1.864     albertel 7958: 
                   7959:     sub reset_domain_info {
                   7960: 	undef($loaded);
                   7961: 	undef(%domain);
                   7962:     }
                   7963: 
1.852     albertel 7964:     sub load_domain_tab {
1.869     albertel 7965: 	my ($ignore_cache) = @_;
                   7966: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7967: 	my $fh;
                   7968: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7969: 	    my @lines = <$fh>;
                   7970: 	    &parse_domain_tab(\@lines);
1.448     albertel 7971: 	}
1.852     albertel 7972: 	close($fh);
                   7973: 	$loaded = 1;
1.327     albertel 7974:     }
1.846     albertel 7975: 
                   7976:     sub domain {
1.852     albertel 7977: 	&load_domain_tab() if (!$loaded);
                   7978: 
1.846     albertel 7979: 	my ($name,$what) = @_;
                   7980: 	return if ( !exists($domain{$name}) );
                   7981: 
                   7982: 	if (!$what) {
                   7983: 	    return $domain{$name}{'description'};
                   7984: 	}
                   7985: 	return $domain{$name}{$what};
                   7986:     }
1.327     albertel 7987: }
                   7988: 
                   7989: 
1.1       albertel 7990: # ------------------------------------------------------------- Read hosts file
                   7991: {
1.838     albertel 7992:     my %hostname;
1.844     albertel 7993:     my %hostdom;
1.845     albertel 7994:     my %libserv;
1.852     albertel 7995:     my $loaded;
1.888     albertel 7996:     my %name_to_host;
1.852     albertel 7997: 
                   7998:     sub parse_hosts_tab {
                   7999: 	my ($file) = @_;
                   8000: 	foreach my $configline (@$file) {
                   8001: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8002: 	    next if ($configline =~ /^\^/);
                   8003: 	    chomp($configline);
                   8004: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8005: 	    $name=~s/\s//g;
                   8006: 	    if ($id && $domain && $role && $name) {
                   8007: 		$hostname{$id}=$name;
1.888     albertel 8008: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8009: 		$hostdom{$id}=$domain;
                   8010: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8011: 	    }
                   8012: 	}
                   8013:     }
1.864     albertel 8014:     
                   8015:     sub reset_hosts_info {
1.897     albertel 8016: 	&purge_remembered();
1.864     albertel 8017: 	&reset_domain_info();
                   8018: 	&reset_hosts_ip_info();
1.892     albertel 8019: 	undef(%name_to_host);
1.864     albertel 8020: 	undef(%hostname);
                   8021: 	undef(%hostdom);
                   8022: 	undef(%libserv);
                   8023: 	undef($loaded);
                   8024:     }
1.1       albertel 8025: 
1.852     albertel 8026:     sub load_hosts_tab {
1.869     albertel 8027: 	my ($ignore_cache) = @_;
                   8028: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8029: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8030: 	my @config = <$config>;
                   8031: 	&parse_hosts_tab(\@config);
                   8032: 	close($config);
                   8033: 	$loaded=1;
1.1       albertel 8034:     }
1.852     albertel 8035: 
1.838     albertel 8036:     sub hostname {
1.852     albertel 8037: 	&load_hosts_tab() if (!$loaded);
                   8038: 
1.838     albertel 8039: 	my ($lonid) = @_;
                   8040: 	return $hostname{$lonid};
                   8041:     }
1.845     albertel 8042: 
1.838     albertel 8043:     sub all_hostnames {
1.852     albertel 8044: 	&load_hosts_tab() if (!$loaded);
                   8045: 
1.838     albertel 8046: 	return %hostname;
                   8047:     }
1.845     albertel 8048: 
1.888     albertel 8049:     sub all_names {
                   8050: 	&load_hosts_tab() if (!$loaded);
                   8051: 
                   8052: 	return %name_to_host;
                   8053:     }
                   8054: 
1.845     albertel 8055:     sub is_library {
1.852     albertel 8056: 	&load_hosts_tab() if (!$loaded);
                   8057: 
1.845     albertel 8058: 	return exists($libserv{$_[0]});
                   8059:     }
                   8060: 
                   8061:     sub all_library {
1.852     albertel 8062: 	&load_hosts_tab() if (!$loaded);
                   8063: 
1.845     albertel 8064: 	return %libserv;
                   8065:     }
                   8066: 
1.841     albertel 8067:     sub get_servers {
1.852     albertel 8068: 	&load_hosts_tab() if (!$loaded);
                   8069: 
1.841     albertel 8070: 	my ($domain,$type) = @_;
                   8071: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8072: 	                                          : %hostname;
                   8073: 	my %result;
1.842     albertel 8074: 	if (ref($domain) eq 'ARRAY') {
                   8075: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8076: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8077: 		    $result{$host} = $hostname;
                   8078: 		}
                   8079: 	    }
                   8080: 	} else {
                   8081: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8082: 		if ($hostdom{$host} eq $domain) {
                   8083: 		    $result{$host} = $hostname;
                   8084: 		}
1.841     albertel 8085: 	    }
                   8086: 	}
                   8087: 	return %result;
                   8088:     }
1.845     albertel 8089: 
1.844     albertel 8090:     sub host_domain {
1.852     albertel 8091: 	&load_hosts_tab() if (!$loaded);
                   8092: 
1.844     albertel 8093: 	my ($lonid) = @_;
                   8094: 	return $hostdom{$lonid};
                   8095:     }
                   8096: 
1.841     albertel 8097:     sub all_domains {
1.852     albertel 8098: 	&load_hosts_tab() if (!$loaded);
                   8099: 
1.841     albertel 8100: 	my %seen;
                   8101: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8102: 	return @uniq;
                   8103:     }
1.1       albertel 8104: }
                   8105: 
1.847     albertel 8106: { 
                   8107:     my %iphost;
1.856     albertel 8108:     my %name_to_ip;
                   8109:     my %lonid_to_ip;
1.869     albertel 8110: 
1.847     albertel 8111:     sub get_hosts_from_ip {
                   8112: 	my ($ip) = @_;
                   8113: 	my %iphosts = &get_iphost();
                   8114: 	if (ref($iphosts{$ip})) {
                   8115: 	    return @{$iphosts{$ip}};
                   8116: 	}
                   8117: 	return;
1.839     albertel 8118:     }
1.864     albertel 8119:     
                   8120:     sub reset_hosts_ip_info {
                   8121: 	undef(%iphost);
                   8122: 	undef(%name_to_ip);
                   8123: 	undef(%lonid_to_ip);
                   8124:     }
1.856     albertel 8125: 
                   8126:     sub get_host_ip {
                   8127: 	my ($lonid) = @_;
                   8128: 	if (exists($lonid_to_ip{$lonid})) {
                   8129: 	    return $lonid_to_ip{$lonid};
                   8130: 	}
                   8131: 	my $name=&hostname($lonid);
                   8132:    	my $ip = gethostbyname($name);
                   8133: 	return if (!$ip || length($ip) ne 4);
                   8134: 	$ip=inet_ntoa($ip);
                   8135: 	$name_to_ip{$name}   = $ip;
                   8136: 	$lonid_to_ip{$lonid} = $ip;
                   8137: 	return $ip;
                   8138:     }
1.847     albertel 8139:     
                   8140:     sub get_iphost {
1.869     albertel 8141: 	my ($ignore_cache) = @_;
1.894     albertel 8142: 
1.869     albertel 8143: 	if (!$ignore_cache) {
                   8144: 	    if (%iphost) {
                   8145: 		return %iphost;
                   8146: 	    }
                   8147: 	    my ($ip_info,$cached)=
                   8148: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8149: 	    if ($cached) {
                   8150: 		%iphost      = %{$ip_info->[0]};
                   8151: 		%name_to_ip  = %{$ip_info->[1]};
                   8152: 		%lonid_to_ip = %{$ip_info->[2]};
                   8153: 		return %iphost;
                   8154: 	    }
                   8155: 	}
1.894     albertel 8156: 
                   8157: 	# get yesterday's info for fallback
                   8158: 	my %old_name_to_ip;
                   8159: 	my ($ip_info,$cached)=
                   8160: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8161: 	if ($cached) {
                   8162: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8163: 	}
                   8164: 
1.888     albertel 8165: 	my %name_to_host = &all_names();
                   8166: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8167: 	    my $ip;
                   8168: 	    if (!exists($name_to_ip{$name})) {
                   8169: 		$ip = gethostbyname($name);
                   8170: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8171: 		    if (defined($old_name_to_ip{$name})) {
                   8172: 			$ip = $old_name_to_ip{$name};
                   8173: 			&logthis("Can't find $name defaulting to old $ip");
                   8174: 		    } else {
                   8175: 			&logthis("Name $name no IP found");
                   8176: 			next;
                   8177: 		    }
                   8178: 		} else {
                   8179: 		    $ip=inet_ntoa($ip);
1.847     albertel 8180: 		}
                   8181: 		$name_to_ip{$name} = $ip;
                   8182: 	    } else {
                   8183: 		$ip = $name_to_ip{$name};
1.653     albertel 8184: 	    }
1.888     albertel 8185: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8186: 		$lonid_to_ip{$id} = $ip;
                   8187: 	    }
                   8188: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8189: 	}
1.869     albertel 8190: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8191: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8192: 				      48*60*60);
1.869     albertel 8193: 
1.847     albertel 8194: 	return %iphost;
1.598     albertel 8195:     }
                   8196: }
                   8197: 
1.862     albertel 8198: BEGIN {
                   8199: 
                   8200: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8201:     unless ($readit) {
                   8202: {
                   8203:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8204:     %perlvar = (%perlvar,%{$configvars});
                   8205: }
                   8206: 
                   8207: 
1.1       albertel 8208: # ------------------------------------------------------ Read spare server file
                   8209: {
1.448     albertel 8210:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8211: 
                   8212:     while (my $configline=<$config>) {
                   8213:        chomp($configline);
1.284     matthew  8214:        if ($configline) {
1.784     albertel 8215: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8216: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8217: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8218:        }
                   8219:     }
1.448     albertel 8220:     close($config);
1.1       albertel 8221: }
1.11      www      8222: # ------------------------------------------------------------ Read permissions
                   8223: {
1.448     albertel 8224:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8225: 
                   8226:     while (my $configline=<$config>) {
1.448     albertel 8227: 	chomp($configline);
                   8228: 	if ($configline) {
                   8229: 	    my ($role,$perm)=split(/ /,$configline);
                   8230: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8231: 	}
1.11      www      8232:     }
1.448     albertel 8233:     close($config);
1.11      www      8234: }
                   8235: 
                   8236: # -------------------------------------------- Read plain texts for permissions
                   8237: {
1.448     albertel 8238:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8239: 
                   8240:     while (my $configline=<$config>) {
1.448     albertel 8241: 	chomp($configline);
                   8242: 	if ($configline) {
1.742     raeburn  8243: 	    my ($short,@plain)=split(/:/,$configline);
                   8244:             %{$prp{$short}} = ();
                   8245: 	    if (@plain > 0) {
                   8246:                 $prp{$short}{'std'} = $plain[0];
                   8247:                 for (my $i=1; $i<@plain; $i++) {
                   8248:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8249:                 }
                   8250:             }
1.448     albertel 8251: 	}
1.135     www      8252:     }
1.448     albertel 8253:     close($config);
1.135     www      8254: }
                   8255: 
                   8256: # ---------------------------------------------------------- Read package table
                   8257: {
1.448     albertel 8258:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8259: 
                   8260:     while (my $configline=<$config>) {
1.483     albertel 8261: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8262: 	chomp($configline);
                   8263: 	my ($short,$plain)=split(/:/,$configline);
                   8264: 	my ($pack,$name)=split(/\&/,$short);
                   8265: 	if ($plain ne '') {
                   8266: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8267: 	    $packagetab{$short}=$plain; 
                   8268: 	}
1.11      www      8269:     }
1.448     albertel 8270:     close($config);
1.329     matthew  8271: }
                   8272: 
                   8273: # ------------- set up temporary directory
                   8274: {
                   8275:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8276: 
1.11      www      8277: }
                   8278: 
1.794     albertel 8279: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8280: 				'compress_threshold'=> 20_000,
                   8281:  			        });
1.185     www      8282: 
1.281     www      8283: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8284: $dumpcount=0;
1.22      www      8285: 
1.163     harris41 8286: &logtouch();
1.672     albertel 8287: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8288: $readit=1;
1.564     albertel 8289:     {
                   8290: 	use integer;
                   8291: 	my $test=(2**32)+1;
1.568     albertel 8292: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8293: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8294:     }
1.195     www      8295: }
1.1       albertel 8296: }
1.179     www      8297: 
1.1       albertel 8298: 1;
1.191     harris41 8299: __END__
                   8300: 
1.243     albertel 8301: =pod
                   8302: 
1.191     harris41 8303: =head1 NAME
                   8304: 
1.243     albertel 8305: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8306: 
                   8307: =head1 SYNOPSIS
                   8308: 
1.243     albertel 8309: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8310: 
                   8311:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8312: 
1.243     albertel 8313: Common parameters:
                   8314: 
                   8315: =over 4
                   8316: 
                   8317: =item *
                   8318: 
                   8319: $uname : an internal username (if $cname expecting a course Id specifically)
                   8320: 
                   8321: =item *
                   8322: 
                   8323: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8324: 
                   8325: =item *
                   8326: 
                   8327: $symb : a resource instance identifier
                   8328: 
                   8329: =item *
                   8330: 
                   8331: $namespace : the name of a .db file that contains the data needed or
                   8332: being set.
                   8333: 
                   8334: =back
                   8335: 
1.394     bowersj2 8336: =head1 OVERVIEW
1.191     harris41 8337: 
1.394     bowersj2 8338: lonnet provides subroutines which interact with the
                   8339: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8340: about classes, users, and resources.
1.243     albertel 8341: 
                   8342: For many of these objects you can also use this to store data about
                   8343: them or modify them in various ways.
1.191     harris41 8344: 
1.394     bowersj2 8345: =head2 Symbs
1.191     harris41 8346: 
1.394     bowersj2 8347: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8348: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8349: map, the resource number of the resource in the map, and the URL of
                   8350: the resource itself. The latter is somewhat redundant, but might help
                   8351: if maps change.
                   8352: 
                   8353: An example is
                   8354: 
                   8355:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8356: 
                   8357: The respective map entry is
                   8358: 
                   8359:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8360:   title="Problem 2">
                   8361:  </resource>
                   8362: 
                   8363: Symbs are used by the random number generator, as well as to store and
                   8364: restore data specific to a certain instance of for example a problem.
                   8365: 
                   8366: =head2 Storing And Retrieving Data
                   8367: 
                   8368: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8369: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8370: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8371: is is the non-critical message twin of cstore. These functions are for
                   8372: handlers to store a perl hash to a user's permanent data space in an
                   8373: easy manner, and to retrieve it again on another call. It is expected
                   8374: that a handler would use this once at the beginning to retrieve data,
                   8375: and then again once at the end to send only the new data back.
                   8376: 
                   8377: The data is stored in the user's data directory on the user's
                   8378: homeserver under the ID of the course.
                   8379: 
                   8380: The hash that is returned by restore will have all of the previous
                   8381: value for all of the elements of the hash.
                   8382: 
                   8383: Example:
                   8384: 
                   8385:  #creating a hash
                   8386:  my %hash;
                   8387:  $hash{'foo'}='bar';
                   8388: 
                   8389:  #storing it
                   8390:  &Apache::lonnet::cstore(\%hash);
                   8391: 
                   8392:  #changing a value
                   8393:  $hash{'foo'}='notbar';
                   8394: 
                   8395:  #adding a new value
                   8396:  $hash{'bar'}='foo';
                   8397:  &Apache::lonnet::cstore(\%hash);
                   8398: 
                   8399:  #retrieving the hash
                   8400:  my %history=&Apache::lonnet::restore();
                   8401: 
                   8402:  #print the hash
                   8403:  foreach my $key (sort(keys(%history))) {
                   8404:    print("\%history{$key} = $history{$key}");
                   8405:  }
                   8406: 
                   8407: Will print out:
1.191     harris41 8408: 
1.394     bowersj2 8409:  %history{1:foo} = bar
                   8410:  %history{1:keys} = foo:timestamp
                   8411:  %history{1:timestamp} = 990455579
                   8412:  %history{2:bar} = foo
                   8413:  %history{2:foo} = notbar
                   8414:  %history{2:keys} = foo:bar:timestamp
                   8415:  %history{2:timestamp} = 990455580
                   8416:  %history{bar} = foo
                   8417:  %history{foo} = notbar
                   8418:  %history{timestamp} = 990455580
                   8419:  %history{version} = 2
                   8420: 
                   8421: Note that the special hash entries C<keys>, C<version> and
                   8422: C<timestamp> were added to the hash. C<version> will be equal to the
                   8423: total number of versions of the data that have been stored. The
                   8424: C<timestamp> attribute will be the UNIX time the hash was
                   8425: stored. C<keys> is available in every historical section to list which
                   8426: keys were added or changed at a specific historical revision of a
                   8427: hash.
                   8428: 
                   8429: B<Warning>: do not store the hash that restore returns directly. This
                   8430: will cause a mess since it will restore the historical keys as if the
                   8431: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8432: 
1.394     bowersj2 8433: Calling convention:
1.191     harris41 8434: 
1.394     bowersj2 8435:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8436:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8437: 
1.394     bowersj2 8438: For more detailed information, see lonnet specific documentation.
1.191     harris41 8439: 
1.394     bowersj2 8440: =head1 RETURN MESSAGES
1.191     harris41 8441: 
1.394     bowersj2 8442: =over 4
1.191     harris41 8443: 
1.394     bowersj2 8444: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8445: 
1.394     bowersj2 8446: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8447: when the connection is brought back up
1.191     harris41 8448: 
1.394     bowersj2 8449: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8450: for later delivery
1.191     harris41 8451: 
1.394     bowersj2 8452: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8453: 
1.394     bowersj2 8454: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8455: that was requested
1.191     harris41 8456: 
1.243     albertel 8457: =back
1.191     harris41 8458: 
1.243     albertel 8459: =head1 PUBLIC SUBROUTINES
1.191     harris41 8460: 
1.243     albertel 8461: =head2 Session Environment Functions
1.191     harris41 8462: 
1.243     albertel 8463: =over 4
1.191     harris41 8464: 
1.394     bowersj2 8465: =item * 
                   8466: X<appenv()>
                   8467: B<appenv(%hash)>: the value of %hash is written to
                   8468: the user envirnoment file, and will be restored for each access this
1.620     albertel 8469: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8470: process
1.191     harris41 8471: 
                   8472: =item *
1.394     bowersj2 8473: X<delenv()>
                   8474: B<delenv($regexp)>: removes all items from the session
                   8475: environment file that matches the regular expression in $regexp. The
1.620     albertel 8476: values are also delted from the current processes %env.
1.191     harris41 8477: 
1.795     albertel 8478: =item * get_env_multiple($name) 
                   8479: 
                   8480: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8481: values may be defined and end up as an array ref.
                   8482: 
                   8483: returns an array of values
                   8484: 
1.243     albertel 8485: =back
                   8486: 
                   8487: =head2 User Information
1.191     harris41 8488: 
1.243     albertel 8489: =over 4
1.191     harris41 8490: 
                   8491: =item *
1.394     bowersj2 8492: X<queryauthenticate()>
                   8493: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8494: authentication scheme
                   8495: 
                   8496: =item *
1.394     bowersj2 8497: X<authenticate()>
                   8498: B<authenticate($uname,$upass,$udom)>: try to
                   8499: authenticate user from domain's lib servers (first use the current
                   8500: one). C<$upass> should be the users password.
1.191     harris41 8501: 
                   8502: =item *
1.394     bowersj2 8503: X<homeserver()>
                   8504: B<homeserver($uname,$udom)>: find the server which has
                   8505: the user's directory and files (there must be only one), this caches
                   8506: the answer, and also caches if there is a borken connection.
1.191     harris41 8507: 
                   8508: =item *
1.394     bowersj2 8509: X<idget()>
                   8510: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8511: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8512: username, and only 1 username per ID in a specific domain) (returns
                   8513: hash: id=>name,id=>name)
1.191     harris41 8514: 
                   8515: =item *
1.394     bowersj2 8516: X<idrget()>
                   8517: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8518: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8519: 
                   8520: =item *
1.394     bowersj2 8521: X<idput()>
                   8522: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8523: 
                   8524: =item *
1.394     bowersj2 8525: X<rolesinit()>
                   8526: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8527: 
                   8528: =item *
1.551     albertel 8529: X<getsection()>
                   8530: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8531: course $cname, return section name/number or '' for "not in course"
                   8532: and '-1' for "no section"
                   8533: 
                   8534: =item *
1.394     bowersj2 8535: X<userenvironment()>
                   8536: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8537: passed in @what from the requested user's environment, returns a hash
                   8538: 
1.858     raeburn  8539: =item * 
                   8540: X<userlog_query()>
1.859     albertel 8541: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8542: activity.log file. %filters defines filters applied when parsing the
                   8543: log file. These can be start or end timestamps, or the type of action
                   8544: - log to look for Login or Logout events, check for Checkin or
                   8545: Checkout, role for role selection. The response is in the form
                   8546: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8547: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8548: 
1.243     albertel 8549: =back
                   8550: 
                   8551: =head2 User Roles
                   8552: 
                   8553: =over 4
                   8554: 
                   8555: =item *
                   8556: 
1.810     raeburn  8557: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8558:  F: full access
                   8559:  U,I,K: authentication modes (cxx only)
                   8560:  '': forbidden
                   8561:  1: user needs to choose course
                   8562:  2: browse allowed
1.766     albertel 8563:  A: passphrase authentication needed
1.243     albertel 8564: 
                   8565: =item *
                   8566: 
                   8567: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8568: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8569: and course level
                   8570: 
                   8571: =item *
                   8572: 
                   8573: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8574: explanation of a user role term
                   8575: 
1.832     raeburn  8576: =item *
                   8577: 
1.858     raeburn  8578: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8579: All arguments are optional. Returns a hash of a roles, either for
                   8580: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8581: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8582: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8583: and value is set to colon-separated start and end times for the role.
                   8584: If no username and domain are specified, will default to current
                   8585: user/domain. Types, roles, and roledoms are references to arrays,
                   8586: of role statuses (active, future or previous), roles 
                   8587: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8588: to restrict the list of roles reported. If no array ref is 
                   8589: provided for types, will default to return only active roles.
1.834     albertel 8590: 
1.243     albertel 8591: =back
                   8592: 
                   8593: =head2 User Modification
                   8594: 
                   8595: =over 4
                   8596: 
                   8597: =item *
                   8598: 
                   8599: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8600: user for the level given by URL.  Optional start and end dates (leave empty
                   8601: string or zero for "no date")
1.191     harris41 8602: 
                   8603: =item *
                   8604: 
1.243     albertel 8605: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8606: change a users, password, possible return values are: ok,
                   8607: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8608: refused
1.191     harris41 8609: 
                   8610: =item *
                   8611: 
1.243     albertel 8612: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8613: 
                   8614: =item *
                   8615: 
1.243     albertel 8616: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8617: modify user
1.191     harris41 8618: 
                   8619: =item *
                   8620: 
1.286     matthew  8621: modifystudent
                   8622: 
                   8623: modify a students enrollment and identification information.
                   8624: The course id is resolved based on the current users environment.  
                   8625: This means the envoking user must be a course coordinator or otherwise
                   8626: associated with a course.
                   8627: 
1.297     matthew  8628: This call is essentially a wrapper for lonnet::modifyuser and
                   8629: lonnet::modify_student_enrollment
1.286     matthew  8630: 
                   8631: Inputs: 
                   8632: 
                   8633: =over 4
                   8634: 
                   8635: =item B<$udom> Students loncapa domain
                   8636: 
                   8637: =item B<$uname> Students loncapa login name
                   8638: 
                   8639: =item B<$uid> Students id/student number
                   8640: 
                   8641: =item B<$umode> Students authentication mode
                   8642: 
                   8643: =item B<$upass> Students password
                   8644: 
                   8645: =item B<$first> Students first name
                   8646: 
                   8647: =item B<$middle> Students middle name
                   8648: 
                   8649: =item B<$last> Students last name
                   8650: 
                   8651: =item B<$gene> Students generation
                   8652: 
                   8653: =item B<$usec> Students section in course
                   8654: 
                   8655: =item B<$end> Unix time of the roles expiration
                   8656: 
                   8657: =item B<$start> Unix time of the roles start date
                   8658: 
                   8659: =item B<$forceid> If defined, allow $uid to be changed
                   8660: 
                   8661: =item B<$desiredhome> server to use as home server for student
                   8662: 
                   8663: =back
1.297     matthew  8664: 
                   8665: =item *
                   8666: 
                   8667: modify_student_enrollment
                   8668: 
                   8669: Change a students enrollment status in a class.  The environment variable
                   8670: 'role.request.course' must be defined for this function to proceed.
                   8671: 
                   8672: Inputs:
                   8673: 
                   8674: =over 4
                   8675: 
                   8676: =item $udom, students domain
                   8677: 
                   8678: =item $uname, students name
                   8679: 
                   8680: =item $uid, students user id
                   8681: 
                   8682: =item $first, students first name
                   8683: 
                   8684: =item $middle
                   8685: 
                   8686: =item $last
                   8687: 
                   8688: =item $gene
                   8689: 
                   8690: =item $usec
                   8691: 
                   8692: =item $end
                   8693: 
                   8694: =item $start
                   8695: 
                   8696: =back
                   8697: 
1.191     harris41 8698: 
                   8699: =item *
                   8700: 
1.243     albertel 8701: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8702: custom role; give a custom role to a user for the level given by URL.  Specify
                   8703: name and domain of role author, and role name
1.191     harris41 8704: 
                   8705: =item *
                   8706: 
1.243     albertel 8707: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8708: 
                   8709: =item *
                   8710: 
1.243     albertel 8711: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8712: 
                   8713: =back
                   8714: 
                   8715: =head2 Course Infomation
                   8716: 
                   8717: =over 4
1.191     harris41 8718: 
                   8719: =item *
                   8720: 
1.631     albertel 8721: coursedescription($courseid) : returns a hash of information about the
                   8722: specified course id, including all environment settings for the
                   8723: course, the description of the course will be in the hash under the
                   8724: key 'description'
1.191     harris41 8725: 
                   8726: =item *
                   8727: 
1.624     albertel 8728: resdata($name,$domain,$type,@which) : request for current parameter
                   8729: setting for a specific $type, where $type is either 'course' or 'user',
                   8730: @what should be a list of parameters to ask about. This routine caches
                   8731: answers for 5 minutes.
1.243     albertel 8732: 
1.877     foxr     8733: =item *
                   8734: 
                   8735: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8736: data base, returning a hash that is keyed by the resource name and has
                   8737: values that are the resource value.  I believe that the timestamps and
                   8738: versions are also returned.
                   8739: 
                   8740: 
1.243     albertel 8741: =back
                   8742: 
                   8743: =head2 Course Modification
                   8744: 
                   8745: =over 4
1.191     harris41 8746: 
                   8747: =item *
                   8748: 
1.243     albertel 8749: writecoursepref($courseid,%prefs) : write preferences (environment
                   8750: database) for a course
1.191     harris41 8751: 
                   8752: =item *
                   8753: 
1.243     albertel 8754: createcourse($udom,$description,$url) : make/modify course
                   8755: 
                   8756: =back
                   8757: 
                   8758: =head2 Resource Subroutines
                   8759: 
                   8760: =over 4
1.191     harris41 8761: 
                   8762: =item *
                   8763: 
1.243     albertel 8764: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8765: 
                   8766: =item *
                   8767: 
1.243     albertel 8768: repcopy($filename) : subscribes to the requested file, and attempts to
                   8769: replicate from the owning library server, Might return
1.607     raeburn  8770: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8771: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8772: resource. Expects the local filesystem pathname
                   8773: (/home/httpd/html/res/....)
                   8774: 
                   8775: =back
                   8776: 
                   8777: =head2 Resource Information
                   8778: 
                   8779: =over 4
1.191     harris41 8780: 
                   8781: =item *
                   8782: 
1.243     albertel 8783: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8784: a vairety of different possible values, $varname should be a request
                   8785: string, and the other parameters can be used to specify who and what
                   8786: one is asking about.
                   8787: 
                   8788: Possible values for $varname are environment.lastname (or other item
                   8789: from the envirnment hash), user.name (or someother aspect about the
                   8790: user), resource.0.maxtries (or some other part and parameter of a
                   8791: resource)
1.204     albertel 8792: 
                   8793: =item *
                   8794: 
1.243     albertel 8795: directcondval($number) : get current value of a condition; reads from a state
                   8796: string
1.204     albertel 8797: 
                   8798: =item *
                   8799: 
1.243     albertel 8800: condval($condidx) : value of condition index based on state
1.204     albertel 8801: 
                   8802: =item *
                   8803: 
1.243     albertel 8804: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8805: resource's metadata, $what should be either a specific key, or either
                   8806: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8807: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8808: 
                   8809: this function automatically caches all requests
1.191     harris41 8810: 
                   8811: =item *
                   8812: 
1.243     albertel 8813: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8814: network of library servers; returns file handle of where SQL and regex results
                   8815: will be stored for query
1.191     harris41 8816: 
                   8817: =item *
                   8818: 
1.243     albertel 8819: symbread($filename) : return symbolic list entry (filename argument optional);
                   8820: returns the data handle
1.191     harris41 8821: 
                   8822: =item *
                   8823: 
1.243     albertel 8824: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8825: a possible symb for the URL in $thisfn, and if is an encryypted
                   8826: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8827: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8828: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8829: 
1.191     harris41 8830: 
                   8831: =item *
                   8832: 
1.243     albertel 8833: symbclean($symb) : removes versions numbers from a symb, returns the
                   8834: cleaned symb
1.191     harris41 8835: 
                   8836: =item *
                   8837: 
1.243     albertel 8838: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8839: course map, user must be in a course for it to work.
1.191     harris41 8840: 
                   8841: =item *
                   8842: 
1.243     albertel 8843: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8844: 
                   8845: =item *
                   8846: 
1.243     albertel 8847: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8848: a random seed, all arguments are optional, if they aren't sent it uses the
                   8849: environment to derive them. Note: if symb isn't sent and it can't get one
                   8850: from &symbread it will use the current time as its return value
1.191     harris41 8851: 
                   8852: =item *
                   8853: 
1.243     albertel 8854: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8855: unfakeable, receipt
1.191     harris41 8856: 
                   8857: =item *
                   8858: 
1.620     albertel 8859: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8860: 
                   8861: =item *
                   8862: 
1.243     albertel 8863: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8864: 
                   8865: =item *
                   8866: 
1.243     albertel 8867: 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 8868: 
                   8869: =item *
                   8870: 
1.243     albertel 8871: 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 8872: 
                   8873: =item *
                   8874: 
1.243     albertel 8875: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8876: 
                   8877: =item *
                   8878: 
1.243     albertel 8879: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8880: forcing spreadsheet to reevaluate the resource scores next time.
                   8881: 
                   8882: =back
                   8883: 
                   8884: =head2 Storing/Retreiving Data
                   8885: 
                   8886: =over 4
1.191     harris41 8887: 
                   8888: =item *
                   8889: 
1.243     albertel 8890: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8891: for this url; hashref needs to be given and should be a \%hashname; the
                   8892: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8893: be derived from the env
1.191     harris41 8894: 
                   8895: =item *
                   8896: 
1.243     albertel 8897: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8898: uses critical subroutine
1.191     harris41 8899: 
                   8900: =item *
                   8901: 
1.243     albertel 8902: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8903: all args are optional
1.191     harris41 8904: 
                   8905: =item *
                   8906: 
1.717     albertel 8907: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8908: dumps the complete (or key matching regexp) namespace into a hash
                   8909: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8910: normally &store()ed into
                   8911: 
                   8912: $range should be either an integer '100' (give me the first 100
                   8913:                                            matching records)
                   8914:               or be  two integers sperated by a - with no spaces
                   8915:                  '30-50' (give me the 30th through the 50th matching
                   8916:                           records)
                   8917: 
                   8918: 
                   8919: =item *
                   8920: 
                   8921: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8922: replaces a &store() version of data with a replacement set of data
                   8923: for a particular resource in a namespace passed in the $storehash hash 
                   8924: reference
                   8925: 
                   8926: =item *
                   8927: 
1.243     albertel 8928: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8929: works very similar to store/cstore, but all data is stored in a
                   8930: temporary location and can be reset using tmpreset, $storehash should
                   8931: be a hash reference, returns nothing on success
1.191     harris41 8932: 
                   8933: =item *
                   8934: 
1.243     albertel 8935: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8936: similar to restore, but all data is stored in a temporary location and
                   8937: can be reset using tmpreset. Returns a hash of values on success,
                   8938: error string otherwise.
1.191     harris41 8939: 
                   8940: =item *
                   8941: 
1.243     albertel 8942: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8943: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8944: 
                   8945: =item *
                   8946: 
1.243     albertel 8947: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8948: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8949: 
                   8950: =item *
                   8951: 
1.243     albertel 8952: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8953: namesp ($udom and $uname are optional)
1.191     harris41 8954: 
                   8955: =item *
                   8956: 
1.702     albertel 8957: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8958: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8959: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8960: 
1.702     albertel 8961: $range should be either an integer '100' (give me the first 100
                   8962:                                            matching records)
                   8963:               or be  two integers sperated by a - with no spaces
                   8964:                  '30-50' (give me the 30th through the 50th matching
                   8965:                           records)
1.449     matthew  8966: =item *
                   8967: 
                   8968: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8969: $store can be a scalar, an array reference, or if the amount to be 
                   8970: incremented is > 1, a hash reference.
                   8971: 
                   8972: ($udom and $uname are optional)
1.191     harris41 8973: 
                   8974: =item *
                   8975: 
1.243     albertel 8976: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8977: ($udom and $uname are optional)
1.191     harris41 8978: 
                   8979: =item *
                   8980: 
1.243     albertel 8981: cput($namespace,$storehash,$udom,$uname) : critical put
                   8982: ($udom and $uname are optional)
1.191     harris41 8983: 
                   8984: =item *
                   8985: 
1.748     albertel 8986: newput($namespace,$storehash,$udom,$uname) :
                   8987: 
                   8988: Attempts to store the items in the $storehash, but only if they don't
                   8989: currently exist, if this succeeds you can be certain that you have 
                   8990: successfully created a new key value pair in the $namespace db.
                   8991: 
                   8992: 
                   8993: Args:
                   8994:  $namespace: name of database to store values to
                   8995:  $storehash: hashref to store to the db
                   8996:  $udom: (optional) domain of user containing the db
                   8997:  $uname: (optional) name of user caontaining the db
                   8998: 
                   8999: Returns:
                   9000:  'ok' -> succeeded in storing all keys of $storehash
                   9001:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9002:                         least <key> already existed in the db (other
                   9003:                         requested keys may also already exist)
                   9004:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9005:  'con_lost' -> unable to contact request server
                   9006:  'refused' -> action was not allowed by remote machine
                   9007: 
                   9008: 
                   9009: =item *
                   9010: 
1.243     albertel 9011: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9012: reference filled in from namesp (encrypts the return communication)
                   9013: ($udom and $uname are optional)
1.191     harris41 9014: 
                   9015: =item *
                   9016: 
1.243     albertel 9017: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9018: critical subroutine
                   9019: 
1.806     raeburn  9020: =item *
                   9021: 
1.860     raeburn  9022: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9023: array reference filled in from namespace found in domain level on either
                   9024: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9025: 
                   9026: =item *
                   9027: 
1.860     raeburn  9028: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9029: domain level either on specified domain server ($uhome) or primary domain 
                   9030: server ($udom and $uhome are optional)
1.806     raeburn  9031: 
1.243     albertel 9032: =back
                   9033: 
                   9034: =head2 Network Status Functions
                   9035: 
                   9036: =over 4
1.191     harris41 9037: 
                   9038: =item *
                   9039: 
                   9040: dirlist($uri) : return directory list based on URI
                   9041: 
                   9042: =item *
                   9043: 
1.243     albertel 9044: spareserver() : find server with least workload from spare.tab
                   9045: 
                   9046: =back
                   9047: 
                   9048: =head2 Apache Request
                   9049: 
                   9050: =over 4
1.191     harris41 9051: 
                   9052: =item *
                   9053: 
1.243     albertel 9054: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9055: localhost, posts hash
                   9056: 
                   9057: =back
                   9058: 
                   9059: =head2 Data to String to Data
                   9060: 
                   9061: =over 4
1.191     harris41 9062: 
                   9063: =item *
                   9064: 
1.243     albertel 9065: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9066: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9067: 
                   9068: =item *
                   9069: 
1.243     albertel 9070: hashref2str($hashref) : convert a hashref into a string complete with
                   9071: escaping and '=' and '&' separators, supports elements that are
                   9072: arrayrefs and hashrefs
1.191     harris41 9073: 
                   9074: =item *
                   9075: 
1.243     albertel 9076: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9077: with escaping and '&' separators, supports elements that are arrayrefs
                   9078: and hashrefs
1.191     harris41 9079: 
                   9080: =item *
                   9081: 
1.243     albertel 9082: str2hash($string) : convert string to hash using unescaping and
                   9083: splitting on '=' and '&', supports elements that are arrayrefs and
                   9084: hashrefs
1.191     harris41 9085: 
                   9086: =item *
                   9087: 
1.243     albertel 9088: str2array($string) : convert string to hash using unescaping and
                   9089: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9090: 
                   9091: =back
                   9092: 
                   9093: =head2 Logging Routines
                   9094: 
                   9095: =over 4
                   9096: 
                   9097: These routines allow one to make log messages in the lonnet.log and
                   9098: lonnet.perm logfiles.
1.191     harris41 9099: 
                   9100: =item *
                   9101: 
1.243     albertel 9102: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9103: 
                   9104: =item *
                   9105: 
1.243     albertel 9106: logthis() : append message to the normal lonnet.log file, it gets
                   9107: preiodically rolled over and deleted.
1.191     harris41 9108: 
                   9109: =item *
                   9110: 
1.243     albertel 9111: logperm() : append a permanent message to lonnet.perm.log, this log
                   9112: file never gets deleted by any automated portion of the system, only
                   9113: messages of critical importance should go in here.
                   9114: 
                   9115: =back
                   9116: 
                   9117: =head2 General File Helper Routines
                   9118: 
                   9119: =over 4
1.191     harris41 9120: 
                   9121: =item *
                   9122: 
1.481     raeburn  9123: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9124: (a) files in /uploaded
                   9125:   (i) If a local copy of the file exists - 
                   9126:       compares modification date of local copy with last-modified date for 
                   9127:       definitive version stored on home server for course. If local copy is 
                   9128:       stale, requests a new version from the home server and stores it. 
                   9129:       If the original has been removed from the home server, then local copy 
                   9130:       is unlinked.
                   9131:   (ii) If local copy does not exist -
                   9132:       requests the file from the home server and stores it. 
                   9133:   
                   9134:   If $caller is 'uploadrep':  
                   9135:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9136:     for request for files originally uploaded via DOCS. 
                   9137:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9138:   
                   9139:   Otherwise:
                   9140:      This indicates a call from the content generation phase of the request.
                   9141:      -  returns the entire contents of the file or -1.
                   9142:      
                   9143: (b) files in /res
                   9144:    - returns the entire contents of a file or -1; 
                   9145:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9146: 
1.712     albertel 9147: 
                   9148: =item *
                   9149: 
                   9150: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9151:                   reference
                   9152: 
                   9153: returns either a stat() list of data about the file or an empty list
                   9154: if the file doesn't exist or couldn't find out about it (connection
                   9155: problems or user unknown)
                   9156: 
1.191     harris41 9157: =item *
                   9158: 
1.243     albertel 9159: filelocation($dir,$file) : returns file system location of a file
                   9160: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9161: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9162: and a file of ../bob will become /a/bob)
1.191     harris41 9163: 
                   9164: =item *
                   9165: 
                   9166: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9167: filelocation except for hrefs
                   9168: 
                   9169: =item *
                   9170: 
                   9171: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9172: 
1.243     albertel 9173: =back
                   9174: 
1.608     albertel 9175: =head2 Usererfile file routines (/uploaded*)
                   9176: 
                   9177: =over 4
                   9178: 
                   9179: =item *
                   9180: 
                   9181: userfileupload(): main rotine for putting a file in a user or course's
                   9182:                   filespace, arguments are,
                   9183: 
1.620     albertel 9184:  formname - required - this is the name of the element in $env where the
1.608     albertel 9185:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9186:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9187:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9188:  coursedoc - if true, store the file in the course of the active role
                   9189:              of the current user
                   9190:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9191:          if undefined, it will be placed in "unknown"
                   9192: 
                   9193:  (This routine calls clean_filename() to remove any dangerous
                   9194:  characters from the filename, and then calls finuserfileupload() to
                   9195:  complete the transaction)
                   9196: 
                   9197:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9198:  and /adm/notfound.html if unsuccessful
                   9199: 
                   9200: =item *
                   9201: 
                   9202: clean_filename(): routine for cleaing a filename up for storage in
                   9203:                  userfile space, argument is:
                   9204: 
                   9205:  filename - proposed filename
                   9206: 
                   9207: returns: the new clean filename
                   9208: 
                   9209: =item *
                   9210: 
                   9211: finishuserfileupload(): routine that creaes and sends the file to
                   9212: userspace, probably shouldn't be called directly
                   9213: 
                   9214:   docuname: username or courseid of destination for the file
                   9215:   docudom: domain of user/course of destination for the file
                   9216:   formname: same as for userfileupload()
                   9217:   fname: filename (inculding subdirectories) for the file
                   9218: 
                   9219:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9220:  and /adm/notfound.html if unsuccessful
                   9221: 
                   9222: =item *
                   9223: 
                   9224: renameuserfile(): renames an existing userfile to a new name
                   9225: 
                   9226:   Args:
                   9227:    docuname: username or courseid of destination for the file
                   9228:    docudom: domain of user/course of destination for the file
                   9229:    old: current file name (including any subdirs under userfiles)
                   9230:    new: desired file name (including any subdirs under userfiles)
                   9231: 
                   9232: =item *
                   9233: 
                   9234: mkdiruserfile(): creates a directory is a userfiles dir
                   9235: 
                   9236:   Args:
                   9237:    docuname: username or courseid of destination for the file
                   9238:    docudom: domain of user/course of destination for the file
                   9239:    dir: dir to create (including any subdirs under userfiles)
                   9240: 
                   9241: =item *
                   9242: 
                   9243: removeuserfile(): removes a file that exists in userfiles
                   9244: 
                   9245:   Args:
                   9246:    docuname: username or courseid of destination for the file
                   9247:    docudom: domain of user/course of destination for the file
                   9248:    fname: filname to delete (including any subdirs under userfiles)
                   9249: 
                   9250: =item *
                   9251: 
                   9252: removeuploadedurl(): convience function for removeuserfile()
                   9253: 
                   9254:   Args:
                   9255:    url:  a full /uploaded/... url to delete
                   9256: 
1.747     albertel 9257: =item * 
                   9258: 
                   9259: get_portfile_permissions():
                   9260:   Args:
                   9261:     domain: domain of user or course contain the portfolio files
                   9262:     user: name of user or num of course contain the portfolio files
                   9263:   Returns:
                   9264:     hashref of a dump of the proper file_permissions.db
                   9265:    
                   9266: 
                   9267: =item * 
                   9268: 
                   9269: get_access_controls():
                   9270: 
                   9271: Args:
                   9272:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9273:   group: (optional) the group you want the files associated with
                   9274:   file: (optional) the file you want access info on
                   9275: 
                   9276: Returns:
1.749     raeburn  9277:     a hash (keys are file names) of hashes containing
                   9278:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9279:         values are XML containing access control settings (see below) 
1.747     albertel 9280: 
                   9281: Internal notes:
                   9282: 
1.749     raeburn  9283:  access controls are stored in file_permissions.db as key=value pairs.
                   9284:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9285:         where scope -> public,guest,course,group,domains or users.
                   9286:               end -> UNIX time for end of access (0 -> no end date)
                   9287:               start -> UNIX time for start of access
                   9288: 
                   9289:     value -> XML description of access control
                   9290:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9291:             <start></start>
                   9292:             <end></end>
                   9293: 
                   9294:             <password></password>  for scope type = guest
                   9295: 
                   9296:             <domain></domain>     for scope type = course or group
                   9297:             <number></number>
                   9298:             <roles id="">
                   9299:              <role></role>
                   9300:              <access></access>
                   9301:              <section></section>
                   9302:              <group></group>
                   9303:             </roles>
                   9304: 
                   9305:             <dom></dom>         for scope type = domains
                   9306: 
                   9307:             <users>             for scope type = users
                   9308:              <user>
                   9309:               <uname></uname>
                   9310:               <udom></udom>
                   9311:              </user>
                   9312:             </users>
                   9313:            </scope> 
                   9314:               
                   9315:  Access data is also aggregated for each file in an additional key=value pair:
                   9316:  key -> path to file/file_name\0accesscontrol 
                   9317:  value -> reference to hash
                   9318:           hash contains key = value pairs
                   9319:           where key = uniqueID:scope_end_start
                   9320:                 value = UNIX time record was last updated
                   9321: 
                   9322:           Used to improve speed of look-ups of access controls for each file.  
                   9323:  
                   9324:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9325: 
                   9326: modify_access_controls():
                   9327: 
                   9328: Modifies access controls for a portfolio file
                   9329: Args
                   9330: 1. file name
                   9331: 2. reference to hash of required changes,
                   9332: 3. domain
                   9333: 4. username
                   9334:   where domain,username are the domain of the portfolio owner 
                   9335:   (either a user or a course) 
                   9336: 
                   9337: Returns:
                   9338: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9339: 2. result of deletions ('ok' or 'error', with error message).
                   9340: 3. reference to hash of any new or updated access controls.
                   9341: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9342:    key = integer (inbound ID)
                   9343:    value = uniqueID  
1.747     albertel 9344: 
1.608     albertel 9345: =back
                   9346: 
1.243     albertel 9347: =head2 HTTP Helper Routines
                   9348: 
                   9349: =over 4
                   9350: 
1.191     harris41 9351: =item *
                   9352: 
                   9353: escape() : unpack non-word characters into CGI-compatible hex codes
                   9354: 
                   9355: =item *
                   9356: 
                   9357: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9358: 
1.243     albertel 9359: =back
                   9360: 
                   9361: =head1 PRIVATE SUBROUTINES
                   9362: 
                   9363: =head2 Underlying communication routines (Shouldn't call)
                   9364: 
                   9365: =over 4
                   9366: 
                   9367: =item *
                   9368: 
                   9369: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9370: 
                   9371: =item *
                   9372: 
                   9373: reply() : uses subreply to send a message to remote machine, logs all failures
                   9374: 
                   9375: =item *
                   9376: 
                   9377: critical() : passes a critical message to another server; if cannot
                   9378: get through then place message in connection buffer directory and
                   9379: returns con_delayed, if incapable of saving message, returns
                   9380: con_failed
                   9381: 
                   9382: =item *
                   9383: 
                   9384: reconlonc() : tries to reconnect lonc client processes.
                   9385: 
                   9386: =back
                   9387: 
                   9388: =head2 Resource Access Logging
                   9389: 
                   9390: =over 4
                   9391: 
                   9392: =item *
                   9393: 
                   9394: flushcourselogs() : flush (save) buffer logs and access logs
                   9395: 
                   9396: =item *
                   9397: 
                   9398: courselog($what) : save message for course in hash
                   9399: 
                   9400: =item *
                   9401: 
                   9402: courseacclog($what) : save message for course using &courselog().  Perform
                   9403: special processing for specific resource types (problems, exams, quizzes, etc).
                   9404: 
1.191     harris41 9405: =item *
                   9406: 
                   9407: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9408: as a PerlChildExitHandler
1.243     albertel 9409: 
                   9410: =back
                   9411: 
                   9412: =head2 Other
                   9413: 
                   9414: =over 4
                   9415: 
                   9416: =item *
                   9417: 
                   9418: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9419: 
                   9420: =back
                   9421: 
                   9422: =cut
1.877     foxr     9423: 

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