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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.911   ! raeburn     4: # $Id: lonnet.pm,v 1.910 2007/09/05 17:37:51 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=
1.911   ! raeburn   909:                 &reply("querysend:".&escape($query).':'.
        !           910:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn   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.911   ! raeburn   927:                 my @matches;
        !           928:                 if ($reply =~ /\n/) {
        !           929:                     @matches = split(/\n/,$reply);
        !           930:                 } else {
        !           931:                     @matches = split(/\&/,$reply);
        !           932:                 }
1.899     raeburn   933:                 foreach my $match (@matches) {
                    934:                     my ($uname,$udom,%userhash);
1.911   ! raeburn   935:                     foreach my $entry (split(/:/,$match)) {
        !           936:                         my ($key,$value) =
        !           937:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn   938:                         $userhash{$key} = $value;
                    939:                         if ($key eq 'username') {
                    940:                             $uname = $value;
                    941:                         } elsif ($key eq 'domain') {
                    942:                             $udom = $value;
1.911   ! raeburn   943:                         }
1.899     raeburn   944:                     }
                    945:                     $results{$uname.':'.$udom} = \%userhash;
                    946:                 }
                    947:             }
                    948:         }
                    949:     }
                    950:     return %results;
                    951: }
                    952: 
1.344     www       953: # --------------------------------------------------- Assign a key to a student
                    954: 
                    955: sub assign_access_key {
1.364     www       956: #
                    957: # a valid key looks like uname:udom#comments
                    958: # comments are being appended
                    959: #
1.498     www       960:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    961:     $kdom=
1.620     albertel  962:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       963:     $knum=
1.620     albertel  964:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       965:     $cdom=
1.620     albertel  966:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       967:     $cnum=
1.620     albertel  968:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    969:     $udom=$env{'user.name'} unless (defined($udom));
                    970:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       971:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       972:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  973:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       974:                                                   # assigned to this person
                    975:                                                   # - this should not happen,
1.345     www       976:                                                   # unless something went wrong
                    977:                                                   # the first time around
                    978: # ready to assign
1.364     www       979:         $logentry=$1.'; '.$logentry;
1.496     www       980:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       981:                                                  $kdom,$knum) eq 'ok') {
1.345     www       982: # key now belongs to user
1.346     www       983: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       984:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    985:                 &appenv('environment.'.$envkey => $ckey);
                    986:                 return 'ok';
                    987:             } else {
                    988:                 return 
                    989:   'error: Count not permanently assign key, will need to be re-entered later.';
                    990: 	    }
                    991:         } else {
                    992:             return 'error: Could not assign key, try again later.';
                    993:         }
1.364     www       994:     } elsif (!$existing{$ckey}) {
1.345     www       995: # the key does not exist
                    996: 	return 'error: The key does not exist';
                    997:     } else {
                    998: # the key is somebody else's
                    999: 	return 'error: The key is already in use';
                   1000:     }
1.344     www      1001: }
                   1002: 
1.364     www      1003: # ------------------------------------------ put an additional comment on a key
                   1004: 
                   1005: sub comment_access_key {
                   1006: #
                   1007: # a valid key looks like uname:udom#comments
                   1008: # comments are being appended
                   1009: #
                   1010:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1011:     $cdom=
1.620     albertel 1012:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1013:     $cnum=
1.620     albertel 1014:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1015:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1016:     if ($existing{$ckey}) {
                   1017:         $existing{$ckey}.='; '.$logentry;
                   1018: # ready to assign
1.367     www      1019:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1020:                                                  $cdom,$cnum) eq 'ok') {
                   1021: 	    return 'ok';
                   1022:         } else {
                   1023: 	    return 'error: Count not store comment.';
                   1024:         }
                   1025:     } else {
                   1026: # the key does not exist
                   1027: 	return 'error: The key does not exist';
                   1028:     }
                   1029: }
                   1030: 
1.344     www      1031: # ------------------------------------------------------ Generate a set of keys
                   1032: 
                   1033: sub generate_access_keys {
1.364     www      1034:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1035:     $cdom=
1.620     albertel 1036:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1037:     $cnum=
1.620     albertel 1038:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1039:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1040:     unless (($cdom) && ($cnum)) { return 0; }
                   1041:     if ($number>10000) { return 0; }
                   1042:     sleep(2); # make sure don't get same seed twice
                   1043:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1044:     my $total=0;
                   1045:     for (my $i=1;$i<=$number;$i++) {
                   1046:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1047:                   sprintf("%lx",int(100000*rand)).'-'.
                   1048:                   sprintf("%lx",int(100000*rand));
                   1049:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1050:        $newkey=~s/0/h/g; # and also 0 and O
                   1051:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1052:        if ($existing{$newkey}) {
                   1053:            $i--;
                   1054:        } else {
1.364     www      1055: 	  if (&put('accesskeys',
                   1056:               { $newkey => '# generated '.localtime().
1.620     albertel 1057:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1058:                            '; '.$logentry },
                   1059: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1060:               $total++;
                   1061: 	  }
                   1062:        }
                   1063:     }
1.620     albertel 1064:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1065:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1066:     return $total;
                   1067: }
                   1068: 
                   1069: # ------------------------------------------------------- Validate an accesskey
                   1070: 
                   1071: sub validate_access_key {
                   1072:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1073:     $cdom=
1.620     albertel 1074:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1075:     $cnum=
1.620     albertel 1076:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1077:     $udom=$env{'user.domain'} unless (defined($udom));
                   1078:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1079:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1080:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1081: }
                   1082: 
                   1083: # ------------------------------------- Find the section of student in a course
1.652     albertel 1084: sub devalidate_getsection_cache {
                   1085:     my ($udom,$unam,$courseid)=@_;
                   1086:     my $hashid="$udom:$unam:$courseid";
                   1087:     &devalidate_cache_new('getsection',$hashid);
                   1088: }
1.298     matthew  1089: 
1.815     albertel 1090: sub courseid_to_courseurl {
                   1091:     my ($courseid) = @_;
                   1092:     #already url style courseid
                   1093:     return $courseid if ($courseid =~ m{^/});
                   1094: 
                   1095:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1096: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1097: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1098: 	return "/$cdom/$cnum";
                   1099:     }
                   1100: 
                   1101:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1102:     if (exists($courseinfo{'num'})) {
                   1103: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1104:     }
                   1105: 
                   1106:     return undef;
                   1107: }
                   1108: 
1.298     matthew  1109: sub getsection {
                   1110:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1111:     my $cachetime=1800;
1.551     albertel 1112: 
                   1113:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1114:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1115:     if (defined($cached)) { return $result; }
                   1116: 
1.298     matthew  1117:     my %Pending; 
                   1118:     my %Expired;
                   1119:     #
                   1120:     # Each role can either have not started yet (pending), be active, 
                   1121:     #    or have expired.
                   1122:     #
                   1123:     # If there is an active role, we are done.
                   1124:     #
                   1125:     # If there is more than one role which has not started yet, 
                   1126:     #     choose the one which will start sooner
                   1127:     # If there is one role which has not started yet, return it.
                   1128:     #
                   1129:     # If there is more than one expired role, choose the one which ended last.
                   1130:     # If there is a role which has expired, return it.
                   1131:     #
1.815     albertel 1132:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1133:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1134:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1135:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1136:         my $section=$1;
                   1137:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1138:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1139:         my $now=time;
1.548     albertel 1140:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1141:             $Expired{$end}=$section;
                   1142:             next;
                   1143:         }
1.548     albertel 1144:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1145:             $Pending{$start}=$section;
                   1146:             next;
                   1147:         }
1.599     albertel 1148:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1149:     }
                   1150:     #
                   1151:     # Presumedly there will be few matching roles from the above
                   1152:     # loop and the sorting time will be negligible.
                   1153:     if (scalar(keys(%Pending))) {
                   1154:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1155:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1156:     } 
                   1157:     if (scalar(keys(%Expired))) {
                   1158:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1159:         my $time = pop(@sorted);
1.599     albertel 1160:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1161:     }
1.599     albertel 1162:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1163: }
1.70      www      1164: 
1.599     albertel 1165: sub save_cache {
                   1166:     &purge_remembered();
1.722     albertel 1167:     #&Apache::loncommon::validate_page();
1.620     albertel 1168:     undef(%env);
1.780     albertel 1169:     undef($env_loaded);
1.599     albertel 1170: }
1.452     albertel 1171: 
1.599     albertel 1172: my $to_remember=-1;
                   1173: my %remembered;
                   1174: my %accessed;
                   1175: my $kicks=0;
                   1176: my $hits=0;
1.849     albertel 1177: sub make_key {
                   1178:     my ($name,$id) = @_;
1.872     albertel 1179:     if (length($id) > 65 
                   1180: 	&& length(&escape($id)) > 200) {
                   1181: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1182:     }
1.849     albertel 1183:     return &escape($name.':'.$id);
                   1184: }
                   1185: 
1.599     albertel 1186: sub devalidate_cache_new {
                   1187:     my ($name,$id,$debug) = @_;
                   1188:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1189:     $id=&make_key($name,$id);
1.599     albertel 1190:     $memcache->delete($id);
                   1191:     delete($remembered{$id});
                   1192:     delete($accessed{$id});
                   1193: }
                   1194: 
                   1195: sub is_cached_new {
                   1196:     my ($name,$id,$debug) = @_;
1.849     albertel 1197:     $id=&make_key($name,$id);
1.599     albertel 1198:     if (exists($remembered{$id})) {
                   1199: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1200: 	$accessed{$id}=[&gettimeofday()];
                   1201: 	$hits++;
                   1202: 	return ($remembered{$id},1);
                   1203:     }
                   1204:     my $value = $memcache->get($id);
                   1205:     if (!(defined($value))) {
                   1206: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1207: 	return (undef,undef);
1.416     albertel 1208:     }
1.599     albertel 1209:     if ($value eq '__undef__') {
                   1210: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1211: 	$value=undef;
                   1212:     }
                   1213:     &make_room($id,$value,$debug);
                   1214:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1215:     return ($value,1);
                   1216: }
                   1217: 
                   1218: sub do_cache_new {
                   1219:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1220:     $id=&make_key($name,$id);
1.599     albertel 1221:     my $setvalue=$value;
                   1222:     if (!defined($setvalue)) {
                   1223: 	$setvalue='__undef__';
                   1224:     }
1.623     albertel 1225:     if (!defined($time) ) {
                   1226: 	$time=600;
                   1227:     }
1.599     albertel 1228:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1229:     my $result = $memcache->set($id,$setvalue,$time);
                   1230:     if (! $result) {
1.872     albertel 1231: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1232: 	$memcache->disconnect_all();
1.872     albertel 1233:     }
1.600     albertel 1234:     # need to make a copy of $value
                   1235:     #&make_room($id,$value,$debug);
1.599     albertel 1236:     return $value;
                   1237: }
                   1238: 
                   1239: sub make_room {
                   1240:     my ($id,$value,$debug)=@_;
                   1241:     $remembered{$id}=$value;
                   1242:     if ($to_remember<0) { return; }
                   1243:     $accessed{$id}=[&gettimeofday()];
                   1244:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1245:     my $to_kick;
                   1246:     my $max_time=0;
                   1247:     foreach my $other (keys(%accessed)) {
                   1248: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1249: 	    $to_kick=$other;
                   1250: 	    $max_time=&tv_interval($accessed{$other});
                   1251: 	}
                   1252:     }
                   1253:     delete($remembered{$to_kick});
                   1254:     delete($accessed{$to_kick});
                   1255:     $kicks++;
                   1256:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1257:     return;
                   1258: }
                   1259: 
1.599     albertel 1260: sub purge_remembered {
1.604     albertel 1261:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1262:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1263:     undef(%remembered);
                   1264:     undef(%accessed);
1.428     albertel 1265: }
1.70      www      1266: # ------------------------------------- Read an entry from a user's environment
                   1267: 
                   1268: sub userenvironment {
                   1269:     my ($udom,$unam,@what)=@_;
                   1270:     my %returnhash=();
                   1271:     my @answer=split(/\&/,
                   1272:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1273:                       &homeserver($unam,$udom)));
                   1274:     my $i;
                   1275:     for ($i=0;$i<=$#what;$i++) {
                   1276: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1277:     }
                   1278:     return %returnhash;
1.1       albertel 1279: }
                   1280: 
1.617     albertel 1281: # ---------------------------------------------------------- Get a studentphoto
                   1282: sub studentphoto {
                   1283:     my ($udom,$unam,$ext) = @_;
                   1284:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1285:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1286:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1287:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1288:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1289:             } else {
                   1290:                 my ($result,$perm_reqd)=
1.707     albertel 1291: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1292:                 if ($result eq 'ok') {
                   1293:                     if (!($perm_reqd eq 'yes')) {
                   1294:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1295:                     }
                   1296:                 }
                   1297:             }
                   1298:         }
                   1299:     } else {
                   1300:         my ($result,$perm_reqd) = 
1.707     albertel 1301: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1302:         if ($result eq 'ok') {
                   1303:             if (!($perm_reqd eq 'yes')) {
                   1304:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1305:             }
                   1306:         }
                   1307:     }
                   1308:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1309: }
                   1310: 
                   1311: sub retrievestudentphoto {
                   1312:     my ($udom,$unam,$ext,$type) = @_;
                   1313:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1314:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1315:     if ($ret eq 'ok') {
                   1316:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1317:         if ($type eq 'thumbnail') {
                   1318:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1319:         }
                   1320:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1321:         return $tokenurl;
                   1322:     } else {
                   1323:         if ($type eq 'thumbnail') {
                   1324:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1325:         } else { 
                   1326:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1327:         }
1.617     albertel 1328:     }
                   1329: }
                   1330: 
1.263     www      1331: # -------------------------------------------------------------------- New chat
                   1332: 
                   1333: sub chatsend {
1.724     raeburn  1334:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1335:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1336:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1337:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1338:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1339: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1340: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1341: }
                   1342: 
                   1343: # ------------------------------------------ Find current version of a resource
                   1344: 
                   1345: sub getversion {
                   1346:     my $fname=&clutter(shift);
                   1347:     unless ($fname=~/^\/res\//) { return -1; }
                   1348:     return &currentversion(&filelocation('',$fname));
                   1349: }
                   1350: 
                   1351: sub currentversion {
                   1352:     my $fname=shift;
1.599     albertel 1353:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1354:     if (defined($cached)) { return $result; }
1.292     www      1355:     my $author=$fname;
                   1356:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1357:     my ($udom,$uname)=split(/\//,$author);
                   1358:     my $home=homeserver($uname,$udom);
                   1359:     if ($home eq 'no_host') { 
                   1360:         return -1; 
                   1361:     }
                   1362:     my $answer=reply("currentversion:$fname",$home);
                   1363:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1364: 	return -1;
                   1365:     }
1.599     albertel 1366:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1367: }
                   1368: 
1.1       albertel 1369: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1370: 
1.1       albertel 1371: sub subscribe {
                   1372:     my $fname=shift;
1.761     raeburn  1373:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1374:     $fname=~s/[\n\r]//g;
1.1       albertel 1375:     my $author=$fname;
                   1376:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1377:     my ($udom,$uname)=split(/\//,$author);
                   1378:     my $home=homeserver($uname,$udom);
1.335     albertel 1379:     if ($home eq 'no_host') {
                   1380:         return 'not_found';
1.1       albertel 1381:     }
                   1382:     my $answer=reply("sub:$fname",$home);
1.64      www      1383:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1384: 	$answer.=' by '.$home;
                   1385:     }
1.1       albertel 1386:     return $answer;
                   1387: }
                   1388:     
1.8       www      1389: # -------------------------------------------------------------- Replicate file
                   1390: 
                   1391: sub repcopy {
                   1392:     my $filename=shift;
1.23      www      1393:     $filename=~s/\/+/\//g;
1.607     raeburn  1394:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1395:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1396:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1397: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1398: 	return &repcopy_userfile($filename);
                   1399:     }
1.532     albertel 1400:     $filename=~s/[\n\r]//g;
1.8       www      1401:     my $transname="$filename.in.transfer";
1.828     www      1402: # FIXME: this should flock
1.607     raeburn  1403:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1404:     my $remoteurl=subscribe($filename);
1.64      www      1405:     if ($remoteurl =~ /^con_lost by/) {
                   1406: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1407:            return 'unavailable';
1.8       www      1408:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1409: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1410: 	   return 'not_found';
1.64      www      1411:     } elsif ($remoteurl =~ /^rejected by/) {
                   1412: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1413:            return 'forbidden';
1.20      www      1414:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1415:            return 'ok';
1.8       www      1416:     } else {
1.290     www      1417:         my $author=$filename;
                   1418:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1419:         my ($udom,$uname)=split(/\//,$author);
                   1420:         my $home=homeserver($uname,$udom);
                   1421:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1422:            my @parts=split(/\//,$filename);
                   1423:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1424:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1425:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1426: 	       return 'bad_request';
1.8       www      1427:            }
                   1428:            my $count;
                   1429:            for ($count=5;$count<$#parts;$count++) {
                   1430:                $path.="/$parts[$count]";
                   1431:                if ((-e $path)!=1) {
                   1432: 		   mkdir($path,0777);
                   1433:                }
                   1434:            }
                   1435:            my $ua=new LWP::UserAgent;
                   1436:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1437:            my $response=$ua->request($request,$transname);
                   1438:            if ($response->is_error()) {
                   1439: 	       unlink($transname);
                   1440:                my $message=$response->status_line;
1.672     albertel 1441:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1442:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1443:                return 'unavailable';
1.8       www      1444:            } else {
1.16      www      1445: 	       if ($remoteurl!~/\.meta$/) {
                   1446:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1447:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1448:                   if ($mresponse->is_error()) {
                   1449: 		      unlink($filename.'.meta');
                   1450:                       &logthis(
1.672     albertel 1451:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1452:                   }
                   1453: 	       }
1.8       www      1454:                rename($transname,$filename);
1.607     raeburn  1455:                return 'ok';
1.8       www      1456:            }
1.290     www      1457:        }
1.8       www      1458:     }
1.330     www      1459: }
                   1460: 
                   1461: # ------------------------------------------------ Get server side include body
                   1462: sub ssi_body {
1.381     albertel 1463:     my ($filelink,%form)=@_;
1.606     matthew  1464:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1465:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1466:     }
1.330     www      1467:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1468:                                      &ssi($filelink,%form));
1.778     albertel 1469:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1470:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1471:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1472:     return $output;
1.8       www      1473: }
                   1474: 
1.15      www      1475: # --------------------------------------------------------- Server Side Include
                   1476: 
1.782     albertel 1477: sub absolute_url {
                   1478:     my ($host_name) = @_;
                   1479:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1480:     if ($host_name eq '') {
                   1481: 	$host_name = $ENV{'SERVER_NAME'};
                   1482:     }
                   1483:     return $protocol.$host_name;
                   1484: }
                   1485: 
1.15      www      1486: sub ssi {
                   1487: 
1.23      www      1488:     my ($fn,%form)=@_;
1.15      www      1489: 
                   1490:     my $ua=new LWP::UserAgent;
1.23      www      1491:     
                   1492:     my $request;
1.711     albertel 1493: 
                   1494:     $form{'no_update_last_known'}=1;
1.895     albertel 1495:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1496:     if (%form) {
1.782     albertel 1497:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1498:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1499:     } else {
1.782     albertel 1500:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1501:     }
                   1502: 
1.15      www      1503:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1504:     my $response=$ua->request($request);
                   1505: 
1.324     www      1506:     return $response->content;
                   1507: }
                   1508: 
                   1509: sub externalssi {
                   1510:     my ($url)=@_;
                   1511:     my $ua=new LWP::UserAgent;
                   1512:     my $request=new HTTP::Request('GET',$url);
                   1513:     my $response=$ua->request($request);
1.15      www      1514:     return $response->content;
                   1515: }
1.254     www      1516: 
1.492     albertel 1517: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1518: 
                   1519: sub allowuploaded {
                   1520:     my ($srcurl,$url)=@_;
                   1521:     $url=&clutter(&declutter($url));
                   1522:     my $dir=$url;
                   1523:     $dir=~s/\/[^\/]+$//;
                   1524:     my %httpref=();
                   1525:     my $httpurl=&hreflocation('',$url);
                   1526:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1527:     &Apache::lonnet::appenv(%httpref);
1.254     www      1528: }
1.477     raeburn  1529: 
1.478     albertel 1530: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1531: # input: action, courseID, current domain, intended
1.637     raeburn  1532: #        path to file, source of file, instruction to parse file for objects,
                   1533: #        ref to hash for embedded objects,
                   1534: #        ref to hash for codebase of java objects.
                   1535: #
1.485     raeburn  1536: # output: url to file (if action was uploaddoc), 
                   1537: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1538: #
1.478     albertel 1539: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1540: # course.
1.477     raeburn  1541: #
1.478     albertel 1542: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1543: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1544: #          course's home server.
1.477     raeburn  1545: #
1.478     albertel 1546: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1547: #          be copied from $source (current location) to 
                   1548: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1549: #         and will then be copied to
                   1550: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1551: #         course's home server.
1.485     raeburn  1552: #
1.481     raeburn  1553: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1554: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1555: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1556: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1557: #         in course's home server.
1.637     raeburn  1558: #
1.477     raeburn  1559: 
                   1560: sub process_coursefile {
1.638     albertel 1561:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1562:     my $fetchresult;
1.638     albertel 1563:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1564:     if ($action eq 'propagate') {
1.638     albertel 1565:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1566: 			     $home);
1.481     raeburn  1567:     } else {
1.477     raeburn  1568:         my $fpath = '';
                   1569:         my $fname = $file;
1.478     albertel 1570:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1571:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1572:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1573:         if ($action eq 'copy') {
                   1574:             if ($source eq '') {
                   1575:                 $fetchresult = 'no source file';
                   1576:                 return $fetchresult;
                   1577:             } else {
                   1578:                 my $destination = $filepath.'/'.$fname;
                   1579:                 rename($source,$destination);
                   1580:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1581:                                  $home);
1.481     raeburn  1582:             }
                   1583:         } elsif ($action eq 'uploaddoc') {
                   1584:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1585:             print $fh $env{'form.'.$source};
1.481     raeburn  1586:             close($fh);
1.637     raeburn  1587:             if ($parser eq 'parse') {
                   1588:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1589:                 unless ($parse_result eq 'ok') {
                   1590:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1591:                 }
                   1592:             }
1.477     raeburn  1593:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1594:                                  $home);
1.481     raeburn  1595:             if ($fetchresult eq 'ok') {
                   1596:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1597:             } else {
                   1598:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1599:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1600:                 return '/adm/notfound.html';
                   1601:             }
1.477     raeburn  1602:         }
                   1603:     }
1.485     raeburn  1604:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1605:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1606:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1607:     }
                   1608:     return $fetchresult;
                   1609: }
                   1610: 
1.637     raeburn  1611: sub build_filepath {
                   1612:     my ($fpath) = @_;
                   1613:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1614:     unless ($fpath eq '') {
                   1615:         my @parts=split('/',$fpath);
                   1616:         foreach my $part (@parts) {
                   1617:             $filepath.= '/'.$part;
                   1618:             if ((-e $filepath)!=1) {
                   1619:                 mkdir($filepath,0777);
                   1620:             }
                   1621:         }
                   1622:     }
                   1623:     return $filepath;
                   1624: }
                   1625: 
                   1626: sub store_edited_file {
1.638     albertel 1627:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1628:     my $file = $primary_url;
                   1629:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1630:     my $fpath = '';
                   1631:     my $fname = $file;
                   1632:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1633:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1634:     my $filepath = &build_filepath($fpath);
                   1635:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1636:     print $fh $content;
                   1637:     close($fh);
1.638     albertel 1638:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1639:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1640: 			  $home);
1.637     raeburn  1641:     if ($$fetchresult eq 'ok') {
                   1642:         return '/uploaded/'.$fpath.'/'.$fname;
                   1643:     } else {
1.638     albertel 1644:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1645: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1646:         return '/adm/notfound.html';
                   1647:     }
                   1648: }
                   1649: 
1.531     albertel 1650: sub clean_filename {
1.831     albertel 1651:     my ($fname,$args)=@_;
1.315     www      1652: # Replace Windows backslashes by forward slashes
1.257     www      1653:     $fname=~s/\\/\//g;
1.831     albertel 1654:     if (!$args->{'keep_path'}) {
                   1655:         # Get rid of everything but the actual filename
                   1656: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1657:     }
1.315     www      1658: # Replace spaces by underscores
                   1659:     $fname=~s/\s+/\_/g;
                   1660: # Replace all other weird characters by nothing
1.831     albertel 1661:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1662: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1663: # numbers
                   1664:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1665:     return $fname;
                   1666: }
                   1667: 
1.608     albertel 1668: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1669: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1670: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1671: #        $coursedoc - if true up to the current course
                   1672: #                     if false
                   1673: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1674: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1675: #        $allfiles - reference to hash for embedded objects
                   1676: #        $codebase - reference to hash for codebase of java objects
                   1677: #        $desuname - username for permanent storage of uploaded file
                   1678: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1679: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1680: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1681: # 
1.686     albertel 1682: # output: url of file in userspace, or error: <message> 
                   1683: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1684: 
                   1685: 
1.531     albertel 1686: sub userfileupload {
1.860     raeburn  1687:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1688:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1689:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1690:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1691:     $fname=&clean_filename($fname);
1.315     www      1692: # See if there is anything left
1.257     www      1693:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1694:     chop($env{'form.'.$formname});
1.523     raeburn  1695:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1696:         my $now = time;
                   1697:         my $filepath = 'tmp/helprequests/'.$now;
                   1698:         my @parts=split(/\//,$filepath);
                   1699:         my $fullpath = $perlvar{'lonDaemons'};
                   1700:         for (my $i=0;$i<@parts;$i++) {
                   1701:             $fullpath .= '/'.$parts[$i];
                   1702:             if ((-e $fullpath)!=1) {
                   1703:                 mkdir($fullpath,0777);
                   1704:             }
                   1705:         }
                   1706:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1707:         print $fh $env{'form.'.$formname};
1.523     raeburn  1708:         close($fh);
1.741     raeburn  1709:         return $fullpath.'/'.$fname;
                   1710:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1711:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1712:                        '_'.$env{'user.domain'}.'/pending';
                   1713:         my @parts=split(/\//,$filepath);
                   1714:         my $fullpath = $perlvar{'lonDaemons'};
                   1715:         for (my $i=0;$i<@parts;$i++) {
                   1716:             $fullpath .= '/'.$parts[$i];
                   1717:             if ((-e $fullpath)!=1) {
                   1718:                 mkdir($fullpath,0777);
                   1719:             }
                   1720:         }
                   1721:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1722:         print $fh $env{'form.'.$formname};
                   1723:         close($fh);
                   1724:         return $fullpath.'/'.$fname;
1.523     raeburn  1725:     }
1.719     banghart 1726:     
1.258     www      1727: # Create the directory if not present
1.493     albertel 1728:     $fname="$subdir/$fname";
1.259     www      1729:     if ($coursedoc) {
1.638     albertel 1730: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1731: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1732:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1733:             return &finishuserfileupload($docuname,$docudom,
                   1734: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1735: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1736:         } else {
1.620     albertel 1737:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1738:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1739: 				       $fname,$formname,$parser,
                   1740: 				       $allfiles,$codebase);
1.481     raeburn  1741:         }
1.719     banghart 1742:     } elsif (defined($destuname)) {
                   1743:         my $docuname=$destuname;
                   1744:         my $docudom=$destudom;
1.860     raeburn  1745: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1746: 				     $parser,$allfiles,$codebase,
                   1747:                                      $thumbwidth,$thumbheight);
1.719     banghart 1748:         
1.259     www      1749:     } else {
1.638     albertel 1750:         my $docuname=$env{'user.name'};
                   1751:         my $docudom=$env{'user.domain'};
1.714     raeburn  1752:         if (exists($env{'form.group'})) {
                   1753:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1754:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1755:         }
1.860     raeburn  1756: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1757: 				     $parser,$allfiles,$codebase,
                   1758:                                      $thumbwidth,$thumbheight);
1.259     www      1759:     }
1.271     www      1760: }
                   1761: 
                   1762: sub finishuserfileupload {
1.860     raeburn  1763:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1764:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1765:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1766:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1767:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1768:     $file=$fname;
                   1769:     if ($fname=~m|/|) {
                   1770:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1771: 	$path.=$fnamepath.'/';
                   1772:     }
1.259     www      1773:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1774:     my $count;
                   1775:     for ($count=4;$count<=$#parts;$count++) {
                   1776:         $filepath.="/$parts[$count]";
                   1777:         if ((-e $filepath)!=1) {
                   1778: 	    mkdir($filepath,0777);
                   1779:         }
                   1780:     }
                   1781: # Save the file
                   1782:     {
1.701     albertel 1783: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1784: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1785: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1786: 	    return '/adm/notfound.html';
                   1787: 	}
                   1788: 	if (!print FH ($env{'form.'.$formname})) {
                   1789: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1790: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1791: 	    return '/adm/notfound.html';
                   1792: 	}
1.570     albertel 1793: 	close(FH);
1.258     www      1794:     }
1.637     raeburn  1795:     if ($parser eq 'parse') {
1.638     albertel 1796:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1797: 						   $codebase);
1.637     raeburn  1798:         unless ($parse_result eq 'ok') {
1.638     albertel 1799:             &logthis('Failed to parse '.$filepath.$file.
                   1800: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1801:         }
                   1802:     }
1.860     raeburn  1803:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1804:         my $input = $filepath.'/'.$file;
                   1805:         my $output = $filepath.'/'.'tn-'.$file;
                   1806:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1807:         system("convert -sample $thumbsize $input $output");
                   1808:         if (-e $filepath.'/'.'tn-'.$file) {
                   1809:             $fetchthumb  = 1; 
                   1810:         }
                   1811:     }
1.858     raeburn  1812:  
1.259     www      1813: # Notify homeserver to grep it
                   1814: #
1.638     albertel 1815:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1816:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1817:     if ($fetchresult eq 'ok') {
1.860     raeburn  1818:         if ($fetchthumb) {
                   1819:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1820:             if ($thumbresult ne 'ok') {
                   1821:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1822:                          $docuhome.': '.$thumbresult);
                   1823:             }
                   1824:         }
1.259     www      1825: #
1.258     www      1826: # Return the URL to it
1.494     albertel 1827:         return '/uploaded/'.$path.$file;
1.263     www      1828:     } else {
1.494     albertel 1829:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1830: 		 ': '.$fetchresult);
1.263     www      1831:         return '/adm/notfound.html';
1.858     raeburn  1832:     }
1.493     albertel 1833: }
                   1834: 
1.637     raeburn  1835: sub extract_embedded_items {
1.648     raeburn  1836:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1837:     my @state = ();
                   1838:     my %javafiles = (
                   1839:                       codebase => '',
                   1840:                       code => '',
                   1841:                       archive => ''
                   1842:                     );
                   1843:     my %mediafiles = (
                   1844:                       src => '',
                   1845:                       movie => '',
                   1846:                      );
1.648     raeburn  1847:     my $p;
                   1848:     if ($content) {
                   1849:         $p = HTML::LCParser->new($content);
                   1850:     } else {
                   1851:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1852:     }
1.641     albertel 1853:     while (my $t=$p->get_token()) {
1.640     albertel 1854: 	if ($t->[0] eq 'S') {
                   1855: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1856: 	    push(@state, $tagname);
1.648     raeburn  1857:             if (lc($tagname) eq 'allow') {
                   1858:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1859:             }
1.640     albertel 1860: 	    if (lc($tagname) eq 'img') {
                   1861: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1862: 	    }
1.886     albertel 1863: 	    if (lc($tagname) eq 'a') {
                   1864: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1865: 	    }
1.645     raeburn  1866:             if (lc($tagname) eq 'script') {
                   1867:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1868:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1869:                 } else {
                   1870:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1871:                 }
                   1872:             }
                   1873:             if (lc($tagname) eq 'link') {
                   1874:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1875:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1876:                 }
                   1877:             }
1.640     albertel 1878: 	    if (lc($tagname) eq 'object' ||
                   1879: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1880: 		foreach my $item (keys(%javafiles)) {
                   1881: 		    $javafiles{$item} = '';
                   1882: 		}
                   1883: 	    }
                   1884: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1885: 		my $name = lc($attr->{'name'});
                   1886: 		foreach my $item (keys(%javafiles)) {
                   1887: 		    if ($name eq $item) {
                   1888: 			$javafiles{$item} = $attr->{'value'};
                   1889: 			last;
                   1890: 		    }
                   1891: 		}
                   1892: 		foreach my $item (keys(%mediafiles)) {
                   1893: 		    if ($name eq $item) {
                   1894: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1895: 			last;
                   1896: 		    }
                   1897: 		}
                   1898: 	    }
                   1899: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1900: 		foreach my $item (keys(%javafiles)) {
                   1901: 		    if ($attr->{$item}) {
                   1902: 			$javafiles{$item} = $attr->{$item};
                   1903: 			last;
                   1904: 		    }
                   1905: 		}
                   1906: 		foreach my $item (keys(%mediafiles)) {
                   1907: 		    if ($attr->{$item}) {
                   1908: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1909: 			last;
                   1910: 		    }
                   1911: 		}
                   1912: 	    }
                   1913: 	} elsif ($t->[0] eq 'E') {
                   1914: 	    my ($tagname) = ($t->[1]);
                   1915: 	    if ($javafiles{'codebase'} ne '') {
                   1916: 		$javafiles{'codebase'} .= '/';
                   1917: 	    }  
                   1918: 	    if (lc($tagname) eq 'applet' ||
                   1919: 		lc($tagname) eq 'object' ||
                   1920: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1921: 		) {
                   1922: 		foreach my $item (keys(%javafiles)) {
                   1923: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1924: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1925: 			&add_filetype($allfiles,$file,$item);
                   1926: 		    }
                   1927: 		}
                   1928: 	    } 
                   1929: 	    pop @state;
                   1930: 	}
                   1931:     }
1.637     raeburn  1932:     return 'ok';
                   1933: }
                   1934: 
1.639     albertel 1935: sub add_filetype {
                   1936:     my ($allfiles,$file,$type)=@_;
                   1937:     if (exists($allfiles->{$file})) {
                   1938: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1939: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1940: 	}
                   1941:     } else {
                   1942: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1943:     }
                   1944: }
                   1945: 
1.493     albertel 1946: sub removeuploadedurl {
                   1947:     my ($url)=@_;
                   1948:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1949:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1950: }
                   1951: 
                   1952: sub removeuserfile {
                   1953:     my ($docuname,$docudom,$fname)=@_;
                   1954:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1955:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1956:     if ($result eq 'ok') {
                   1957:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1958:             my $metafile = $fname.'.meta';
                   1959:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1960: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1961:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1962:             my $sqlresult = 
1.823     albertel 1963:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1964:                                         'portfolio_metadata',$group,
                   1965:                                         'delete');
1.798     raeburn  1966:         }
                   1967:     }
                   1968:     return $result;
1.257     www      1969: }
1.15      www      1970: 
1.530     albertel 1971: sub mkdiruserfile {
                   1972:     my ($docuname,$docudom,$dir)=@_;
                   1973:     my $home=&homeserver($docuname,$docudom);
                   1974:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1975: }
                   1976: 
1.531     albertel 1977: sub renameuserfile {
                   1978:     my ($docuname,$docudom,$old,$new)=@_;
                   1979:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1980:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1981:                         &escape("$old").':'.&escape("$new"),$home);
                   1982:     if ($result eq 'ok') {
                   1983:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1984:             my $oldmeta = $old.'.meta';
                   1985:             my $newmeta = $new.'.meta';
                   1986:             my $metaresult = 
                   1987:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1988: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1989:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1990:             my $sqlresult = 
1.823     albertel 1991:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1992:                                         'portfolio_metadata',$group,
                   1993:                                         'delete');
1.798     raeburn  1994:         }
                   1995:     }
                   1996:     return $result;
1.531     albertel 1997: }
                   1998: 
1.14      www      1999: # ------------------------------------------------------------------------- Log
                   2000: 
                   2001: sub log {
                   2002:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2003:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2004: }
                   2005: 
                   2006: # ------------------------------------------------------------------ Course Log
1.352     www      2007: #
                   2008: # This routine flushes several buffers of non-mission-critical nature
                   2009: #
1.157     www      2010: 
                   2011: sub flushcourselogs {
1.352     www      2012:     &logthis('Flushing log buffers');
                   2013: #
                   2014: # course logs
                   2015: # This is a log of all transactions in a course, which can be used
                   2016: # for data mining purposes
                   2017: #
                   2018: # It also collects the courseid database, which lists last transaction
                   2019: # times and course titles for all courseids
                   2020: #
                   2021:     my %courseidbuffer=();
1.800     albertel 2022:     foreach my $crsid (keys %courselogs) {
1.352     www      2023:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2024: 		          &escape($courselogs{$crsid}),
                   2025: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2026: 	    delete $courselogs{$crsid};
                   2027:         } else {
                   2028:             &logthis('Failed to flush log buffer for '.$crsid);
                   2029:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2030:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2031:                         " exceeded maximum size, deleting.</font>");
                   2032:                delete $courselogs{$crsid};
                   2033:             }
1.352     www      2034:         }
                   2035:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2036:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2037: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2038:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2039:         } else {
                   2040:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2041: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2042:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2043:         }
1.191     harris41 2044:     }
1.352     www      2045: #
                   2046: # Write course id database (reverse lookup) to homeserver of courses 
                   2047: # Is used in pickcourse
                   2048: #
1.840     albertel 2049:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2050:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2051: 		     $crs_home);
1.352     www      2052:     }
                   2053: #
                   2054: # File accesses
                   2055: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2056: #
1.449     matthew  2057:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2058:         if ($entry =~ /___count$/) {
                   2059:             my ($dom,$name);
1.807     albertel 2060:             ($dom,$name,undef)=
1.811     albertel 2061: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2062:             if (! defined($dom) || $dom eq '' || 
                   2063:                 ! defined($name) || $name eq '') {
1.620     albertel 2064:                 my $cid = $env{'request.course.id'};
                   2065:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2066:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2067:             }
1.450     matthew  2068:             my $value = $accesshash{$entry};
                   2069:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2070:             my %temphash=($url => $value);
1.449     matthew  2071:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2072:             if ($result eq 'ok') {
                   2073:                 delete $accesshash{$entry};
                   2074:             } elsif ($result eq 'unknown_cmd') {
                   2075:                 # Target server has old code running on it.
1.450     matthew  2076:                 my %temphash=($entry => $value);
1.449     matthew  2077:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2078:                     delete $accesshash{$entry};
                   2079:                 }
                   2080:             }
                   2081:         } else {
1.811     albertel 2082:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2083:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2084:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2085:                 delete $accesshash{$entry};
                   2086:             }
1.185     www      2087:         }
1.191     harris41 2088:     }
1.352     www      2089: #
                   2090: # Roles
                   2091: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2092: #
1.800     albertel 2093:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2094:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2095: 	    split(/\:/,$entry);
                   2096:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2097:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2098:                 $rudom,$runame) eq 'ok') {
                   2099: 	    delete $userrolehash{$entry};
                   2100:         }
                   2101:     }
1.662     raeburn  2102: #
                   2103: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2104: #
                   2105:     my %domrolebuffer = ();
                   2106:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2107:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2108:         if ($domrolebuffer{$rudom}) {
                   2109:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2110:                       '='.&escape($domainrolehash{$entry});
                   2111:         } else {
                   2112:             $domrolebuffer{$rudom}.=&escape($entry).
                   2113:                       '='.&escape($domainrolehash{$entry});
                   2114:         }
                   2115:         delete $domainrolehash{$entry};
                   2116:     }
                   2117:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2118: 	my %servers = &get_servers($dom,'library');
                   2119: 	foreach my $tryserver (keys(%servers)) {
                   2120: 	    unless (&reply('domroleput:'.$dom.':'.
                   2121: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2122: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2123: 	    }
1.662     raeburn  2124:         }
                   2125:     }
1.186     www      2126:     $dumpcount++;
1.157     www      2127: }
                   2128: 
                   2129: sub courselog {
                   2130:     my $what=shift;
1.158     www      2131:     $what=time.':'.$what;
1.620     albertel 2132:     unless ($env{'request.course.id'}) { return ''; }
                   2133:     $coursedombuf{$env{'request.course.id'}}=
                   2134:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2135:     $coursenumbuf{$env{'request.course.id'}}=
                   2136:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2137:     $coursehombuf{$env{'request.course.id'}}=
                   2138:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2139:     $coursedescrbuf{$env{'request.course.id'}}=
                   2140:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2141:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2142:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2143:     $courseownerbuf{$env{'request.course.id'}}=
                   2144:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2145:     $coursetypebuf{$env{'request.course.id'}}=
                   2146:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2147:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2148: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2149:     } else {
1.620     albertel 2150: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2151:     }
1.620     albertel 2152:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2153: 	&flushcourselogs();
                   2154:     }
1.158     www      2155: }
                   2156: 
                   2157: sub courseacclog {
                   2158:     my $fnsymb=shift;
1.620     albertel 2159:     unless ($env{'request.course.id'}) { return ''; }
                   2160:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2161:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2162:         $what.=':POST';
1.583     matthew  2163:         # FIXME: Probably ought to escape things....
1.800     albertel 2164: 	foreach my $key (keys(%env)) {
                   2165:             if ($key=~/^form\.(.*)/) {
                   2166: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2167:             }
1.191     harris41 2168:         }
1.583     matthew  2169:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2170:         # FIXME: We should not be depending on a form parameter that someone
                   2171:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2172:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2173:             $what.= ':POST';
                   2174:             # FIXME: Probably ought to escape things....
                   2175:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2176:                                  'crsdiscuss') {
1.620     albertel 2177:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2178:             }
                   2179:         }
1.158     www      2180:     }
                   2181:     &courselog($what);
1.149     www      2182: }
                   2183: 
1.185     www      2184: sub countacc {
                   2185:     my $url=&declutter(shift);
1.458     matthew  2186:     return if (! defined($url) || $url eq '');
1.620     albertel 2187:     unless ($env{'request.course.id'}) { return ''; }
                   2188:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2189:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2190:     $accesshash{$key}++;
1.185     www      2191: }
1.349     www      2192: 
1.361     www      2193: sub linklog {
                   2194:     my ($from,$to)=@_;
                   2195:     $from=&declutter($from);
                   2196:     $to=&declutter($to);
                   2197:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2198:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2199: }
                   2200:   
1.349     www      2201: sub userrolelog {
                   2202:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2203:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2204:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2205:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2206:         ($trole=~/^ta/)) {
1.350     www      2207:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2208:        $userrolehash
                   2209:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2210:                     =$tend.':'.$tstart;
1.662     raeburn  2211:     }
1.898     albertel 2212:     if (($env{'request.role'} =~ /dc\./) &&
                   2213: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2214: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2215: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2216:        $userrolehash
                   2217:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2218:                     =$tend.':'.$tstart;
                   2219:     }
1.662     raeburn  2220:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2221:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2222:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2223:         ($trole=~/^sc/)) {
                   2224:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2225:        $domainrolehash
                   2226:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2227:                     = $tend.':'.$tstart;
                   2228:     }
1.351     www      2229: }
                   2230: 
                   2231: sub get_course_adv_roles {
                   2232:     my $cid=shift;
1.620     albertel 2233:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2234:     my %coursehash=&coursedescription($cid);
1.470     www      2235:     my %nothide=();
1.800     albertel 2236:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2237: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2238:     }
1.351     www      2239:     my %returnhash=();
                   2240:     my %dumphash=
                   2241:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2242:     my $now=time;
1.800     albertel 2243:     foreach my $entry (keys %dumphash) {
                   2244: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2245:         if (($tstart) && ($tstart<0)) { next; }
                   2246:         if (($tend) && ($tend<$now)) { next; }
                   2247:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2248:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2249: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2250: 	if ((&privileged($username,$domain)) && 
                   2251: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2252: 	if ($role eq 'cr') { next; }
1.351     www      2253:         my $key=&plaintext($role);
                   2254:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2255:         if ($returnhash{$key}) {
                   2256: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2257:         } else {
                   2258:             $returnhash{$key}=$username.':'.$domain;
                   2259:         }
1.400     www      2260:      }
                   2261:     return %returnhash;
                   2262: }
                   2263: 
                   2264: sub get_my_roles {
1.858     raeburn  2265:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2266:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2267:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2268:     my %dumphash;
                   2269:     if ($context eq 'userroles') { 
                   2270:         %dumphash = &dump('roles',$udom,$uname);
                   2271:     } else {
                   2272:         %dumphash=
1.400     www      2273:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2274:     }
1.400     www      2275:     my %returnhash=();
                   2276:     my $now=time;
1.800     albertel 2277:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2278:         my ($role,$tend,$tstart);
                   2279:         if ($context eq 'userroles') {
                   2280: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2281:         } else {
                   2282:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2283:         }
1.400     www      2284:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2285:         my $status = 'active';
                   2286:         if (($tend) && ($tend<$now)) {
                   2287:             $status = 'previous';
                   2288:         } 
                   2289:         if (($tstart) && ($now<$tstart)) {
                   2290:             $status = 'future';
                   2291:         }
                   2292:         if (ref($types) eq 'ARRAY') {
                   2293:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2294:                 next;
                   2295:             } 
                   2296:         } else {
                   2297:             if ($status ne 'active') {
                   2298:                 next;
                   2299:             }
                   2300:         }
1.867     raeburn  2301:         my ($rolecode,$username,$domain,$section,$area);
                   2302:         if ($context eq 'userroles') {
                   2303:             ($area,$rolecode) = split(/_/,$entry);
                   2304:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2305:         } else {
                   2306:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2307:         }
1.832     raeburn  2308:         if (ref($roledoms) eq 'ARRAY') {
                   2309:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2310:                 next;
                   2311:             }
                   2312:         }
                   2313:         if (ref($roles) eq 'ARRAY') {
                   2314:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2315:                 next;
                   2316:             }
1.867     raeburn  2317:         }
1.400     www      2318: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2319:     }
1.373     www      2320:     return %returnhash;
1.399     www      2321: }
                   2322: 
                   2323: # ----------------------------------------------------- Frontpage Announcements
                   2324: #
                   2325: #
                   2326: 
                   2327: sub postannounce {
                   2328:     my ($server,$text)=@_;
1.844     albertel 2329:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2330:     unless ($text=~/\w/) { $text=''; }
                   2331:     return &reply('setannounce:'.&escape($text),$server);
                   2332: }
                   2333: 
                   2334: sub getannounce {
1.448     albertel 2335: 
                   2336:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2337: 	my $announcement='';
1.800     albertel 2338: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2339: 	close($fh);
1.399     www      2340: 	if ($announcement=~/\w/) { 
                   2341: 	    return 
                   2342:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2343:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2344: 	} else {
                   2345: 	    return '';
                   2346: 	}
                   2347:     } else {
                   2348: 	return '';
                   2349:     }
1.351     www      2350: }
1.353     www      2351: 
                   2352: # ---------------------------------------------------------- Course ID routines
                   2353: # Deal with domain's nohist_courseid.db files
                   2354: #
                   2355: 
                   2356: sub courseidput {
                   2357:     my ($domain,$what,$coursehome)=@_;
                   2358:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2359: }
                   2360: 
                   2361: sub courseiddump {
1.791     raeburn  2362:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2363:     my %returnhash=();
1.355     www      2364:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2365:     my %libserv = &all_library();
                   2366:     foreach my $tryserver (keys(%libserv)) {
                   2367:         if ( (  $hostidflag == 1 
                   2368: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2369: 	     || (!defined($hostidflag)) ) {
                   2370: 
                   2371: 	    if ($domfilter eq ''
                   2372: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2373: 	        foreach my $line (
1.844     albertel 2374:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2375: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2376:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2377:                                $tryserver))) {
1.800     albertel 2378: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2379:                     if (($key) && ($value)) {
1.516     raeburn  2380: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2381:                     }
1.353     www      2382:                 }
                   2383:             }
                   2384:         }
                   2385:     }
                   2386:     return %returnhash;
                   2387: }
                   2388: 
1.658     raeburn  2389: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2390: 
                   2391: sub dcmailput {
1.685     raeburn  2392:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2393:     my $status = &Apache::lonnet::critical(
1.740     www      2394:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2395:        &escape($message),$server);
1.662     raeburn  2396:     return $status;
                   2397: }
                   2398: 
1.658     raeburn  2399: sub dcmaildump {
                   2400:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2401:     my %returnhash=();
1.846     albertel 2402: 
                   2403:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2404:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2405:                                                          &escape($enddate).':';
                   2406: 	my @esc_senders=map { &escape($_)} @$senders;
                   2407: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2408: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2409:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2410:             if (($key) && ($value)) {
                   2411:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2412:             }
                   2413:         }
                   2414:     }
                   2415:     return %returnhash;
                   2416: }
1.662     raeburn  2417: # ---------------------------------------------------------- Domain roles
                   2418: 
                   2419: sub get_domain_roles {
                   2420:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2421:     if (undef($startdate) || $startdate eq '') {
                   2422:         $startdate = '.';
                   2423:     }
                   2424:     if (undef($enddate) || $enddate eq '') {
                   2425:         $enddate = '.';
                   2426:     }
                   2427:     my $rolelist = join(':',@{$roles});
                   2428:     my %personnel = ();
1.841     albertel 2429: 
                   2430:     my %servers = &get_servers($dom,'library');
                   2431:     foreach my $tryserver (keys(%servers)) {
                   2432: 	%{$personnel{$tryserver}}=();
                   2433: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2434: 					    &escape($startdate).':'.
                   2435: 					    &escape($enddate).':'.
                   2436: 					    &escape($rolelist), $tryserver))) {
                   2437: 	    my ($key,$value) = split(/\=/,$line,2);
                   2438: 	    if (($key) && ($value)) {
                   2439: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2440: 	    }
                   2441: 	}
1.662     raeburn  2442:     }
                   2443:     return %personnel;
                   2444: }
1.658     raeburn  2445: 
1.149     www      2446: # ----------------------------------------------------------- Check out an item
                   2447: 
1.504     albertel 2448: sub get_first_access {
                   2449:     my ($type,$argsymb)=@_;
1.790     albertel 2450:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2451:     if ($argsymb) { $symb=$argsymb; }
                   2452:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2453:     if ($type eq 'map') {
                   2454: 	$res=&symbread($map);
                   2455:     } else {
                   2456: 	$res=$symb;
                   2457:     }
                   2458:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2459:     return $times{"$courseid\0$res"};
1.504     albertel 2460: }
                   2461: 
                   2462: sub set_first_access {
                   2463:     my ($type)=@_;
1.790     albertel 2464:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2465:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2466:     if ($type eq 'map') {
                   2467: 	$res=&symbread($map);
                   2468:     } else {
                   2469: 	$res=$symb;
                   2470:     }
                   2471:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2472:     if (!$firstaccess) {
1.588     albertel 2473: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2474:     }
                   2475:     return 'already_set';
1.504     albertel 2476: }
                   2477: 
1.149     www      2478: sub checkout {
                   2479:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2480:     my $now=time;
                   2481:     my $lonhost=$perlvar{'lonHostID'};
                   2482:     my $infostr=&escape(
1.234     www      2483:                  'CHECKOUTTOKEN&'.
1.149     www      2484:                  $tuname.'&'.
                   2485:                  $tudom.'&'.
                   2486:                  $tcrsid.'&'.
                   2487:                  $symb.'&'.
                   2488: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2489:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2490:     if ($token=~/^error\:/) { 
1.672     albertel 2491:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2492:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2493:                  "</font>");
                   2494:         return ''; 
                   2495:     }
                   2496: 
1.149     www      2497:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2498:     $token=~tr/a-z/A-Z/;
                   2499: 
1.153     www      2500:     my %infohash=('resource.0.outtoken' => $token,
                   2501:                   'resource.0.checkouttime' => $now,
                   2502:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2503: 
                   2504:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2505:        return '';
1.151     www      2506:     } else {
1.672     albertel 2507:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2508:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2509:                  "</font>");
1.149     www      2510:     }    
                   2511: 
                   2512:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2513:                          &escape('Checkout '.$infostr.' - '.
                   2514:                                                  $token)) ne 'ok') {
                   2515: 	return '';
1.151     www      2516:     } else {
1.672     albertel 2517:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2518:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2519:                  "</font>");
1.149     www      2520:     }
1.151     www      2521:     return $token;
1.149     www      2522: }
                   2523: 
                   2524: # ------------------------------------------------------------ Check in an item
                   2525: 
                   2526: sub checkin {
                   2527:     my $token=shift;
1.150     www      2528:     my $now=time;
                   2529:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2530:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2531:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2532:     $dtoken=~s/\W/\_/g;
1.234     www      2533:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2534:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2535: 
1.154     www      2536:     unless (($tuname) && ($tudom)) {
                   2537:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2538:         return '';
                   2539:     }
                   2540:     
                   2541:     unless (&allowed('mgr',$tcrsid)) {
                   2542:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2543:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2544:         return '';
                   2545:     }
                   2546: 
1.153     www      2547:     my %infohash=('resource.0.intoken' => $token,
                   2548:                   'resource.0.checkintime' => $now,
                   2549:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2550: 
                   2551:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2552:        return '';
                   2553:     }    
                   2554: 
                   2555:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2556:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2557: 	return '';
                   2558:     }
                   2559: 
                   2560:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2561: }
                   2562: 
                   2563: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2564: 
                   2565: sub expirespread {
                   2566:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2567:     my $cid=$env{'request.course.id'}; 
1.110     www      2568:     if ($cid) {
                   2569:        my $now=time;
                   2570:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2571:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2572:                             $env{'course.'.$cid.'.num'}.
1.110     www      2573: 	        	    ':nohist_expirationdates:'.
                   2574:                             &escape($key).'='.$now,
1.620     albertel 2575:                             $env{'course.'.$cid.'.home'})
1.110     www      2576:     }
                   2577:     return 'ok';
1.14      www      2578: }
                   2579: 
1.109     www      2580: # ----------------------------------------------------- Devalidate Spreadsheets
                   2581: 
                   2582: sub devalidate {
1.325     www      2583:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2584:     my $cid=$env{'request.course.id'}; 
1.109     www      2585:     if ($cid) {
1.391     matthew  2586:         # delete the stored spreadsheets for
                   2587:         # - the student level sheet of this user in course's homespace
                   2588:         # - the assessment level sheet for this resource 
                   2589:         #   for this user in user's homespace
1.553     albertel 2590: 	# - current conditional state info
1.325     www      2591: 	my $key=$uname.':'.$udom.':';
1.109     www      2592:         my $status=
1.299     matthew  2593: 	    &del('nohist_calculatedsheets',
1.391     matthew  2594: 		 [$key.'studentcalc:'],
1.620     albertel 2595: 		 $env{'course.'.$cid.'.domain'},
                   2596: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2597: 		.' '.
                   2598: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2599: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2600:         unless ($status eq 'ok ok') {
                   2601:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2602:                     $uname.' at '.$udom.' for '.
1.109     www      2603: 		    $symb.': '.$status);
1.133     albertel 2604:         }
1.553     albertel 2605: 	&delenv('user.state.'.$cid);
1.109     www      2606:     }
                   2607: }
                   2608: 
1.265     albertel 2609: sub get_scalar {
                   2610:     my ($string,$end) = @_;
                   2611:     my $value;
                   2612:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2613: 	$value = $1;
                   2614:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2615: 	$value = $1;
                   2616:     }
                   2617:     return &unescape($value);
                   2618: }
                   2619: 
                   2620: sub array2str {
                   2621:   my (@array) = @_;
                   2622:   my $result=&arrayref2str(\@array);
                   2623:   $result=~s/^__ARRAY_REF__//;
                   2624:   $result=~s/__END_ARRAY_REF__$//;
                   2625:   return $result;
                   2626: }
                   2627: 
1.204     albertel 2628: sub arrayref2str {
                   2629:   my ($arrayref) = @_;
1.265     albertel 2630:   my $result='__ARRAY_REF__';
1.204     albertel 2631:   foreach my $elem (@$arrayref) {
1.265     albertel 2632:     if(ref($elem) eq 'ARRAY') {
                   2633:       $result.=&arrayref2str($elem).'&';
                   2634:     } elsif(ref($elem) eq 'HASH') {
                   2635:       $result.=&hashref2str($elem).'&';
                   2636:     } elsif(ref($elem)) {
                   2637:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2638:     } else {
                   2639:       $result.=&escape($elem).'&';
                   2640:     }
                   2641:   }
                   2642:   $result=~s/\&$//;
1.265     albertel 2643:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2644:   return $result;
                   2645: }
                   2646: 
1.168     albertel 2647: sub hash2str {
1.204     albertel 2648:   my (%hash) = @_;
                   2649:   my $result=&hashref2str(\%hash);
1.265     albertel 2650:   $result=~s/^__HASH_REF__//;
                   2651:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2652:   return $result;
                   2653: }
                   2654: 
                   2655: sub hashref2str {
                   2656:   my ($hashref)=@_;
1.265     albertel 2657:   my $result='__HASH_REF__';
1.800     albertel 2658:   foreach my $key (sort(keys(%$hashref))) {
                   2659:     if (ref($key) eq 'ARRAY') {
                   2660:       $result.=&arrayref2str($key).'=';
                   2661:     } elsif (ref($key) eq 'HASH') {
                   2662:       $result.=&hashref2str($key).'=';
                   2663:     } elsif (ref($key)) {
1.265     albertel 2664:       $result.='=';
1.800     albertel 2665:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2666:     } else {
1.800     albertel 2667: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2668:     }
                   2669: 
1.800     albertel 2670:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2671:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2672:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2673:       $result.=&hashref2str($hashref->{$key}).'&';
                   2674:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2675:        $result.='&';
1.800     albertel 2676:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2677:     } else {
1.800     albertel 2678:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2679:     }
                   2680:   }
1.168     albertel 2681:   $result=~s/\&$//;
1.265     albertel 2682:   $result .= '__END_HASH_REF__';
1.168     albertel 2683:   return $result;
                   2684: }
                   2685: 
                   2686: sub str2hash {
1.265     albertel 2687:     my ($string)=@_;
                   2688:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2689:     return %$hash;
                   2690: }
                   2691: 
                   2692: sub str2hashref {
1.168     albertel 2693:   my ($string) = @_;
1.265     albertel 2694: 
                   2695:   my %hash;
                   2696: 
                   2697:   if($string !~ /^__HASH_REF__/) {
                   2698:       if (! ($string eq '' || !defined($string))) {
                   2699: 	  $hash{'error'}='Not hash reference';
                   2700:       }
                   2701:       return (\%hash, $string);
                   2702:   }
                   2703: 
                   2704:   $string =~ s/^__HASH_REF__//;
                   2705: 
                   2706:   while($string !~ /^__END_HASH_REF__/) {
                   2707:       #key
                   2708:       my $key='';
                   2709:       if($string =~ /^__HASH_REF__/) {
                   2710:           ($key, $string)=&str2hashref($string);
                   2711:           if(defined($key->{'error'})) {
                   2712:               $hash{'error'}='Bad data';
                   2713:               return (\%hash, $string);
                   2714:           }
                   2715:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2716:           ($key, $string)=&str2arrayref($string);
                   2717:           if($key->[0] eq 'Array reference error') {
                   2718:               $hash{'error'}='Bad data';
                   2719:               return (\%hash, $string);
                   2720:           }
                   2721:       } else {
                   2722:           $string =~ s/^(.*?)=//;
1.267     albertel 2723: 	  $key=&unescape($1);
1.265     albertel 2724:       }
                   2725:       $string =~ s/^=//;
                   2726: 
                   2727:       #value
                   2728:       my $value='';
                   2729:       if($string =~ /^__HASH_REF__/) {
                   2730:           ($value, $string)=&str2hashref($string);
                   2731:           if(defined($value->{'error'})) {
                   2732:               $hash{'error'}='Bad data';
                   2733:               return (\%hash, $string);
                   2734:           }
                   2735:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2736:           ($value, $string)=&str2arrayref($string);
                   2737:           if($value->[0] eq 'Array reference error') {
                   2738:               $hash{'error'}='Bad data';
                   2739:               return (\%hash, $string);
                   2740:           }
                   2741:       } else {
                   2742: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2743:       }
                   2744:       $string =~ s/^&//;
                   2745: 
                   2746:       $hash{$key}=$value;
1.204     albertel 2747:   }
1.265     albertel 2748: 
                   2749:   $string =~ s/^__END_HASH_REF__//;
                   2750: 
                   2751:   return (\%hash, $string);
1.204     albertel 2752: }
                   2753: 
                   2754: sub str2array {
1.265     albertel 2755:     my ($string)=@_;
                   2756:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2757:     return @$array;
                   2758: }
                   2759: 
                   2760: sub str2arrayref {
1.204     albertel 2761:   my ($string) = @_;
1.265     albertel 2762:   my @array;
                   2763: 
                   2764:   if($string !~ /^__ARRAY_REF__/) {
                   2765:       if (! ($string eq '' || !defined($string))) {
                   2766: 	  $array[0]='Array reference error';
                   2767:       }
                   2768:       return (\@array, $string);
                   2769:   }
                   2770: 
                   2771:   $string =~ s/^__ARRAY_REF__//;
                   2772: 
                   2773:   while($string !~ /^__END_ARRAY_REF__/) {
                   2774:       my $value='';
                   2775:       if($string =~ /^__HASH_REF__/) {
                   2776:           ($value, $string)=&str2hashref($string);
                   2777:           if(defined($value->{'error'})) {
                   2778:               $array[0] ='Array reference error';
                   2779:               return (\@array, $string);
                   2780:           }
                   2781:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2782:           ($value, $string)=&str2arrayref($string);
                   2783:           if($value->[0] eq 'Array reference error') {
                   2784:               $array[0] ='Array reference error';
                   2785:               return (\@array, $string);
                   2786:           }
                   2787:       } else {
                   2788: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2789:       }
                   2790:       $string =~ s/^&//;
                   2791: 
                   2792:       push(@array, $value);
1.191     harris41 2793:   }
1.265     albertel 2794: 
                   2795:   $string =~ s/^__END_ARRAY_REF__//;
                   2796: 
                   2797:   return (\@array, $string);
1.168     albertel 2798: }
                   2799: 
1.167     albertel 2800: # -------------------------------------------------------------------Temp Store
                   2801: 
1.168     albertel 2802: sub tmpreset {
                   2803:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2804:   if (!$symb) {
                   2805:     $symb=&symbread();
1.620     albertel 2806:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2807:   }
                   2808:   $symb=escape($symb);
                   2809: 
1.620     albertel 2810:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2811:   $namespace=~s/\//\_/g;
                   2812:   $namespace=~s/\W//g;
                   2813: 
1.620     albertel 2814:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2815:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2816:   if ($domain eq 'public' && $stuname eq 'public') {
                   2817:       $stuname=$ENV{'REMOTE_ADDR'};
                   2818:   }
1.168     albertel 2819:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2820:   my %hash;
                   2821:   if (tie(%hash,'GDBM_File',
                   2822: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2823: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2824:     foreach my $key (keys %hash) {
1.180     albertel 2825:       if ($key=~ /:$symb/) {
1.168     albertel 2826: 	delete($hash{$key});
                   2827:       }
                   2828:     }
                   2829:   }
                   2830: }
                   2831: 
1.167     albertel 2832: sub tmpstore {
1.168     albertel 2833:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2834: 
                   2835:   if (!$symb) {
                   2836:     $symb=&symbread();
1.620     albertel 2837:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2838:   }
                   2839:   $symb=escape($symb);
                   2840: 
                   2841:   if (!$namespace) {
                   2842:     # I don't think we would ever want to store this for a course.
                   2843:     # it seems this will only be used if we don't have a course.
1.620     albertel 2844:     #$namespace=$env{'request.course.id'};
1.168     albertel 2845:     #if (!$namespace) {
1.620     albertel 2846:       $namespace=$env{'request.state'};
1.168     albertel 2847:     #}
                   2848:   }
                   2849:   $namespace=~s/\//\_/g;
                   2850:   $namespace=~s/\W//g;
1.620     albertel 2851:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2852:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2853:   if ($domain eq 'public' && $stuname eq 'public') {
                   2854:       $stuname=$ENV{'REMOTE_ADDR'};
                   2855:   }
1.168     albertel 2856:   my $now=time;
                   2857:   my %hash;
                   2858:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2859:   if (tie(%hash,'GDBM_File',
                   2860: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2861: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2862:     $hash{"version:$symb"}++;
                   2863:     my $version=$hash{"version:$symb"};
                   2864:     my $allkeys=''; 
                   2865:     foreach my $key (keys(%$storehash)) {
                   2866:       $allkeys.=$key.':';
1.591     albertel 2867:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2868:     }
                   2869:     $hash{"$version:$symb:timestamp"}=$now;
                   2870:     $allkeys.='timestamp';
                   2871:     $hash{"$version:keys:$symb"}=$allkeys;
                   2872:     if (untie(%hash)) {
                   2873:       return 'ok';
                   2874:     } else {
                   2875:       return "error:$!";
                   2876:     }
                   2877:   } else {
                   2878:     return "error:$!";
                   2879:   }
                   2880: }
1.167     albertel 2881: 
1.168     albertel 2882: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2883: 
1.168     albertel 2884: sub tmprestore {
                   2885:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2886: 
1.168     albertel 2887:   if (!$symb) {
                   2888:     $symb=&symbread();
1.620     albertel 2889:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2890:   }
                   2891:   $symb=escape($symb);
                   2892: 
1.620     albertel 2893:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2894: 
1.620     albertel 2895:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2896:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2897:   if ($domain eq 'public' && $stuname eq 'public') {
                   2898:       $stuname=$ENV{'REMOTE_ADDR'};
                   2899:   }
1.168     albertel 2900:   my %returnhash;
                   2901:   $namespace=~s/\//\_/g;
                   2902:   $namespace=~s/\W//g;
                   2903:   my %hash;
                   2904:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2905:   if (tie(%hash,'GDBM_File',
                   2906: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2907: 	  &GDBM_READER(),0640)) {
1.168     albertel 2908:     my $version=$hash{"version:$symb"};
                   2909:     $returnhash{'version'}=$version;
                   2910:     my $scope;
                   2911:     for ($scope=1;$scope<=$version;$scope++) {
                   2912:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2913:       my @keys=split(/:/,$vkeys);
                   2914:       my $key;
                   2915:       $returnhash{"$scope:keys"}=$vkeys;
                   2916:       foreach $key (@keys) {
1.591     albertel 2917: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2918: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2919:       }
                   2920:     }
1.168     albertel 2921:     if (!(untie(%hash))) {
                   2922:       return "error:$!";
                   2923:     }
                   2924:   } else {
                   2925:     return "error:$!";
                   2926:   }
                   2927:   return %returnhash;
1.167     albertel 2928: }
                   2929: 
1.9       www      2930: # ----------------------------------------------------------------------- Store
                   2931: 
                   2932: sub store {
1.124     www      2933:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2934:     my $home='';
                   2935: 
1.168     albertel 2936:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2937: 
1.213     www      2938:     $symb=&symbclean($symb);
1.122     albertel 2939:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2940: 
1.620     albertel 2941:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2942:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2943: 
                   2944:     &devalidate($symb,$stuname,$domain);
1.109     www      2945: 
                   2946:     $symb=escape($symb);
1.187     www      2947:     if (!$namespace) { 
1.620     albertel 2948:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2949:           return ''; 
                   2950:        } 
                   2951:     }
1.620     albertel 2952:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2953: 
                   2954:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2955:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2956: 
1.12      www      2957:     my $namevalue='';
1.800     albertel 2958:     foreach my $key (keys(%$storehash)) {
                   2959:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2960:     }
1.12      www      2961:     $namevalue=~s/\&$//;
1.187     www      2962:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2963:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2964: }
                   2965: 
1.47      www      2966: # -------------------------------------------------------------- Critical Store
                   2967: 
                   2968: sub cstore {
1.124     www      2969:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2970:     my $home='';
                   2971: 
1.168     albertel 2972:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2973: 
1.213     www      2974:     $symb=&symbclean($symb);
1.122     albertel 2975:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2976: 
1.620     albertel 2977:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2978:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2979: 
                   2980:     &devalidate($symb,$stuname,$domain);
1.109     www      2981: 
                   2982:     $symb=escape($symb);
1.187     www      2983:     if (!$namespace) { 
1.620     albertel 2984:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2985:           return ''; 
                   2986:        } 
                   2987:     }
1.620     albertel 2988:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2989: 
                   2990:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2991:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2992: 
1.47      www      2993:     my $namevalue='';
1.800     albertel 2994:     foreach my $key (keys(%$storehash)) {
                   2995:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2996:     }
1.47      www      2997:     $namevalue=~s/\&$//;
1.187     www      2998:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2999:     return critical
                   3000:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3001: }
                   3002: 
1.9       www      3003: # --------------------------------------------------------------------- Restore
                   3004: 
                   3005: sub restore {
1.124     www      3006:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3007:     my $home='';
                   3008: 
1.168     albertel 3009:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3010: 
1.122     albertel 3011:     if (!$symb) {
                   3012:       unless ($symb=escape(&symbread())) { return ''; }
                   3013:     } else {
1.213     www      3014:       $symb=&escape(&symbclean($symb));
1.122     albertel 3015:     }
1.188     www      3016:     if (!$namespace) { 
1.620     albertel 3017:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3018:           return ''; 
                   3019:        } 
                   3020:     }
1.620     albertel 3021:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3022:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3023:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3024:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3025: 
1.12      www      3026:     my %returnhash=();
1.800     albertel 3027:     foreach my $line (split(/\&/,$answer)) {
                   3028: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3029:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3030:     }
1.75      www      3031:     my $version;
                   3032:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3033:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3034:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3035:        }
1.75      www      3036:     }
1.13      www      3037:     return %returnhash;
1.34      www      3038: }
                   3039: 
                   3040: # ---------------------------------------------------------- Course Description
                   3041: 
                   3042: sub coursedescription {
1.731     albertel 3043:     my ($courseid,$args)=@_;
1.34      www      3044:     $courseid=~s/^\///;
1.49      www      3045:     $courseid=~s/\_/\//g;
1.34      www      3046:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3047:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3048:     my $normalid=$cdomain.'_'.$cnum;
                   3049:     # need to always cache even if we get errors otherwise we keep 
                   3050:     # trying and trying and trying to get the course description.
                   3051:     my %envhash=();
                   3052:     my %returnhash=();
1.731     albertel 3053:     
                   3054:     my $expiretime=600;
                   3055:     if ($env{'request.course.id'} eq $normalid) {
                   3056: 	$expiretime=120;
                   3057:     }
                   3058: 
                   3059:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3060:     if (!$args->{'freshen_cache'}
                   3061: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3062: 	foreach my $key (keys(%env)) {
                   3063: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3064: 	    my ($setting) = $1;
                   3065: 	    $returnhash{$setting} = $env{$key};
                   3066: 	}
                   3067: 	return %returnhash;
                   3068:     }
                   3069: 
                   3070:     # get the data agin
                   3071:     if (!$args->{'one_time'}) {
                   3072: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3073:     }
1.811     albertel 3074: 
1.34      www      3075:     if ($chome ne 'no_host') {
1.302     albertel 3076:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3077:        if (!exists($returnhash{'con_lost'})) {
                   3078:            $returnhash{'home'}= $chome;
                   3079: 	   $returnhash{'domain'} = $cdomain;
                   3080: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3081:            if (!defined($returnhash{'type'})) {
                   3082:                $returnhash{'type'} = 'Course';
                   3083:            }
1.130     albertel 3084:            while (my ($name,$value) = each %returnhash) {
1.53      www      3085:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3086:            }
1.270     www      3087:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3088:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3089: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3090:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3091:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3092:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3093:        }
                   3094:     }
1.731     albertel 3095:     if (!$args->{'one_time'}) {
                   3096: 	&appenv(%envhash);
                   3097:     }
1.302     albertel 3098:     return %returnhash;
1.461     www      3099: }
                   3100: 
                   3101: # -------------------------------------------------See if a user is privileged
                   3102: 
                   3103: sub privileged {
                   3104:     my ($username,$domain)=@_;
                   3105:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3106: 			&homeserver($username,$domain));
                   3107:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3108:     my $now=time;
                   3109:     if ($rolesdump ne '') {
1.800     albertel 3110:         foreach my $entry (split(/&/,$rolesdump)) {
                   3111: 	    if ($entry!~/^rolesdef_/) {
                   3112: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3113: 		$area=~s/\_\w\w$//;
                   3114: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3115: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3116: 		    my $active=1;
                   3117: 		    if ($tend) {
                   3118: 			if ($tend<$now) { $active=0; }
                   3119: 		    }
                   3120: 		    if ($tstart) {
                   3121: 			if ($tstart>$now) { $active=0; }
                   3122: 		    }
                   3123: 		    if ($active) { return 1; }
                   3124: 		}
                   3125: 	    }
                   3126: 	}
                   3127:     }
                   3128:     return 0;
1.9       www      3129: }
1.1       albertel 3130: 
1.103     harris41 3131: # -------------------------------------------------------- Get user privileges
1.11      www      3132: 
                   3133: sub rolesinit {
                   3134:     my ($domain,$username,$authhost)=@_;
                   3135:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3136:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3137:     my %allroles=();
1.678     raeburn  3138:     my %allgroups=();   
1.11      www      3139:     my $now=time;
1.743     albertel 3140:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3141:     my $group_privs;
1.11      www      3142: 
                   3143:     if ($rolesdump ne '') {
1.800     albertel 3144:         foreach my $entry (split(/&/,$rolesdump)) {
                   3145: 	  if ($entry!~/^rolesdef_/) {
                   3146:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3147: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3148:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3149: 	    if ($role=~/^cr/) { 
1.807     albertel 3150: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3151: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3152: 		    ($tend,$tstart)=split('_',$trest);
                   3153: 		} else {
                   3154: 		    $trole=$role;
                   3155: 		}
1.678     raeburn  3156:             } elsif ($role =~ m|^gr/|) {
                   3157:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3158:                 ($trole,$group_privs) = split(/\//,$trole);
                   3159:                 $group_privs = &unescape($group_privs);
1.587     albertel 3160: 	    } else {
                   3161: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3162: 	    }
1.743     albertel 3163: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3164: 					 $username);
                   3165: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3166:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3167:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3168:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3169: 		my $spec=$trole.'.'.$area;
                   3170: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3171: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3172:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3173:                 } elsif ($trole eq 'gr') {
                   3174:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3175: 		} else {
1.567     raeburn  3176:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3177: 		}
1.12      www      3178:             }
1.662     raeburn  3179:           }
1.191     harris41 3180:         }
1.743     albertel 3181:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3182:         $userroles{'user.adv'}    = $adv;
                   3183: 	$userroles{'user.author'} = $author;
1.620     albertel 3184:         $env{'user.adv'}=$adv;
1.11      www      3185:     }
1.743     albertel 3186:     return \%userroles;  
1.11      www      3187: }
                   3188: 
1.567     raeburn  3189: sub set_arearole {
                   3190:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3191: # log the associated role with the area
                   3192:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3193:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3194: }
                   3195: 
                   3196: sub custom_roleprivs {
                   3197:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3198:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3199:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3200:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3201:         my ($rdummy,$roledef)=
                   3202:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3203:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3204:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3205:             if (defined($syspriv)) {
                   3206:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3207:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3208:             }
                   3209:             if ($tdomain ne '') {
                   3210:                 if (defined($dompriv)) {
                   3211:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3212:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3213:                 }
                   3214:                 if (($trest ne '') && (defined($coursepriv))) {
                   3215:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3216:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3217:                 }
                   3218:             }
                   3219:         }
                   3220:     }
                   3221: }
                   3222: 
1.678     raeburn  3223: sub group_roleprivs {
                   3224:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3225:     my $access = 1;
                   3226:     my $now = time;
                   3227:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3228:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3229:     if ($access) {
1.811     albertel 3230:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3231:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3232:     }
                   3233: }
1.567     raeburn  3234: 
                   3235: sub standard_roleprivs {
                   3236:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3237:     if (defined($pr{$trole.':s'})) {
                   3238:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3239:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3240:     }
                   3241:     if ($tdomain ne '') {
                   3242:         if (defined($pr{$trole.':d'})) {
                   3243:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3244:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3245:         }
                   3246:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3247:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3248:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3249:         }
                   3250:     }
                   3251: }
                   3252: 
                   3253: sub set_userprivs {
1.678     raeburn  3254:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3255:     my $author=0;
                   3256:     my $adv=0;
1.678     raeburn  3257:     my %grouproles = ();
                   3258:     if (keys(%{$allgroups}) > 0) {
                   3259:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3260:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3261:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3262:                 $trole = $1;
                   3263:                 $area = $2;
1.681     raeburn  3264:                 $sec = $3;
                   3265:                 $extendedarea = $area.$sec;
                   3266:                 if (exists($$allgroups{$area})) {
                   3267:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3268:                         my $spec = $trole.'.'.$extendedarea;
                   3269:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3270:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3271:                     }
                   3272:                 }
                   3273:             }
                   3274:         }
                   3275:     }
1.800     albertel 3276:     foreach my $group (keys(%grouproles)) {
                   3277:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3278:     }
1.800     albertel 3279:     foreach my $role (keys(%{$allroles})) {
                   3280:         my %thesepriv;
                   3281:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3282:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3283:             if ($item ne '') {
                   3284:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3285:                 if ($restrictions eq '') {
                   3286:                     $thesepriv{$privilege}='F';
                   3287:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3288:                     $thesepriv{$privilege}.=$restrictions;
                   3289:                 }
                   3290:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3291:             }
                   3292:         }
                   3293:         my $thesestr='';
1.800     albertel 3294:         foreach my $priv (keys(%thesepriv)) {
                   3295: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3296: 	}
                   3297:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3298:     }
                   3299:     return ($author,$adv);
                   3300: }
                   3301: 
1.12      www      3302: # --------------------------------------------------------------- get interface
                   3303: 
                   3304: sub get {
1.131     albertel 3305:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3306:    my $items='';
1.800     albertel 3307:    foreach my $item (@$storearr) {
                   3308:        $items.=&escape($item).'&';
1.191     harris41 3309:    }
1.12      www      3310:    $items=~s/\&$//;
1.620     albertel 3311:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3312:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3313:    my $uhome=&homeserver($uname,$udomain);
                   3314: 
1.133     albertel 3315:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3316:    my @pairs=split(/\&/,$rep);
1.273     albertel 3317:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3318:      return @pairs;
                   3319:    }
1.15      www      3320:    my %returnhash=();
1.42      www      3321:    my $i=0;
1.800     albertel 3322:    foreach my $item (@$storearr) {
                   3323:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3324:       $i++;
1.191     harris41 3325:    }
1.15      www      3326:    return %returnhash;
1.27      www      3327: }
                   3328: 
                   3329: # --------------------------------------------------------------- del interface
                   3330: 
                   3331: sub del {
1.133     albertel 3332:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3333:    my $items='';
1.800     albertel 3334:    foreach my $item (@$storearr) {
                   3335:        $items.=&escape($item).'&';
1.191     harris41 3336:    }
1.27      www      3337:    $items=~s/\&$//;
1.620     albertel 3338:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3339:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3340:    my $uhome=&homeserver($uname,$udomain);
                   3341: 
                   3342:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3343: }
                   3344: 
                   3345: # -------------------------------------------------------------- dump interface
                   3346: 
                   3347: sub dump {
1.755     albertel 3348:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3349:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3350:     if (!$uname) { $uname=$env{'user.name'}; }
                   3351:     my $uhome=&homeserver($uname,$udomain);
                   3352:     if ($regexp) {
                   3353: 	$regexp=&escape($regexp);
                   3354:     } else {
                   3355: 	$regexp='.';
                   3356:     }
                   3357:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3358:     my @pairs=split(/\&/,$rep);
                   3359:     my %returnhash=();
                   3360:     foreach my $item (@pairs) {
                   3361: 	my ($key,$value)=split(/=/,$item,2);
                   3362: 	$key = &unescape($key);
                   3363: 	next if ($key =~ /^error: 2 /);
                   3364: 	$returnhash{$key}=&thaw_unescape($value);
                   3365:     }
                   3366:     return %returnhash;
1.407     www      3367: }
                   3368: 
1.717     albertel 3369: # --------------------------------------------------------- dumpstore interface
                   3370: 
                   3371: sub dumpstore {
                   3372:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3373:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3374:    if (!$uname) { $uname=$env{'user.name'}; }
                   3375:    my $uhome=&homeserver($uname,$udomain);
                   3376:    if ($regexp) {
                   3377:        $regexp=&escape($regexp);
                   3378:    } else {
                   3379:        $regexp='.';
                   3380:    }
                   3381:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3382:    my @pairs=split(/\&/,$rep);
                   3383:    my %returnhash=();
                   3384:    foreach my $item (@pairs) {
                   3385:        my ($key,$value)=split(/=/,$item,2);
                   3386:        next if ($key =~ /^error: 2 /);
                   3387:        $returnhash{$key}=&thaw_unescape($value);
                   3388:    }
                   3389:    return %returnhash;
1.717     albertel 3390: }
                   3391: 
1.407     www      3392: # -------------------------------------------------------------- keys interface
                   3393: 
                   3394: sub getkeys {
                   3395:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3396:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3397:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3398:    my $uhome=&homeserver($uname,$udomain);
                   3399:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3400:    my @keyarray=();
1.800     albertel 3401:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3402:       next if ($key =~ /^error: 2 /);
1.800     albertel 3403:       push(@keyarray,&unescape($key));
1.407     www      3404:    }
                   3405:    return @keyarray;
1.318     matthew  3406: }
                   3407: 
1.319     matthew  3408: # --------------------------------------------------------------- currentdump
                   3409: sub currentdump {
1.328     matthew  3410:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3411:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3412:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3413:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3414:    my $uhome = &homeserver($sname,$sdom);
                   3415:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3416:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3417:    #
1.318     matthew  3418:    my %returnhash=();
1.319     matthew  3419:    #
                   3420:    if ($rep eq "unknown_cmd") { 
                   3421:        # an old lond will not know currentdump
                   3422:        # Do a dump and make it look like a currentdump
1.822     albertel 3423:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3424:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3425:        my %hash = @tmp;
                   3426:        @tmp=();
1.424     matthew  3427:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3428:    } else {
                   3429:        my @pairs=split(/\&/,$rep);
1.800     albertel 3430:        foreach my $pair (@pairs) {
                   3431:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3432:            my ($symb,$param) = split(/:/,$key);
                   3433:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3434:                                                         &thaw_unescape($value);
1.319     matthew  3435:        }
1.191     harris41 3436:    }
1.12      www      3437:    return %returnhash;
1.424     matthew  3438: }
                   3439: 
                   3440: sub convert_dump_to_currentdump{
                   3441:     my %hash = %{shift()};
                   3442:     my %returnhash;
                   3443:     # Code ripped from lond, essentially.  The only difference
                   3444:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3445:     # we might run in to problems with parameter names =~ /^v\./
                   3446:     while (my ($key,$value) = each(%hash)) {
                   3447:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3448: 	$symb  = &unescape($symb);
                   3449: 	$param = &unescape($param);
1.424     matthew  3450:         next if ($v eq 'version' || $symb eq 'keys');
                   3451:         next if (exists($returnhash{$symb}) &&
                   3452:                  exists($returnhash{$symb}->{$param}) &&
                   3453:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3454:         $returnhash{$symb}->{$param}=$value;
                   3455:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3456:     }
                   3457:     #
                   3458:     # Remove all of the keys in the hashes which keep track of
                   3459:     # the version of the parameter.
                   3460:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3461:         # use a foreach because we are going to delete from the hash.
                   3462:         foreach my $key (keys(%$param_hash)) {
                   3463:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3464:         }
                   3465:     }
                   3466:     return \%returnhash;
1.12      www      3467: }
                   3468: 
1.627     albertel 3469: # ------------------------------------------------------ critical inc interface
                   3470: 
                   3471: sub cinc {
                   3472:     return &inc(@_,'critical');
                   3473: }
                   3474: 
1.449     matthew  3475: # --------------------------------------------------------------- inc interface
                   3476: 
                   3477: sub inc {
1.627     albertel 3478:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3479:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3480:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3481:     my $uhome=&homeserver($uname,$udomain);
                   3482:     my $items='';
                   3483:     if (! ref($store)) {
                   3484:         # got a single value, so use that instead
                   3485:         $items = &escape($store).'=&';
                   3486:     } elsif (ref($store) eq 'SCALAR') {
                   3487:         $items = &escape($$store).'=&';        
                   3488:     } elsif (ref($store) eq 'ARRAY') {
                   3489:         $items = join('=&',map {&escape($_);} @{$store});
                   3490:     } elsif (ref($store) eq 'HASH') {
                   3491:         while (my($key,$value) = each(%{$store})) {
                   3492:             $items.= &escape($key).'='.&escape($value).'&';
                   3493:         }
                   3494:     }
                   3495:     $items=~s/\&$//;
1.627     albertel 3496:     if ($critical) {
                   3497: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3498:     } else {
                   3499: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3500:     }
1.449     matthew  3501: }
                   3502: 
1.12      www      3503: # --------------------------------------------------------------- put interface
                   3504: 
                   3505: sub put {
1.134     albertel 3506:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3507:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3508:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3509:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3510:    my $items='';
1.800     albertel 3511:    foreach my $item (keys(%$storehash)) {
                   3512:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3513:    }
1.12      www      3514:    $items=~s/\&$//;
1.134     albertel 3515:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3516: }
                   3517: 
1.631     albertel 3518: # ------------------------------------------------------------ newput interface
                   3519: 
                   3520: sub newput {
                   3521:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3522:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3523:    if (!$uname) { $uname=$env{'user.name'}; }
                   3524:    my $uhome=&homeserver($uname,$udomain);
                   3525:    my $items='';
                   3526:    foreach my $key (keys(%$storehash)) {
                   3527:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3528:    }
                   3529:    $items=~s/\&$//;
                   3530:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3531: }
                   3532: 
                   3533: # ---------------------------------------------------------  putstore interface
                   3534: 
1.524     raeburn  3535: sub putstore {
1.715     albertel 3536:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3537:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3538:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3539:    my $uhome=&homeserver($uname,$udomain);
                   3540:    my $items='';
1.715     albertel 3541:    foreach my $key (keys(%$storehash)) {
                   3542:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3543:    }
1.715     albertel 3544:    $items=~s/\&$//;
1.716     albertel 3545:    my $esc_symb=&escape($symb);
                   3546:    my $esc_v=&escape($version);
1.715     albertel 3547:    my $reply =
1.716     albertel 3548:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3549: 	      $uhome);
                   3550:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3551:        # gfall back to way things use to be done
1.715     albertel 3552:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3553: 			    $uname);
1.524     raeburn  3554:    }
1.715     albertel 3555:    return $reply;
                   3556: }
                   3557: 
                   3558: sub old_putstore {
1.716     albertel 3559:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3560:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3561:     if (!$uname) { $uname=$env{'user.name'}; }
                   3562:     my $uhome=&homeserver($uname,$udomain);
                   3563:     my %newstorehash;
1.800     albertel 3564:     foreach my $item (keys(%$storehash)) {
                   3565: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3566: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3567:     }
                   3568:     my $items='';
                   3569:     my %allitems = ();
1.800     albertel 3570:     foreach my $item (keys(%newstorehash)) {
                   3571: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3572: 	    my $key = $1.':keys:'.$2;
                   3573: 	    $allitems{$key} .= $3.':';
                   3574: 	}
1.800     albertel 3575: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3576:     }
1.800     albertel 3577:     foreach my $item (keys(%allitems)) {
                   3578: 	$allitems{$item} =~ s/\:$//;
                   3579: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3580:     }
                   3581:     $items=~s/\&$//;
                   3582:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3583: }
                   3584: 
1.47      www      3585: # ------------------------------------------------------ critical put interface
                   3586: 
                   3587: sub cput {
1.134     albertel 3588:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3589:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3590:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3591:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3592:    my $items='';
1.800     albertel 3593:    foreach my $item (keys(%$storehash)) {
                   3594:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3595:    }
1.47      www      3596:    $items=~s/\&$//;
1.134     albertel 3597:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3598: }
                   3599: 
                   3600: # -------------------------------------------------------------- eget interface
                   3601: 
                   3602: sub eget {
1.133     albertel 3603:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3604:    my $items='';
1.800     albertel 3605:    foreach my $item (@$storearr) {
                   3606:        $items.=&escape($item).'&';
1.191     harris41 3607:    }
1.12      www      3608:    $items=~s/\&$//;
1.620     albertel 3609:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3610:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3611:    my $uhome=&homeserver($uname,$udomain);
                   3612:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3613:    my @pairs=split(/\&/,$rep);
                   3614:    my %returnhash=();
1.42      www      3615:    my $i=0;
1.800     albertel 3616:    foreach my $item (@$storearr) {
                   3617:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3618:       $i++;
1.191     harris41 3619:    }
1.12      www      3620:    return %returnhash;
                   3621: }
                   3622: 
1.667     albertel 3623: # ------------------------------------------------------------ tmpput interface
                   3624: sub tmpput {
1.802     raeburn  3625:     my ($storehash,$server,$context)=@_;
1.667     albertel 3626:     my $items='';
1.800     albertel 3627:     foreach my $item (keys(%$storehash)) {
                   3628: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3629:     }
                   3630:     $items=~s/\&$//;
1.802     raeburn  3631:     if (defined($context)) {
                   3632:         $items .= ':'.&escape($context);
                   3633:     }
1.667     albertel 3634:     return &reply("tmpput:$items",$server);
                   3635: }
                   3636: 
                   3637: # ------------------------------------------------------------ tmpget interface
                   3638: sub tmpget {
1.688     albertel 3639:     my ($token,$server)=@_;
                   3640:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3641:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3642:     my %returnhash;
                   3643:     foreach my $item (split(/\&/,$rep)) {
                   3644: 	my ($key,$value)=split(/=/,$item);
                   3645: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3646:     }
                   3647:     return %returnhash;
                   3648: }
                   3649: 
1.688     albertel 3650: # ------------------------------------------------------------ tmpget interface
                   3651: sub tmpdel {
                   3652:     my ($token,$server)=@_;
                   3653:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3654:     return &reply("tmpdel:$token",$server);
                   3655: }
                   3656: 
1.765     albertel 3657: # -------------------------------------------------- portfolio access checking
                   3658: 
                   3659: sub portfolio_access {
1.766     albertel 3660:     my ($requrl) = @_;
1.765     albertel 3661:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3662:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3663:     if ($result) {
                   3664:         my %setters;
                   3665:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3666:             my ($startblock,$endblock) =
                   3667:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3668:             if ($startblock && $endblock) {
                   3669:                 return 'B';
                   3670:             }
                   3671:         } else {
                   3672:             my ($startblock,$endblock) =
                   3673:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3674:             if ($startblock && $endblock) {
                   3675:                 return 'B';
                   3676:             }
                   3677:         }
                   3678:     }
1.765     albertel 3679:     if ($result eq 'ok') {
1.766     albertel 3680:        return 'F';
1.765     albertel 3681:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3682:        return 'A';
1.765     albertel 3683:     }
1.766     albertel 3684:     return '';
1.765     albertel 3685: }
                   3686: 
                   3687: sub get_portfolio_access {
1.767     albertel 3688:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3689: 
                   3690:     if (!ref($access_hash)) {
                   3691: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3692: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3693: 						   $file_name);
                   3694: 	$access_hash = $access_controls{$file_name};
                   3695:     }
                   3696: 
1.765     albertel 3697:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3698:     my $now = time;
                   3699:     if (ref($access_hash) eq 'HASH') {
                   3700:         foreach my $key (keys(%{$access_hash})) {
                   3701:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3702:             if ($start > $now) {
                   3703:                 next;
                   3704:             }
                   3705:             if ($end && $end<$now) {
                   3706:                 next;
                   3707:             }
                   3708:             if ($scope eq 'public') {
                   3709:                 $public = $key;
                   3710:                 last;
                   3711:             } elsif ($scope eq 'guest') {
                   3712:                 $guest = $key;
                   3713:             } elsif ($scope eq 'domains') {
                   3714:                 push(@domains,$key);
                   3715:             } elsif ($scope eq 'users') {
                   3716:                 push(@users,$key);
                   3717:             } elsif ($scope eq 'course') {
                   3718:                 push(@courses,$key);
                   3719:             } elsif ($scope eq 'group') {
                   3720:                 push(@groups,$key);
                   3721:             }
                   3722:         }
                   3723:         if ($public) {
                   3724:             return 'ok';
                   3725:         }
                   3726:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3727:             if ($guest) {
                   3728:                 return $guest;
                   3729:             }
                   3730:         } else {
                   3731:             if (@domains > 0) {
                   3732:                 foreach my $domkey (@domains) {
                   3733:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3734:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3735:                             return 'ok';
                   3736:                         }
                   3737:                     }
                   3738:                 }
                   3739:             }
                   3740:             if (@users > 0) {
                   3741:                 foreach my $userkey (@users) {
1.865     raeburn  3742:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3743:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3744:                             if (ref($item) eq 'HASH') {
                   3745:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3746:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3747:                                     return 'ok';
                   3748:                                 }
                   3749:                             }
                   3750:                         }
                   3751:                     } 
1.765     albertel 3752:                 }
                   3753:             }
                   3754:             my %roleshash;
                   3755:             my @courses_and_groups = @courses;
                   3756:             push(@courses_and_groups,@groups); 
                   3757:             if (@courses_and_groups > 0) {
                   3758:                 my (%allgroups,%allroles); 
                   3759:                 my ($start,$end,$role,$sec,$group);
                   3760:                 foreach my $envkey (%env) {
1.811     albertel 3761:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3762:                         my $cid = $2.'_'.$3; 
                   3763:                         if ($1 eq 'gr') {
                   3764:                             $group = $4;
                   3765:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3766:                         } else {
                   3767:                             if ($4 eq '') {
                   3768:                                 $sec = 'none';
                   3769:                             } else {
                   3770:                                 $sec = $4;
                   3771:                             }
                   3772:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3773:                         }
1.811     albertel 3774:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3775:                         my $cid = $2.'_'.$3;
                   3776:                         if ($4 eq '') {
                   3777:                             $sec = 'none';
                   3778:                         } else {
                   3779:                             $sec = $4;
                   3780:                         }
                   3781:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3782:                     }
                   3783:                 }
                   3784:                 if (keys(%allroles) == 0) {
                   3785:                     return;
                   3786:                 }
                   3787:                 foreach my $key (@courses_and_groups) {
                   3788:                     my %content = %{$$access_hash{$key}};
                   3789:                     my $cnum = $content{'number'};
                   3790:                     my $cdom = $content{'domain'};
                   3791:                     my $cid = $cdom.'_'.$cnum;
                   3792:                     if (!exists($allroles{$cid})) {
                   3793:                         next;
                   3794:                     }    
                   3795:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3796:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3797:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3798:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3799:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3800:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3801:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3802:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3803:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3804:                                         if (grep/^all$/,@sections) {
                   3805:                                             return 'ok';
                   3806:                                         } else {
                   3807:                                             if (grep/^$sec$/,@sections) {
                   3808:                                                 return 'ok';
                   3809:                                             }
                   3810:                                         }
                   3811:                                     }
                   3812:                                 }
                   3813:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3814:                                     if (grep/^none$/,@groups) {
                   3815:                                         return 'ok';
                   3816:                                     }
                   3817:                                 } else {
                   3818:                                     if (grep/^all$/,@groups) {
                   3819:                                         return 'ok';
                   3820:                                     } 
                   3821:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3822:                                         if (grep/^$group$/,@groups) {
                   3823:                                             return 'ok';
                   3824:                                         }
                   3825:                                     }
                   3826:                                 } 
                   3827:                             }
                   3828:                         }
                   3829:                     }
                   3830:                 }
                   3831:             }
                   3832:             if ($guest) {
                   3833:                 return $guest;
                   3834:             }
                   3835:         }
                   3836:     }
                   3837:     return;
                   3838: }
                   3839: 
                   3840: sub course_group_datechecker {
                   3841:     my ($dates,$now,$status) = @_;
                   3842:     my ($start,$end) = split(/\./,$dates);
                   3843:     if (!$start && !$end) {
                   3844:         return 'ok';
                   3845:     }
                   3846:     if (grep/^active$/,@{$status}) {
                   3847:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3848:             return 'ok';
                   3849:         }
                   3850:     }
                   3851:     if (grep/^previous$/,@{$status}) {
                   3852:         if ($end > $now ) {
                   3853:             return 'ok';
                   3854:         }
                   3855:     }
                   3856:     if (grep/^future$/,@{$status}) {
                   3857:         if ($start > $now) {
                   3858:             return 'ok';
                   3859:         }
                   3860:     }
                   3861:     return; 
                   3862: }
                   3863: 
                   3864: sub parse_portfolio_url {
                   3865:     my ($url) = @_;
                   3866: 
                   3867:     my ($type,$udom,$unum,$group,$file_name);
                   3868:     
1.823     albertel 3869:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3870: 	$type = 1;
                   3871:         $udom = $1;
                   3872:         $unum = $2;
                   3873:         $file_name = $3;
1.823     albertel 3874:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3875: 	$type = 2;
                   3876:         $udom = $1;
                   3877:         $unum = $2;
                   3878:         $group = $3;
                   3879:         $file_name = $3.'/'.$4;
                   3880:     }
                   3881:     if (wantarray) {
                   3882: 	return ($type,$udom,$unum,$file_name,$group);
                   3883:     }
                   3884:     return $type;
                   3885: }
                   3886: 
                   3887: sub is_portfolio_url {
                   3888:     my ($url) = @_;
                   3889:     return scalar(&parse_portfolio_url($url));
                   3890: }
                   3891: 
1.798     raeburn  3892: sub is_portfolio_file {
                   3893:     my ($file) = @_;
1.820     raeburn  3894:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3895:         return 1;
                   3896:     }
                   3897:     return;
                   3898: }
                   3899: 
                   3900: 
1.341     www      3901: # ---------------------------------------------- Custom access rule evaluation
                   3902: 
                   3903: sub customaccess {
                   3904:     my ($priv,$uri)=@_;
1.807     albertel 3905:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3906:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3907:     $udom = &LONCAPA::clean_domain($udom);
                   3908:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3909:     my $access=0;
1.800     albertel 3910:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 3911: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   3912: 	if ($type eq 'user') {
                   3913: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 3914: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 3915: 		if ($tdom) {
                   3916: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   3917: 		}
1.896     albertel 3918: 		if ($tuname) {
                   3919: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 3920: 		}
                   3921: 		$access=($effect eq 'allow');
                   3922: 		last;
                   3923: 	    }
                   3924: 	} else {
                   3925: 	    if ($role) {
                   3926: 		if ($role ne $urole) { next; }
                   3927: 	    }
                   3928: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3929: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   3930: 		if ($tdom) {
                   3931: 		    if ($tdom ne $udom) { next; }
                   3932: 		}
                   3933: 		if ($tcrs) {
                   3934: 		    if ($tcrs ne $ucrs) { next; }
                   3935: 		}
                   3936: 		if ($tsec) {
                   3937: 		    if ($tsec ne $usec) { next; }
                   3938: 		}
                   3939: 		$access=($effect eq 'allow');
                   3940: 		last;
                   3941: 	    }
                   3942: 	    if ($realm eq '' && $role eq '') {
                   3943: 		$access=($effect eq 'allow');
                   3944: 	    }
1.402     bowersj2 3945: 	}
1.341     www      3946:     }
                   3947:     return $access;
                   3948: }
                   3949: 
1.103     harris41 3950: # ------------------------------------------------- Check for a user privilege
1.12      www      3951: 
                   3952: sub allowed {
1.810     raeburn  3953:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3954:     my $ver_orguri=$uri;
1.439     www      3955:     $uri=&deversion($uri);
1.152     www      3956:     my $orguri=$uri;
1.52      www      3957:     $uri=&declutter($uri);
1.809     raeburn  3958: 
1.810     raeburn  3959:     if ($priv eq 'evb') {
                   3960: # Evade communication block restrictions for specified role in a course
                   3961:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3962:             return $1;
                   3963:         } else {
                   3964:             return;
                   3965:         }
                   3966:     }
                   3967: 
1.620     albertel 3968:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3969: # Free bre access to adm and meta resources
1.775     albertel 3970:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3971: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3972: 	&& ($priv eq 'bre')) {
1.14      www      3973: 	return 'F';
1.159     www      3974:     }
                   3975: 
1.545     banghart 3976: # Free bre access to user's own portfolio contents
1.714     raeburn  3977:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3978:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3979: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3980:         my %setters;
                   3981:         my ($startblock,$endblock) = 
                   3982:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3983:         if ($startblock && $endblock) {
                   3984:             return 'B';
                   3985:         } else {
                   3986:             return 'F';
                   3987:         }
1.545     banghart 3988:     }
                   3989: 
1.762     raeburn  3990: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3991:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3992:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3993:         if (exists($env{'request.course.id'})) {
                   3994:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3995:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3996:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3997:                 my $courseprivid=$env{'request.course.id'};
                   3998:                 $courseprivid=~s/\_/\//;
                   3999:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4000:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4001:                     return $1; 
1.762     raeburn  4002:                 } else {
                   4003:                     if ($env{'request.course.sec'}) {
                   4004:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4005:                     }
                   4006:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4007:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4008:                         return $2;
                   4009:                     }
1.714     raeburn  4010:                 }
                   4011:             }
                   4012:         }
                   4013:     }
                   4014: 
1.159     www      4015: # Free bre to public access
                   4016: 
                   4017:     if ($priv eq 'bre') {
1.238     www      4018:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4019: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4020:            return 'F'; 
                   4021:         }
1.238     www      4022:         if ($copyright eq 'priv') {
                   4023:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4024: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4025: 		return '';
                   4026:             }
                   4027:         }
                   4028:         if ($copyright eq 'domain') {
                   4029:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4030: 	    unless (($env{'user.domain'} eq $1) ||
                   4031:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4032: 		return '';
                   4033:             }
1.262     matthew  4034:         }
1.620     albertel 4035:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4036:             # Library role, so allow browsing of resources in this domain.
                   4037:             return 'F';
1.238     www      4038:         }
1.341     www      4039:         if ($copyright eq 'custom') {
                   4040: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4041:         }
1.14      www      4042:     }
1.264     matthew  4043:     # Domain coordinator is trying to create a course
1.620     albertel 4044:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4045:         # uri is the requested domain in this case.
                   4046:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4047:         # a role of dc for the domain in question.
1.620     albertel 4048:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4049:     }
1.29      www      4050: 
1.52      www      4051:     my $thisallowed='';
                   4052:     my $statecond=0;
                   4053:     my $courseprivid='';
                   4054: 
                   4055: # Course
                   4056: 
1.620     albertel 4057:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4058:        $thisallowed.=$1;
                   4059:     }
1.29      www      4060: 
1.52      www      4061: # Domain
                   4062: 
1.620     albertel 4063:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4064:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4065:        $thisallowed.=$1;
                   4066:     }
1.52      www      4067: 
                   4068: # Course: uri itself is a course
1.66      www      4069:     my $courseuri=$uri;
                   4070:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4071:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4072: 
1.620     albertel 4073:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4074:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4075:        $thisallowed.=$1;
                   4076:     }
1.29      www      4077: 
1.665     albertel 4078: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4079: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4080:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4081: 	$thisallowed='';
1.671     raeburn  4082:         my ($match)=&is_on_map($uri);
                   4083:         if ($match) {
                   4084:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4085:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4086:                 $thisallowed.=$1;
                   4087:             }
                   4088:         } else {
1.705     albertel 4089:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4090:             if ($refuri) {
                   4091:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4092:                     $thisallowed='F';
1.671     raeburn  4093:                 } else {
                   4094:                     $refuri=&declutter($refuri);
                   4095:                     my ($match) = &is_on_map($refuri);
                   4096:                     if ($match) {
                   4097:                         $thisallowed='F';
                   4098:                     }
1.669     raeburn  4099:                 }
1.671     raeburn  4100:             }
                   4101:         }
1.314     www      4102:     }
1.492     albertel 4103: 
1.766     albertel 4104:     if ($priv eq 'bre'
                   4105: 	&& $thisallowed ne 'F' 
                   4106: 	&& $thisallowed ne '2'
                   4107: 	&& &is_portfolio_url($uri)) {
                   4108: 	$thisallowed = &portfolio_access($uri);
                   4109:     }
                   4110:     
1.52      www      4111: # Full access at system, domain or course-wide level? Exit.
1.29      www      4112: 
                   4113:     if ($thisallowed=~/F/) {
                   4114: 	return 'F';
                   4115:     }
                   4116: 
1.52      www      4117: # If this is generating or modifying users, exit with special codes
1.29      www      4118: 
1.643     www      4119:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4120: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4121: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4122: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4123: 	    unless ($auname) { return $thisallowed; }
                   4124: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4125: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4126: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4127: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4128: 	}
1.52      www      4129: 	return $thisallowed;
                   4130:     }
                   4131: #
1.103     harris41 4132: # Gathered so far: system, domain and course wide privileges
1.52      www      4133: #
                   4134: # Course: See if uri or referer is an individual resource that is part of 
                   4135: # the course
                   4136: 
1.620     albertel 4137:     if ($env{'request.course.id'}) {
1.232     www      4138: 
1.620     albertel 4139:        $courseprivid=$env{'request.course.id'};
                   4140:        if ($env{'request.course.sec'}) {
                   4141:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4142:        }
                   4143:        $courseprivid=~s/\_/\//;
                   4144:        my $checkreferer=1;
1.232     www      4145:        my ($match,$cond)=&is_on_map($uri);
                   4146:        if ($match) {
                   4147:            $statecond=$cond;
1.620     albertel 4148:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4149:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4150:                $thisallowed.=$1;
                   4151:                $checkreferer=0;
                   4152:            }
1.29      www      4153:        }
1.83      www      4154:        
1.148     www      4155:        if ($checkreferer) {
1.620     albertel 4156: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4157:             unless ($refuri) {
1.800     albertel 4158:                 foreach my $key (keys(%env)) {
                   4159: 		    if ($key=~/^httpref\..*\*/) {
                   4160: 			my $pattern=$key;
1.156     www      4161:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4162:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4163:                         $pattern=~s/\//\\\//g;
1.152     www      4164:                         if ($orguri=~/$pattern/) {
1.800     albertel 4165: 			    $refuri=$env{$key};
1.148     www      4166:                         }
                   4167:                     }
1.191     harris41 4168:                 }
1.148     www      4169:             }
1.232     www      4170: 
1.148     www      4171:          if ($refuri) { 
1.152     www      4172: 	  $refuri=&declutter($refuri);
1.232     www      4173:           my ($match,$cond)=&is_on_map($refuri);
                   4174:             if ($match) {
                   4175:               my $refstatecond=$cond;
1.620     albertel 4176:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4177:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4178:                   $thisallowed.=$1;
1.53      www      4179:                   $uri=$refuri;
                   4180:                   $statecond=$refstatecond;
1.52      www      4181:               }
                   4182:           }
1.148     www      4183:         }
1.29      www      4184:        }
1.52      www      4185:    }
1.29      www      4186: 
1.52      www      4187: #
1.103     harris41 4188: # Gathered now: all privileges that could apply, and condition number
1.52      www      4189: # 
                   4190: #
                   4191: # Full or no access?
                   4192: #
1.29      www      4193: 
1.52      www      4194:     if ($thisallowed=~/F/) {
                   4195: 	return 'F';
                   4196:     }
1.29      www      4197: 
1.52      www      4198:     unless ($thisallowed) {
                   4199:         return '';
                   4200:     }
1.29      www      4201: 
1.52      www      4202: # Restrictions exist, deal with them
                   4203: #
                   4204: #   C:according to course preferences
                   4205: #   R:according to resource settings
                   4206: #   L:unless locked
                   4207: #   X:according to user session state
                   4208: #
                   4209: 
                   4210: # Possibly locked functionality, check all courses
1.54      www      4211: # Locks might take effect only after 10 minutes cache expiration for other
                   4212: # courses, and 2 minutes for current course
1.52      www      4213: 
                   4214:     my $envkey;
                   4215:     if ($thisallowed=~/L/) {
1.620     albertel 4216:         foreach $envkey (keys %env) {
1.54      www      4217:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4218:                my $courseid=$2;
                   4219:                my $roleid=$1.'.'.$2;
1.92      www      4220:                $courseid=~s/^\///;
1.54      www      4221:                my $expiretime=600;
1.620     albertel 4222:                if ($env{'request.role'} eq $roleid) {
1.54      www      4223: 		  $expiretime=120;
                   4224:                }
                   4225: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4226:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4227:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4228: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4229:                }
1.620     albertel 4230:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4231:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4232: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4233:                        &log($env{'user.domain'},$env{'user.name'},
                   4234:                             $env{'user.home'},
1.57      www      4235:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4236:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4237:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4238: 		       return '';
                   4239:                    }
                   4240:                }
1.620     albertel 4241:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4242:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4243: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4244:                        &log($env{'user.domain'},$env{'user.name'},
                   4245:                             $env{'user.home'},
1.57      www      4246:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4247:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4248:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4249: 		       return '';
                   4250:                    }
                   4251:                }
                   4252: 	   }
1.29      www      4253:        }
1.52      www      4254:     }
                   4255:    
                   4256: #
                   4257: # Rest of the restrictions depend on selected course
                   4258: #
                   4259: 
1.620     albertel 4260:     unless ($env{'request.course.id'}) {
1.766     albertel 4261: 	if ($thisallowed eq 'A') {
                   4262: 	    return 'A';
1.814     raeburn  4263:         } elsif ($thisallowed eq 'B') {
                   4264:             return 'B';
1.766     albertel 4265: 	} else {
                   4266: 	    return '1';
                   4267: 	}
1.52      www      4268:     }
1.29      www      4269: 
1.52      www      4270: #
                   4271: # Now user is definitely in a course
                   4272: #
1.53      www      4273: 
                   4274: 
                   4275: # Course preferences
                   4276: 
                   4277:    if ($thisallowed=~/C/) {
1.620     albertel 4278:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4279:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4280:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4281: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4282: 	   if ($priv ne 'pch') { 
                   4283: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4284: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4285: 			$env{'request.course.id'});
                   4286: 	   }
1.237     www      4287:            return '';
                   4288:        }
                   4289: 
1.620     albertel 4290:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4291: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4292: 	   if ($priv ne 'pch') { 
                   4293: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4294: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4295: 			$env{'request.course.id'});
                   4296: 	   }
1.54      www      4297:            return '';
                   4298:        }
1.53      www      4299:    }
                   4300: 
                   4301: # Resource preferences
                   4302: 
                   4303:    if ($thisallowed=~/R/) {
1.620     albertel 4304:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4305:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4306: 	   if ($priv ne 'pch') { 
                   4307: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4308: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4309: 	   }
                   4310: 	   return '';
1.54      www      4311:        }
1.53      www      4312:    }
1.30      www      4313: 
1.246     www      4314: # Restricted by state or randomout?
1.30      www      4315: 
1.52      www      4316:    if ($thisallowed=~/X/) {
1.620     albertel 4317:       if ($env{'acc.randomout'}) {
1.579     albertel 4318: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4319:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4320:             return ''; 
                   4321:          }
1.247     www      4322:       }
                   4323:       if (&condval($statecond)) {
1.52      www      4324: 	 return '2';
                   4325:       } else {
                   4326:          return '';
                   4327:       }
                   4328:    }
1.30      www      4329: 
1.766     albertel 4330:     if ($thisallowed eq 'A') {
                   4331: 	return 'A';
1.814     raeburn  4332:     } elsif ($thisallowed eq 'B') {
                   4333:         return 'B';
1.766     albertel 4334:     }
1.52      www      4335:    return 'F';
1.232     www      4336: }
                   4337: 
1.710     albertel 4338: sub split_uri_for_cond {
                   4339:     my $uri=&deversion(&declutter(shift));
                   4340:     my @uriparts=split(/\//,$uri);
                   4341:     my $filename=pop(@uriparts);
                   4342:     my $pathname=join('/',@uriparts);
                   4343:     return ($pathname,$filename);
                   4344: }
1.232     www      4345: # --------------------------------------------------- Is a resource on the map?
                   4346: 
                   4347: sub is_on_map {
1.710     albertel 4348:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4349:     #Trying to find the conditional for the file
1.620     albertel 4350:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4351: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4352:     if ($match) {
1.289     bowersj2 4353: 	return (1,$1);
                   4354:     } else {
1.434     www      4355: 	return (0,0);
1.289     bowersj2 4356:     }
1.12      www      4357: }
                   4358: 
1.427     www      4359: # --------------------------------------------------------- Get symb from alias
                   4360: 
                   4361: sub get_symb_from_alias {
                   4362:     my $symb=shift;
                   4363:     my ($map,$resid,$url)=&decode_symb($symb);
                   4364: # Already is a symb
                   4365:     if ($url) { return $symb; }
                   4366: # Must be an alias
                   4367:     my $aliassymb='';
                   4368:     my %bighash;
1.620     albertel 4369:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4370:                             &GDBM_READER(),0640)) {
                   4371:         my $rid=$bighash{'mapalias_'.$symb};
                   4372: 	if ($rid) {
                   4373: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4374: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4375: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4376: 	}
                   4377:         untie %bighash;
                   4378:     }
                   4379:     return $aliassymb;
                   4380: }
                   4381: 
1.12      www      4382: # ----------------------------------------------------------------- Define Role
                   4383: 
                   4384: sub definerole {
                   4385:   if (allowed('mcr','/')) {
                   4386:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4387:     foreach my $role (split(':',$sysrole)) {
                   4388: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4389:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4390:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4391: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4392:                return "refused:s:$crole&$cqual"; 
                   4393:             }
                   4394:         }
1.191     harris41 4395:     }
1.800     albertel 4396:     foreach my $role (split(':',$domrole)) {
                   4397: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4398:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4399:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4400: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4401:                return "refused:d:$crole&$cqual"; 
                   4402:             }
                   4403:         }
1.191     harris41 4404:     }
1.800     albertel 4405:     foreach my $role (split(':',$courole)) {
                   4406: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4407:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4408:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4409: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4410:                return "refused:c:$crole&$cqual"; 
                   4411:             }
                   4412:         }
1.191     harris41 4413:     }
1.620     albertel 4414:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4415:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4416: 	        "rolesdef_$rolename=".
                   4417:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4418:     return reply($command,$env{'user.home'});
1.12      www      4419:   } else {
                   4420:     return 'refused';
                   4421:   }
1.105     harris41 4422: }
                   4423: 
                   4424: # ---------------- Make a metadata query against the network of library servers
                   4425: 
                   4426: sub metadata_query {
1.244     matthew  4427:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4428:     my %rhash;
1.845     albertel 4429:     my %libserv = &all_library();
1.244     matthew  4430:     my @server_list = (defined($server_array) ? @$server_array
                   4431:                                               : keys(%libserv) );
                   4432:     for my $server (@server_list) {
1.118     harris41 4433: 	unless ($custom or $customshow) {
                   4434: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4435: 	    $rhash{$server}=$reply;
                   4436: 	}
                   4437: 	else {
                   4438: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4439: 			     &escape($custom).':'.&escape($customshow),
                   4440: 			     $server);
                   4441: 	    $rhash{$server}=$reply;
                   4442: 	}
1.112     harris41 4443:     }
1.118     harris41 4444:     return \%rhash;
1.240     www      4445: }
                   4446: 
                   4447: # ----------------------------------------- Send log queries and wait for reply
                   4448: 
                   4449: sub log_query {
                   4450:     my ($uname,$udom,$query,%filters)=@_;
                   4451:     my $uhome=&homeserver($uname,$udom);
                   4452:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4453:     my $uhost=&hostname($uhome);
1.800     albertel 4454:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4455:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4456:                        $uhome);
1.479     albertel 4457:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4458:     return get_query_reply($queryid);
                   4459: }
                   4460: 
1.818     raeburn  4461: # -------------------------- Update MySQL table for portfolio file
                   4462: 
                   4463: sub update_portfolio_table {
1.821     raeburn  4464:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4465:     my $homeserver = &homeserver($uname,$udom);
                   4466:     my $queryid=
1.821     raeburn  4467:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4468:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4469:     my $reply = &get_query_reply($queryid);
                   4470:     return $reply;
                   4471: }
                   4472: 
1.899     raeburn  4473: # -------------------------- Update MySQL allusers table
                   4474: 
                   4475: sub update_allusers_table {
                   4476:     my ($uname,$udom,$names) = @_;
                   4477:     my $homeserver = &homeserver($uname,$udom);
                   4478:     my $queryid=
                   4479:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4480:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4481:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4482:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4483:                'generation='.&escape($names->{'generation'}).'%%'.
                   4484:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4485:                'id='.&escape($names->{'id'}),$homeserver);
                   4486:     my $reply = &get_query_reply($queryid);
                   4487:     return $reply;
                   4488: }
                   4489: 
1.508     raeburn  4490: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4491: 
                   4492: sub fetch_enrollment_query {
1.511     raeburn  4493:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4494:     my $homeserver;
1.547     raeburn  4495:     my $maxtries = 1;
1.508     raeburn  4496:     if ($context eq 'automated') {
                   4497:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4498:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4499:     } else {
                   4500:         $homeserver = &homeserver($cnum,$dom);
                   4501:     }
1.838     albertel 4502:     my $host=&hostname($homeserver);
1.506     raeburn  4503:     my $cmd = '';
1.800     albertel 4504:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4505:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4506:     }
                   4507:     $cmd =~ s/%%$//;
                   4508:     $cmd = &escape($cmd);
                   4509:     my $query = 'fetchenrollment';
1.620     albertel 4510:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4511:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4512:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4513:         return 'error: '.$queryid;
                   4514:     }
1.506     raeburn  4515:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4516:     my $tries = 1;
                   4517:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4518:         $reply = &get_query_reply($queryid);
                   4519:         $tries ++;
                   4520:     }
1.526     raeburn  4521:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4522:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4523:     } else {
1.901     albertel 4524:         my @responses = split(/:/,$reply);
1.515     raeburn  4525:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4526:             foreach my $line (@responses) {
                   4527:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4528:                 $$replyref{$key} = $value;
                   4529:             }
                   4530:         } else {
1.506     raeburn  4531:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4532:             foreach my $line (@responses) {
                   4533:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4534:                 $$replyref{$key} = $value;
                   4535:                 if ($value > 0) {
1.800     albertel 4536:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4537:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4538:                         my $destname = $pathname.'/'.$filename;
                   4539:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4540:                         if ($xml_classlist =~ /^error/) {
                   4541:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4542:                         } else {
1.506     raeburn  4543:                             if ( open(FILE,">$destname") ) {
                   4544:                                 print FILE &unescape($xml_classlist);
                   4545:                                 close(FILE);
1.526     raeburn  4546:                             } else {
                   4547:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4548:                             }
                   4549:                         }
                   4550:                     }
                   4551:                 }
                   4552:             }
                   4553:         }
                   4554:         return 'ok';
                   4555:     }
                   4556:     return 'error';
                   4557: }
                   4558: 
1.242     www      4559: sub get_query_reply {
                   4560:     my $queryid=shift;
1.240     www      4561:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4562:     my $reply='';
                   4563:     for (1..100) {
                   4564: 	sleep 2;
                   4565:         if (-e $replyfile.'.end') {
1.448     albertel 4566: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4567: 		$reply = join('',<$fh>);
                   4568: 		close($fh);
1.240     www      4569: 	   } else { return 'error: reply_file_error'; }
1.242     www      4570:            return &unescape($reply);
                   4571: 	}
1.240     www      4572:     }
1.242     www      4573:     return 'timeout:'.$queryid;
1.240     www      4574: }
                   4575: 
                   4576: sub courselog_query {
1.241     www      4577: #
                   4578: # possible filters:
                   4579: # url: url or symb
                   4580: # username
                   4581: # domain
                   4582: # action: view, submit, grade
                   4583: # start: timestamp
                   4584: # end: timestamp
                   4585: #
1.240     www      4586:     my (%filters)=@_;
1.620     albertel 4587:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4588:     if ($filters{'url'}) {
                   4589: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4590:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4591:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4592:     }
1.620     albertel 4593:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4594:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4595:     return &log_query($cname,$cdom,'courselog',%filters);
                   4596: }
                   4597: 
                   4598: sub userlog_query {
1.858     raeburn  4599: #
                   4600: # possible filters:
                   4601: # action: log check role
                   4602: # start: timestamp
                   4603: # end: timestamp
                   4604: #
1.240     www      4605:     my ($uname,$udom,%filters)=@_;
                   4606:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4607: }
                   4608: 
1.506     raeburn  4609: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4610: 
                   4611: sub auto_run {
1.508     raeburn  4612:     my ($cnum,$cdom) = @_;
1.876     raeburn  4613:     my $response = 0;
                   4614:     my $settings;
                   4615:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4616:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4617:         $settings = $domconfig{'autoenroll'};
                   4618:         if ($settings->{'run'} eq '1') {
                   4619:             $response = 1;
                   4620:         }
                   4621:     } else {
                   4622:         my $homeserver = &homeserver($cnum,$cdom);
                   4623:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4624:     }
1.506     raeburn  4625:     return $response;
                   4626: }
1.776     albertel 4627: 
1.506     raeburn  4628: sub auto_get_sections {
1.508     raeburn  4629:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4630:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4631:     my @secs = ();
1.511     raeburn  4632:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4633:     unless ($response eq 'refused') {
1.901     albertel 4634:         @secs = split(/:/,$response);
1.506     raeburn  4635:     }
                   4636:     return @secs;
                   4637: }
1.776     albertel 4638: 
1.506     raeburn  4639: sub auto_new_course {
1.508     raeburn  4640:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4641:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4642:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4643:     return $response;
                   4644: }
1.776     albertel 4645: 
1.506     raeburn  4646: sub auto_validate_courseID {
1.508     raeburn  4647:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4648:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4649:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4650:     return $response;
                   4651: }
1.776     albertel 4652: 
1.506     raeburn  4653: sub auto_create_password {
1.873     raeburn  4654:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4655:     my ($homeserver,$response);
1.506     raeburn  4656:     my $create_passwd = 0;
                   4657:     my $authchk = '';
1.873     raeburn  4658:     if ($udom =~ /^$match_domain$/) {
                   4659:         $homeserver = &domain($udom,'primary');
                   4660:     }
                   4661:     if ($homeserver eq '') {
                   4662:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4663:             $homeserver = &homeserver($cnum,$cdom);
                   4664:         }
                   4665:     }
                   4666:     if ($homeserver eq '') {
                   4667:         $authchk = 'nodomain';
1.506     raeburn  4668:     } else {
1.873     raeburn  4669:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4670:         if ($response eq 'refused') {
                   4671:             $authchk = 'refused';
                   4672:         } else {
1.901     albertel 4673:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4674:         }
1.506     raeburn  4675:     }
                   4676:     return ($authparam,$create_passwd,$authchk);
                   4677: }
                   4678: 
1.706     raeburn  4679: sub auto_photo_permission {
                   4680:     my ($cnum,$cdom,$students) = @_;
                   4681:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4682:     my ($outcome,$perm_reqd,$conditions) = 
                   4683: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4684:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4685: 	return (undef,undef);
                   4686:     }
1.706     raeburn  4687:     return ($outcome,$perm_reqd,$conditions);
                   4688: }
                   4689: 
                   4690: sub auto_checkphotos {
                   4691:     my ($uname,$udom,$pid) = @_;
                   4692:     my $homeserver = &homeserver($uname,$udom);
                   4693:     my ($result,$resulttype);
                   4694:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4695: 				   &escape($uname).':'.&escape($pid),
                   4696: 				   $homeserver));
1.709     albertel 4697:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4698: 	return (undef,undef);
                   4699:     }
1.706     raeburn  4700:     if ($outcome) {
                   4701:         ($result,$resulttype) = split(/:/,$outcome);
                   4702:     } 
                   4703:     return ($result,$resulttype);
                   4704: }
                   4705: 
                   4706: sub auto_photochoice {
                   4707:     my ($cnum,$cdom) = @_;
                   4708:     my $homeserver = &homeserver($cnum,$cdom);
                   4709:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4710: 						       &escape($cdom),
                   4711: 						       $homeserver)));
1.709     albertel 4712:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4713: 	return (undef,undef);
                   4714:     }
1.706     raeburn  4715:     return ($update,$comment);
                   4716: }
                   4717: 
                   4718: sub auto_photoupdate {
                   4719:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4720:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4721:     my $host=&hostname($homeserver);
1.706     raeburn  4722:     my $cmd = '';
                   4723:     my $maxtries = 1;
1.800     albertel 4724:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4725:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4726:     }
                   4727:     $cmd =~ s/%%$//;
                   4728:     $cmd = &escape($cmd);
                   4729:     my $query = 'institutionalphotos';
                   4730:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4731:     unless ($queryid=~/^\Q$host\E\_/) {
                   4732:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4733:         return 'error: '.$queryid;
                   4734:     }
                   4735:     my $reply = &get_query_reply($queryid);
                   4736:     my $tries = 1;
                   4737:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4738:         $reply = &get_query_reply($queryid);
                   4739:         $tries ++;
                   4740:     }
                   4741:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4742:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4743:     } else {
                   4744:         my @responses = split(/:/,$reply);
                   4745:         my $outcome = shift(@responses); 
                   4746:         foreach my $item (@responses) {
                   4747:             my ($key,$value) = split(/=/,$item);
                   4748:             $$photo{$key} = $value;
                   4749:         }
                   4750:         return $outcome;
                   4751:     }
                   4752:     return 'error';
                   4753: }
                   4754: 
1.521     raeburn  4755: sub auto_instcode_format {
1.793     albertel 4756:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4757: 	$cat_order) = @_;
1.521     raeburn  4758:     my $courses = '';
1.772     raeburn  4759:     my @homeservers;
1.521     raeburn  4760:     if ($caller eq 'global') {
1.841     albertel 4761: 	my %servers = &get_servers($codedom,'library');
                   4762: 	foreach my $tryserver (keys(%servers)) {
                   4763: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4764: 		push(@homeservers,$tryserver);
                   4765: 	    }
1.584     raeburn  4766:         }
1.521     raeburn  4767:     } else {
1.772     raeburn  4768:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4769:     }
1.793     albertel 4770:     foreach my $code (keys(%{$instcodes})) {
                   4771:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4772:     }
                   4773:     chop($courses);
1.772     raeburn  4774:     my $ok_response = 0;
                   4775:     my $response;
                   4776:     while (@homeservers > 0 && $ok_response == 0) {
                   4777:         my $server = shift(@homeservers); 
                   4778:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4779:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4780:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4781: 		split(/:/,$response);
1.772     raeburn  4782:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4783:             push(@{$codetitles},&str2array($codetitles_str));
                   4784:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4785:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4786:             $ok_response = 1;
                   4787:         }
                   4788:     }
                   4789:     if ($ok_response) {
1.521     raeburn  4790:         return 'ok';
1.772     raeburn  4791:     } else {
                   4792:         return $response;
1.521     raeburn  4793:     }
                   4794: }
                   4795: 
1.792     raeburn  4796: sub auto_instcode_defaults {
                   4797:     my ($domain,$returnhash,$code_order) = @_;
                   4798:     my @homeservers;
1.841     albertel 4799: 
                   4800:     my %servers = &get_servers($domain,'library');
                   4801:     foreach my $tryserver (keys(%servers)) {
                   4802: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4803: 	    push(@homeservers,$tryserver);
                   4804: 	}
1.792     raeburn  4805:     }
1.841     albertel 4806: 
1.792     raeburn  4807:     my $response;
1.841     albertel 4808:     foreach my $server (@homeservers) {
1.792     raeburn  4809:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4810:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4811: 	
                   4812: 	foreach my $pair (split(/\&/,$response)) {
                   4813: 	    my ($name,$value)=split(/\=/,$pair);
                   4814: 	    if ($name eq 'code_order') {
                   4815: 		@{$code_order} = split(/\&/,&unescape($value));
                   4816: 	    } else {
                   4817: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4818: 	    }
                   4819: 	}
                   4820: 	return 'ok';
1.792     raeburn  4821:     }
1.841     albertel 4822: 
                   4823:     return $response;
1.792     raeburn  4824: } 
                   4825: 
1.777     albertel 4826: sub auto_validate_class_sec {
1.773     raeburn  4827:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4828:     my $homeserver = &homeserver($cnum,$cdom);
                   4829:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4830:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4831:     return $response;
                   4832: }
                   4833: 
1.679     raeburn  4834: # ------------------------------------------------------- Course Group routines
                   4835: 
                   4836: sub get_coursegroups {
1.809     raeburn  4837:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4838:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4839: }
                   4840: 
1.679     raeburn  4841: sub modify_coursegroup {
                   4842:     my ($cdom,$cnum,$groupsettings) = @_;
                   4843:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4844: }
                   4845: 
1.809     raeburn  4846: sub toggle_coursegroup_status {
                   4847:     my ($cdom,$cnum,$group,$action) = @_;
                   4848:     my ($from_namespace,$to_namespace);
                   4849:     if ($action eq 'delete') {
                   4850:         $from_namespace = 'coursegroups';
                   4851:         $to_namespace = 'deleted_groups';
                   4852:     } else {
                   4853:         $from_namespace = 'deleted_groups';
                   4854:         $to_namespace = 'coursegroups';
                   4855:     }
                   4856:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4857:     if (my $tmp = &error(%curr_group)) {
                   4858:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4859:         return ('read error',$tmp);
                   4860:     } else {
                   4861:         my %savedsettings = %curr_group; 
1.809     raeburn  4862:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4863:         my $deloutcome;
                   4864:         if ($result eq 'ok') {
1.809     raeburn  4865:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4866:         } else {
                   4867:             return ('write error',$result);
                   4868:         }
                   4869:         if ($deloutcome eq 'ok') {
                   4870:             return 'ok';
                   4871:         } else {
                   4872:             return ('delete error',$deloutcome);
                   4873:         }
                   4874:     }
                   4875: }
                   4876: 
1.679     raeburn  4877: sub modify_group_roles {
                   4878:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4879:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4880:     my $role = 'gr/'.&escape($userprivs);
                   4881:     my ($uname,$udom) = split(/:/,$user);
                   4882:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4883:     if ($result eq 'ok') {
                   4884:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4885:     }
1.679     raeburn  4886:     return $result;
                   4887: }
                   4888: 
                   4889: sub modify_coursegroup_membership {
                   4890:     my ($cdom,$cnum,$membership) = @_;
                   4891:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4892:     return $result;
                   4893: }
                   4894: 
1.682     raeburn  4895: sub get_active_groups {
                   4896:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4897:     my $now = time;
                   4898:     my %groups = ();
                   4899:     foreach my $key (keys(%env)) {
1.811     albertel 4900:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4901:             my ($start,$end) = split(/\./,$env{$key});
                   4902:             if (($end!=0) && ($end<$now)) { next; }
                   4903:             if (($start!=0) && ($start>$now)) { next; }
                   4904:             if ($1 eq $cdom && $2 eq $cnum) {
                   4905:                 $groups{$3} = $env{$key} ;
                   4906:             }
                   4907:         }
                   4908:     }
                   4909:     return %groups;
                   4910: }
                   4911: 
1.683     raeburn  4912: sub get_group_membership {
                   4913:     my ($cdom,$cnum,$group) = @_;
                   4914:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4915: }
                   4916: 
                   4917: sub get_users_groups {
                   4918:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4919:     my @usersgroups;
1.683     raeburn  4920:     my $cachetime=1800;
                   4921: 
                   4922:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4923:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4924:     if (defined($cached)) {
1.734     albertel 4925:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4926:     } else {  
                   4927:         $grouplist = '';
1.816     raeburn  4928:         my $courseurl = &courseid_to_courseurl($courseid);
                   4929:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4930:         my $access_end = $env{'course.'.$courseid.
                   4931:                               '.default_enrollment_end_date'};
                   4932:         my $now = time;
                   4933:         foreach my $key (keys(%roleshash)) {
                   4934:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4935:                 my $group = $1;
                   4936:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4937:                     my $start = $2;
                   4938:                     my $end = $1;
                   4939:                     if ($start == -1) { next; } # deleted from group
                   4940:                     if (($start!=0) && ($start>$now)) { next; }
                   4941:                     if (($end!=0) && ($end<$now)) {
                   4942:                         if ($access_end && $access_end < $now) {
                   4943:                             if ($access_end - $end < 86400) {
                   4944:                                 push(@usersgroups,$group);
1.733     raeburn  4945:                             }
                   4946:                         }
1.817     raeburn  4947:                         next;
1.733     raeburn  4948:                     }
1.817     raeburn  4949:                     push(@usersgroups,$group);
1.683     raeburn  4950:                 }
                   4951:             }
                   4952:         }
1.817     raeburn  4953:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4954:         $grouplist = join(':',@usersgroups);
                   4955:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4956:     }
1.733     raeburn  4957:     return @usersgroups;
1.683     raeburn  4958: }
                   4959: 
                   4960: sub devalidate_getgroups_cache {
                   4961:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4962:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4963: 
1.683     raeburn  4964:     my $hashid="$udom:$uname:$courseid";
                   4965:     &devalidate_cache_new('getgroups',$hashid);
                   4966: }
                   4967: 
1.12      www      4968: # ------------------------------------------------------------------ Plain Text
                   4969: 
                   4970: sub plaintext {
1.742     raeburn  4971:     my ($short,$type,$cid) = @_;
1.758     albertel 4972:     if ($short =~ /^cr/) {
                   4973: 	return (split('/',$short))[-1];
                   4974:     }
1.742     raeburn  4975:     if (!defined($cid)) {
                   4976:         $cid = $env{'request.course.id'};
                   4977:     }
                   4978:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4979:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4980:                                           '.plaintext'});
                   4981:     }
                   4982:     my %rolenames = (
                   4983:                       Course => 'std',
                   4984:                       Group => 'alt1',
                   4985:                     );
                   4986:     if (defined($type) && 
                   4987:          defined($rolenames{$type}) && 
                   4988:          defined($prp{$short}{$rolenames{$type}})) {
                   4989:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4990:     } else {
                   4991:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4992:     }
1.12      www      4993: }
                   4994: 
                   4995: # ----------------------------------------------------------------- Assign Role
                   4996: 
                   4997: sub assignrole {
1.357     www      4998:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4999:     my $mrole;
                   5000:     if ($role =~ /^cr\//) {
1.393     www      5001:         my $cwosec=$url;
1.811     albertel 5002:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5003: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5004:            &logthis('Refused custom assignrole: '.
                   5005:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5006: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5007:            return 'refused'; 
                   5008:         }
1.21      www      5009:         $mrole='cr';
1.678     raeburn  5010:     } elsif ($role =~ /^gr\//) {
                   5011:         my $cwogrp=$url;
1.811     albertel 5012:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5013:         unless (&allowed('mdg',$cwogrp)) {
                   5014:             &logthis('Refused group assignrole: '.
                   5015:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5016:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5017:             return 'refused';
                   5018:         }
                   5019:         $mrole='gr';
1.21      www      5020:     } else {
1.82      www      5021:         my $cwosec=$url;
1.811     albertel 5022:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5023:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5024:            &logthis('Refused assignrole: '.
                   5025:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5026: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5027:            return 'refused'; 
                   5028:         }
1.21      www      5029:         $mrole=$role;
                   5030:     }
1.620     albertel 5031:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5032:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5033:     if ($end) { $command.='_'.$end; }
1.21      www      5034:     if ($start) {
                   5035: 	if ($end) { 
1.81      www      5036:            $command.='_'.$start; 
1.21      www      5037:         } else {
1.81      www      5038:            $command.='_0_'.$start;
1.21      www      5039:         }
                   5040:     }
1.739     raeburn  5041:     my $origstart = $start;
                   5042:     my $origend = $end;
1.357     www      5043: # actually delete
                   5044:     if ($deleteflag) {
1.373     www      5045: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5046: # modify command to delete the role
1.620     albertel 5047:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5048:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5049: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5050: # set start and finish to negative values for userrolelog
                   5051:            $start=-1;
                   5052:            $end=-1;
                   5053:         }
                   5054:     }
                   5055: # send command
1.349     www      5056:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5057: # log new user role if status is ok
1.349     www      5058:     if ($answer eq 'ok') {
1.663     raeburn  5059: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5060: # for course roles, perform group memberships changes triggered by role change.
                   5061:         unless ($role =~ /^gr/) {
                   5062:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5063:                                              $origstart);
                   5064:         }
1.349     www      5065:     }
                   5066:     return $answer;
1.169     harris41 5067: }
                   5068: 
                   5069: # -------------------------------------------------- Modify user authentication
1.197     www      5070: # Overrides without validation
                   5071: 
1.169     harris41 5072: sub modifyuserauth {
                   5073:     my ($udom,$uname,$umode,$upass)=@_;
                   5074:     my $uhome=&homeserver($uname,$udom);
1.197     www      5075:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5076:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5077:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5078:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5079:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5080: 		     &escape($upass),$uhome);
1.620     albertel 5081:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5082:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5083:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5084:     &log($udom,,$uname,$uhome,
1.620     albertel 5085:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5086:                                      $env{'user.name'}.', '.$umode.
1.197     www      5087:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5088:     unless ($reply eq 'ok') {
1.197     www      5089:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5090: 	return 'error: '.$reply;
                   5091:     }   
1.170     harris41 5092:     return 'ok';
1.80      www      5093: }
                   5094: 
1.81      www      5095: # --------------------------------------------------------------- Modify a user
1.80      www      5096: 
1.81      www      5097: sub modifyuser {
1.206     matthew  5098:     my ($udom,    $uname, $uid,
                   5099:         $umode,   $upass, $first,
                   5100:         $middle,  $last,  $gene,
1.387     www      5101:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5102:     $udom= &LONCAPA::clean_domain($udom);
                   5103:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5104:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5105:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5106: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5107:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5108:                                      ' desiredhome not specified'). 
1.620     albertel 5109:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5110:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5111:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5112: # ----------------------------------------------------------------- Create User
1.406     albertel 5113:     if (($uhome eq 'no_host') && 
                   5114: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5115:         my $unhome='';
1.844     albertel 5116:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5117:             $unhome = $desiredhome;
1.620     albertel 5118: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5119: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5120:         } else { # load balancing routine for determining $unhome
1.81      www      5121:             my $loadm=10000000;
1.841     albertel 5122: 	    my %servers = &get_servers($udom,'library');
                   5123: 	    foreach my $tryserver (keys(%servers)) {
                   5124: 		my $answer=reply('load',$tryserver);
                   5125: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5126: 		    $loadm=$answer;
                   5127: 		    $unhome=$tryserver;
                   5128: 		}
1.80      www      5129: 	    }
                   5130:         }
                   5131:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5132: 	    return 'error: unable to find a home server for '.$uname.
                   5133:                    ' in domain '.$udom;
1.80      www      5134:         }
                   5135:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5136:                          &escape($upass),$unhome);
                   5137: 	unless ($reply eq 'ok') {
                   5138:             return 'error: '.$reply;
                   5139:         }   
1.230     stredwic 5140:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5141:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5142: 	    return 'error: unable verify users home machine.';
1.80      www      5143:         }
1.209     matthew  5144:     }   # End of creation of new user
1.80      www      5145: # ---------------------------------------------------------------------- Add ID
                   5146:     if ($uid) {
                   5147:        $uid=~tr/A-Z/a-z/;
                   5148:        my %uidhash=&idrget($udom,$uname);
1.196     www      5149:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5150:          && (!$forceid)) {
1.80      www      5151: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5152: 	      return 'error: user id "'.$uid.'" does not match '.
                   5153:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5154:           }
                   5155:        } else {
                   5156: 	  &idput($udom,($uname => $uid));
                   5157:        }
                   5158:     }
                   5159: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5160:     my @tmp=&get('environment',
1.899     raeburn  5161: 		   ['firstname','middlename','lastname','generation','id',
                   5162:                     'permanentemail'],
1.134     albertel 5163: 		   $udom,$uname);
1.313     matthew  5164:     my %names;
                   5165:     if ($tmp[0] =~ m/^error:.*/) { 
                   5166:         %names=(); 
                   5167:     } else {
                   5168:         %names = @tmp;
                   5169:     }
1.388     www      5170: #
                   5171: # Make sure to not trash student environment if instructor does not bother
                   5172: # to supply name and email information
                   5173: #
                   5174:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5175:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5176:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5177:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5178:     if ($email) {
                   5179:        $email=~s/[^\w\@\.\-\,]//gs;
                   5180:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5181: 			   $names{'critnotification'} = $email;
                   5182: 			   $names{'permanentemail'} = $email; }
                   5183:     }
1.899     raeburn  5184:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5185:     my $reply = &put('environment', \%names, $udom,$uname);
                   5186:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5187:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5188:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5189:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5190:              $umode.', '.$first.', '.$middle.', '.
                   5191: 	     $last.', '.$gene.' by '.
1.620     albertel 5192:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5193:     return 'ok';
1.80      www      5194: }
                   5195: 
1.81      www      5196: # -------------------------------------------------------------- Modify student
1.80      www      5197: 
1.81      www      5198: sub modifystudent {
                   5199:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5200:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5201:     if (!$cid) {
1.620     albertel 5202: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5203: 	    return 'not_in_class';
                   5204: 	}
1.80      www      5205:     }
                   5206: # --------------------------------------------------------------- Make the user
1.81      www      5207:     my $reply=&modifyuser
1.209     matthew  5208: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5209:          $desiredhome,$email);
1.80      www      5210:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5211:     # This will cause &modify_student_enrollment to get the uid from the
                   5212:     # students environment
                   5213:     $uid = undef if (!$forceid);
1.455     albertel 5214:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5215: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5216:     return $reply;
                   5217: }
                   5218: 
                   5219: sub modify_student_enrollment {
1.515     raeburn  5220:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5221:     my ($cdom,$cnum,$chome);
                   5222:     if (!$cid) {
1.620     albertel 5223: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5224: 	    return 'not_in_class';
                   5225: 	}
1.620     albertel 5226: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5227: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5228:     } else {
                   5229: 	($cdom,$cnum)=split(/_/,$cid);
                   5230:     }
1.620     albertel 5231:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5232:     if (!$chome) {
1.457     raeburn  5233: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5234:     }
1.455     albertel 5235:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5236:     # Make sure the user exists
1.81      www      5237:     my $uhome=&homeserver($uname,$udom);
                   5238:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5239: 	return 'error: no such user';
                   5240:     }
1.297     matthew  5241:     # Get student data if we were not given enough information
                   5242:     if (!defined($first)  || $first  eq '' || 
                   5243:         !defined($last)   || $last   eq '' || 
                   5244:         !defined($uid)    || $uid    eq '' || 
                   5245:         !defined($middle) || $middle eq '' || 
                   5246:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5247:         # They did not supply us with enough data to enroll the student, so
                   5248:         # we need to pick up more information.
1.297     matthew  5249:         my %tmp = &get('environment',
1.294     matthew  5250:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5251:                        ,$udom,$uname);
                   5252: 
1.800     albertel 5253:         #foreach my $key (keys(%tmp)) {
                   5254:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5255:         #}
1.294     matthew  5256:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5257:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5258:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5259:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5260:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5261:     }
1.556     albertel 5262:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5263:     my $reply=cput('classlist',
                   5264: 		   {"$uname:$udom" => 
1.515     raeburn  5265: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5266: 		   $cdom,$cnum);
1.81      www      5267:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5268: 	return 'error: '.$reply;
1.652     albertel 5269:     } else {
                   5270: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5271:     }
1.297     matthew  5272:     # Add student role to user
1.83      www      5273:     my $uurl='/'.$cid;
1.81      www      5274:     $uurl=~s/\_/\//g;
                   5275:     if ($usec) {
                   5276: 	$uurl.='/'.$usec;
                   5277:     }
                   5278:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5279: }
                   5280: 
1.556     albertel 5281: sub format_name {
                   5282:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5283:     my $name;
                   5284:     if ($first ne 'lastname') {
                   5285: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5286:     } else {
                   5287: 	if ($lastname=~/\S/) {
                   5288: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5289: 	    $name=~s/\s+,/,/;
                   5290: 	} else {
                   5291: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5292: 	}
                   5293:     }
                   5294:     $name=~s/^\s+//;
                   5295:     $name=~s/\s+$//;
                   5296:     $name=~s/\s+/ /g;
                   5297:     return $name;
                   5298: }
                   5299: 
1.84      www      5300: # ------------------------------------------------- Write to course preferences
                   5301: 
                   5302: sub writecoursepref {
                   5303:     my ($courseid,%prefs)=@_;
                   5304:     $courseid=~s/^\///;
                   5305:     $courseid=~s/\_/\//g;
                   5306:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5307:     my $chome=homeserver($cnum,$cdomain);
                   5308:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5309: 	return 'error: no such course';
                   5310:     }
                   5311:     my $cstring='';
1.800     albertel 5312:     foreach my $pref (keys(%prefs)) {
                   5313: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5314:     }
1.84      www      5315:     $cstring=~s/\&$//;
                   5316:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5317: }
                   5318: 
                   5319: # ---------------------------------------------------------- Make/modify course
                   5320: 
                   5321: sub createcourse {
1.741     raeburn  5322:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5323:         $course_owner,$crstype)=@_;
1.84      www      5324:     $url=&declutter($url);
                   5325:     my $cid='';
1.264     matthew  5326:     unless (&allowed('ccc',$udom)) {
1.84      www      5327:         return 'refused';
                   5328:     }
                   5329: # ------------------------------------------------------------------- Create ID
1.674     www      5330:    my $uname=int(1+rand(9)).
                   5331:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5332:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5333:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5334: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5335:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5336:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5337:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5338:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5339:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5340:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5341:            return 'error: unable to generate unique course-ID';
                   5342:        } 
                   5343:    }
1.264     matthew  5344: # ------------------------------------------------ Check supplied server name
1.620     albertel 5345:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5346:     if (! &is_library($course_server)) {
1.264     matthew  5347:         return 'error:bad server name '.$course_server;
                   5348:     }
1.84      www      5349: # ------------------------------------------------------------- Make the course
                   5350:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5351:                       $course_server);
1.84      www      5352:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5353:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5354:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5355: 	return 'error: no such course';
                   5356:     }
1.271     www      5357: # ----------------------------------------------------------------- Course made
1.516     raeburn  5358: # log existence
                   5359:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5360:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5361:                   &escape($crstype),$uhome);
1.358     www      5362:     &flushcourselogs();
                   5363: # set toplevel url
1.271     www      5364:     my $topurl=$url;
                   5365:     unless ($nonstandard) {
                   5366: # ------------------------------------------ For standard courses, make top url
                   5367:         my $mapurl=&clutter($url);
1.278     www      5368:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5369:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5370: <map>
                   5371: <resource id="1" type="start"></resource>
                   5372: <resource id="2" src="$mapurl"></resource>
                   5373: <resource id="3" type="finish"></resource>
                   5374: <link index="1" from="1" to="2"></link>
                   5375: <link index="2" from="2" to="3"></link>
                   5376: </map>
                   5377: ENDINITMAP
                   5378:         $topurl=&declutter(
1.638     albertel 5379:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5380:                           );
                   5381:     }
                   5382: # ----------------------------------------------------------- Write preferences
1.84      www      5383:     &writecoursepref($udom.'_'.$uname,
                   5384:                      ('description' => $description,
1.271     www      5385:                       'url'         => $topurl));
1.84      www      5386:     return '/'.$udom.'/'.$uname;
                   5387: }
                   5388: 
1.813     albertel 5389: sub is_course {
                   5390:     my ($cdom,$cnum) = @_;
                   5391:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5392: 				undef,'.');
                   5393:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5394:         return 1;
                   5395:     }
                   5396:     return 0;
                   5397: }
                   5398: 
1.21      www      5399: # ---------------------------------------------------------- Assign Custom Role
                   5400: 
                   5401: sub assigncustomrole {
1.357     www      5402:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5403:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5404:                        $end,$start,$deleteflag);
1.21      www      5405: }
                   5406: 
                   5407: # ----------------------------------------------------------------- Revoke Role
                   5408: 
                   5409: sub revokerole {
1.357     www      5410:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5411:     my $now=time;
1.357     www      5412:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5413: }
                   5414: 
                   5415: # ---------------------------------------------------------- Revoke Custom Role
                   5416: 
                   5417: sub revokecustomrole {
1.357     www      5418:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5419:     my $now=time;
1.357     www      5420:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5421:            $deleteflag);
1.17      www      5422: }
                   5423: 
1.533     banghart 5424: # ------------------------------------------------------------ Disk usage
1.535     albertel 5425: sub diskusage {
1.533     banghart 5426:     my ($udom,$uname,$directoryRoot)=@_;
                   5427:     $directoryRoot =~ s/\/$//;
1.535     albertel 5428:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5429:     return $listing;
1.512     banghart 5430: }
                   5431: 
1.566     banghart 5432: sub is_locked {
                   5433:     my ($file_name, $domain, $user) = @_;
                   5434:     my @check;
                   5435:     my $is_locked;
                   5436:     push @check, $file_name;
1.613     albertel 5437:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5438: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5439:     my ($tmp)=keys(%locked);
                   5440:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5441:     
1.566     banghart 5442:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5443:         $is_locked = 'false';
                   5444:         foreach my $entry (@{$locked{$file_name}}) {
                   5445:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5446:                $is_locked = 'true';
                   5447:                last;
1.745     raeburn  5448:            }
                   5449:        }
1.566     banghart 5450:     } else {
                   5451:         $is_locked = 'false';
                   5452:     }
                   5453: }
                   5454: 
1.759     albertel 5455: sub declutter_portfile {
                   5456:     my ($file) = @_;
1.833     albertel 5457:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5458:     return $file;
                   5459: }
                   5460: 
1.559     banghart 5461: # ------------------------------------------------------------- Mark as Read Only
                   5462: 
                   5463: sub mark_as_readonly {
                   5464:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5465:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5466:     my ($tmp)=keys(%current_permissions);
                   5467:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5468:     foreach my $file (@{$files}) {
1.759     albertel 5469: 	$file = &declutter_portfile($file);
1.561     banghart 5470:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5471:     }
1.613     albertel 5472:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5473:     return;
                   5474: }
                   5475: 
1.572     banghart 5476: # ------------------------------------------------------------Save Selected Files
                   5477: 
                   5478: sub save_selected_files {
                   5479:     my ($user, $path, @files) = @_;
                   5480:     my $filename = $user."savedfiles";
1.573     banghart 5481:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5482:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5483:     foreach my $file (@files) {
1.620     albertel 5484:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5485:     }
                   5486:     foreach my $file (@other_files) {
1.574     banghart 5487:         print (OUT $file."\n");
1.572     banghart 5488:     }
1.574     banghart 5489:     close (OUT);
1.572     banghart 5490:     return 'ok';
                   5491: }
                   5492: 
1.574     banghart 5493: sub clear_selected_files {
                   5494:     my ($user) = @_;
                   5495:     my $filename = $user."savedfiles";
                   5496:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5497:     print (OUT undef);
                   5498:     close (OUT);
                   5499:     return ("ok");    
                   5500: }
                   5501: 
1.572     banghart 5502: sub files_in_path {
                   5503:     my ($user, $path) = @_;
                   5504:     my $filename = $user."savedfiles";
                   5505:     my %return_files;
1.574     banghart 5506:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5507:     while (my $line_in = <IN>) {
1.574     banghart 5508:         chomp ($line_in);
                   5509:         my @paths_and_file = split (m!/!, $line_in);
                   5510:         my $file_part = pop (@paths_and_file);
                   5511:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5512:         $path_part.='/';
                   5513:         my $path_and_file = $path_part.$file_part;
                   5514:         if ($path_part eq $path) {
                   5515:             $return_files{$file_part}= 'selected';
                   5516:         }
                   5517:     }
1.574     banghart 5518:     close (IN);
                   5519:     return (\%return_files);
1.572     banghart 5520: }
                   5521: 
                   5522: # called in portfolio select mode, to show files selected NOT in current directory
                   5523: sub files_not_in_path {
                   5524:     my ($user, $path) = @_;
                   5525:     my $filename = $user."savedfiles";
                   5526:     my @return_files;
                   5527:     my $path_part;
1.800     albertel 5528:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5529:     while (my $line = <IN>) {
1.572     banghart 5530:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5531:         my @paths_and_file = split(m|/|, $line);
                   5532:         my $file_part = pop(@paths_and_file);
                   5533:         chomp($file_part);
                   5534:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5535:         $path_part .= '/';
                   5536:         my $path_and_file = $path_part.$file_part;
                   5537:         if ($path_part ne $path) {
1.800     albertel 5538:             push(@return_files, ($path_and_file));
1.572     banghart 5539:         }
                   5540:     }
1.800     albertel 5541:     close(OUT);
1.574     banghart 5542:     return (@return_files);
1.572     banghart 5543: }
                   5544: 
1.745     raeburn  5545: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5546: 
1.745     raeburn  5547: sub get_portfile_permissions {
                   5548:     my ($domain,$user) = @_;
1.613     albertel 5549:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5550:     my ($tmp)=keys(%current_permissions);
                   5551:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5552:     return \%current_permissions;
                   5553: }
                   5554: 
                   5555: #---------------------------------------------Get portfolio file access controls
                   5556: 
1.749     raeburn  5557: sub get_access_controls {
1.745     raeburn  5558:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5559:     my %access;
                   5560:     my $real_file = $file;
                   5561:     $file =~ s/\.meta$//;
1.745     raeburn  5562:     if (defined($file)) {
1.749     raeburn  5563:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5564:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5565:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5566:             }
                   5567:         }
1.745     raeburn  5568:     } else {
1.749     raeburn  5569:         foreach my $key (keys(%{$current_permissions})) {
                   5570:             if ($key =~ /\0accesscontrol$/) {
                   5571:                 if (defined($group)) {
                   5572:                     if ($key !~ m-^\Q$group\E/-) {
                   5573:                         next;
                   5574:                     }
                   5575:                 }
                   5576:                 my ($fullpath) = split(/\0/,$key);
                   5577:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5578:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5579:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5580:                     }
                   5581:                 }
                   5582:             }
                   5583:         }
                   5584:     }
                   5585:     return %access;
                   5586: }
                   5587: 
                   5588: sub modify_access_controls {
                   5589:     my ($file_name,$changes,$domain,$user)=@_;
                   5590:     my ($outcome,$deloutcome);
                   5591:     my %store_permissions;
                   5592:     my %new_values;
                   5593:     my %new_control;
                   5594:     my %translation;
                   5595:     my @deletions = ();
                   5596:     my $now = time;
                   5597:     if (exists($$changes{'activate'})) {
                   5598:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5599:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5600:             my $numnew = scalar(@newitems);
                   5601:             for (my $i=0; $i<$numnew; $i++) {
                   5602:                 my $newkey = $newitems[$i];
                   5603:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5604:                 if ($newkey =~ /^\d+:/) { 
                   5605:                     $newkey =~ s/^(\d+)/$newid/;
                   5606:                     $translation{$1} = $newid;
                   5607:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5608:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5609:                     $translation{$1} = $newid;
                   5610:                 }
1.749     raeburn  5611:                 $new_values{$file_name."\0".$newkey} = 
                   5612:                                           $$changes{'activate'}{$newitems[$i]};
                   5613:                 $new_control{$newkey} = $now;
                   5614:             }
                   5615:         }
                   5616:     }
                   5617:     my %todelete;
                   5618:     my %changed_items;
                   5619:     foreach my $action ('delete','update') {
                   5620:         if (exists($$changes{$action})) {
                   5621:             if (ref($$changes{$action}) eq 'HASH') {
                   5622:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5623:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5624:                     if ($action eq 'delete') { 
                   5625:                         $todelete{$itemnum} = 1;
                   5626:                     } else {
                   5627:                         $changed_items{$itemnum} = $key;
                   5628:                     }
                   5629:                 }
1.745     raeburn  5630:             }
                   5631:         }
1.749     raeburn  5632:     }
                   5633:     # get lock on access controls for file.
                   5634:     my $lockhash = {
                   5635:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5636:                                                        ':'.$env{'user.domain'},
                   5637:                    }; 
                   5638:     my $tries = 0;
                   5639:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5640:    
                   5641:     while (($gotlock ne 'ok') && $tries <3) {
                   5642:         $tries ++;
                   5643:         sleep 1;
                   5644:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5645:     }
                   5646:     if ($gotlock eq 'ok') {
                   5647:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5648:         my ($tmp)=keys(%curr_permissions);
                   5649:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5650:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5651:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5652:             if (ref($curr_controls) eq 'HASH') {
                   5653:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5654:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5655:                     if (defined($todelete{$itemnum})) {
                   5656:                         push(@deletions,$file_name."\0".$control_item);
                   5657:                     } else {
                   5658:                         if (defined($changed_items{$itemnum})) {
                   5659:                             $new_control{$changed_items{$itemnum}} = $now;
                   5660:                             push(@deletions,$file_name."\0".$control_item);
                   5661:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5662:                         } else {
                   5663:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5664:                         }
                   5665:                     }
1.745     raeburn  5666:                 }
                   5667:             }
                   5668:         }
1.749     raeburn  5669:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5670:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5671:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5672:         #  remove lock
                   5673:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5674:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5675:         my ($file,$group);
                   5676:         if (&is_course($domain,$user)) {
                   5677:             ($group,$file) = split(/\//,$file_name,2);
                   5678:         } else {
                   5679:             $file = $file_name;
                   5680:         }
                   5681:         my $sqlresult =
                   5682:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5683:                                     $group);
1.749     raeburn  5684:     } else {
                   5685:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5686:     }
1.749     raeburn  5687:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5688: }
                   5689: 
1.827     raeburn  5690: sub make_public_indefinitely {
                   5691:     my ($requrl) = @_;
                   5692:     my $now = time;
                   5693:     my $action = 'activate';
                   5694:     my $aclnum = 0;
                   5695:     if (&is_portfolio_url($requrl)) {
                   5696:         my (undef,$udom,$unum,$file_name,$group) =
                   5697:             &parse_portfolio_url($requrl);
                   5698:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5699:         my %access_controls = &get_access_controls($current_perms,
                   5700:                                                    $group,$file_name);
                   5701:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5702:             my ($num,$scope,$end,$start) = 
                   5703:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5704:             if ($scope eq 'public') {
                   5705:                 if ($start <= $now && $end == 0) {
                   5706:                     $action = 'none';
                   5707:                 } else {
                   5708:                     $action = 'update';
                   5709:                     $aclnum = $num;
                   5710:                 }
                   5711:                 last;
                   5712:             }
                   5713:         }
                   5714:         if ($action eq 'none') {
                   5715:              return 'ok';
                   5716:         } else {
                   5717:             my %changes;
                   5718:             my $newend = 0;
                   5719:             my $newstart = $now;
                   5720:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5721:             $changes{$action}{$newkey} = {
                   5722:                 type => 'public',
                   5723:                 time => {
                   5724:                     start => $newstart,
                   5725:                     end   => $newend,
                   5726:                 },
                   5727:             };
                   5728:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5729:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5730:             return $outcome;
                   5731:         }
                   5732:     } else {
                   5733:         return 'invalid';
                   5734:     }
                   5735: }
                   5736: 
1.745     raeburn  5737: #------------------------------------------------------Get Marked as Read Only
                   5738: 
                   5739: sub get_marked_as_readonly {
                   5740:     my ($domain,$user,$what,$group) = @_;
                   5741:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5742:     my @readonly_files;
1.629     banghart 5743:     my $cmp1=$what;
                   5744:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5745:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5746:         if (defined($group)) {
                   5747:             if ($file_name !~ m-^\Q$group\E/-) {
                   5748:                 next;
                   5749:             }
                   5750:         }
1.561     banghart 5751:         if (ref($value) eq "ARRAY"){
                   5752:             foreach my $stored_what (@{$value}) {
1.629     banghart 5753:                 my $cmp2=$stored_what;
1.759     albertel 5754:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5755:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5756:                 }
1.629     banghart 5757:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5758:                     push(@readonly_files, $file_name);
1.745     raeburn  5759:                     last;
1.563     banghart 5760:                 } elsif (!defined($what)) {
                   5761:                     push(@readonly_files, $file_name);
1.745     raeburn  5762:                     last;
1.561     banghart 5763:                 }
                   5764:             }
1.745     raeburn  5765:         }
1.561     banghart 5766:     }
                   5767:     return @readonly_files;
                   5768: }
1.577     banghart 5769: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5770: 
1.577     banghart 5771: sub get_marked_as_readonly_hash {
1.745     raeburn  5772:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5773:     my %readonly_files;
1.745     raeburn  5774:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5775:         if (defined($group)) {
                   5776:             if ($file_name !~ m-^\Q$group\E/-) {
                   5777:                 next;
                   5778:             }
                   5779:         }
1.577     banghart 5780:         if (ref($value) eq "ARRAY"){
                   5781:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5782:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5783:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5784:                         if ($lock_descriptor eq 'graded') {
                   5785:                             $readonly_files{$file_name} = 'graded';
                   5786:                         } elsif ($lock_descriptor eq 'handback') {
                   5787:                             $readonly_files{$file_name} = 'handback';
                   5788:                         } else {
                   5789:                             if (!exists($readonly_files{$file_name})) {
                   5790:                                 $readonly_files{$file_name} = 'locked';
                   5791:                             }
                   5792:                         }
1.745     raeburn  5793:                     }
1.750     banghart 5794:                 } 
1.577     banghart 5795:             }
                   5796:         } 
                   5797:     }
                   5798:     return %readonly_files;
                   5799: }
1.559     banghart 5800: # ------------------------------------------------------------ Unmark as Read Only
                   5801: 
                   5802: sub unmark_as_readonly {
1.629     banghart 5803:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5804:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5805:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5806:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5807:     my $symb_crs = $what;
                   5808:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5809:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5810:     my ($tmp)=keys(%current_permissions);
                   5811:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5812:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5813:     foreach my $file (@readonly_files) {
1.759     albertel 5814: 	my $clean_file = &declutter_portfile($file);
                   5815: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5816: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5817:         my @new_locks;
                   5818:         my @del_keys;
                   5819:         if (ref($current_locks) eq "ARRAY"){
                   5820:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5821:                 my $compare=$locker;
1.749     raeburn  5822:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5823:                     $compare=join('',@{$locker});
1.746     raeburn  5824:                     if ($compare ne $symb_crs) {
                   5825:                         push(@new_locks, $locker);
                   5826:                     }
1.563     banghart 5827:                 }
                   5828:             }
1.650     albertel 5829:             if (scalar(@new_locks) > 0) {
1.563     banghart 5830:                 $current_permissions{$file} = \@new_locks;
                   5831:             } else {
                   5832:                 push(@del_keys, $file);
1.613     albertel 5833:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5834:                 delete($current_permissions{$file});
1.563     banghart 5835:             }
                   5836:         }
1.561     banghart 5837:     }
1.613     albertel 5838:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5839:     return;
                   5840: }
1.512     banghart 5841: 
1.17      www      5842: # ------------------------------------------------------------ Directory lister
                   5843: 
                   5844: sub dirlist {
1.253     stredwic 5845:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5846: 
1.18      www      5847:     $uri=~s/^\///;
                   5848:     $uri=~s/\/$//;
1.253     stredwic 5849:     my ($udom, $uname);
                   5850:     (undef,$udom,$uname)=split(/\//,$uri);
                   5851:     if(defined($userdomain)) {
                   5852:         $udom = $userdomain;
                   5853:     }
                   5854:     if(defined($username)) {
                   5855:         $uname = $username;
                   5856:     }
                   5857: 
                   5858:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5859:     if(defined($alternateDirectoryRoot)) {
                   5860:         $dirRoot = $alternateDirectoryRoot;
                   5861:         $dirRoot =~ s/\/$//;
1.751     banghart 5862:     }
1.253     stredwic 5863: 
                   5864:     if($udom) {
                   5865:         if($uname) {
1.800     albertel 5866:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5867: 				 &homeserver($uname,$udom));
1.605     matthew  5868:             my @listing_results;
                   5869:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5870:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5871: 				  &homeserver($uname,$udom));
1.605     matthew  5872:                 @listing_results = split(/:/,$listing);
                   5873:             } else {
                   5874:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5875:             }
                   5876:             return @listing_results;
1.253     stredwic 5877:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5878:             my %allusers;
1.841     albertel 5879: 	    my %servers = &get_servers($udom,'library');
                   5880: 	    foreach my $tryserver (keys(%servers)) {
                   5881: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5882: 				     $udom, $tryserver);
                   5883: 		my @listing_results;
                   5884: 		if ($listing eq 'unknown_cmd') {
                   5885: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5886: 				      $udom, $tryserver);
                   5887: 		    @listing_results = split(/:/,$listing);
                   5888: 		} else {
                   5889: 		    @listing_results =
                   5890: 			map { &unescape($_); } split(/:/,$listing);
                   5891: 		}
                   5892: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5893: 		    $listing_results[0] ne 'empty'       &&
                   5894: 		    $listing_results[0] ne 'con_lost') {
                   5895: 		    foreach my $line (@listing_results) {
                   5896: 			my ($entry) = split(/&/,$line,2);
                   5897: 			$allusers{$entry} = 1;
                   5898: 		    }
                   5899: 		}
1.253     stredwic 5900:             }
                   5901:             my $alluserstr='';
1.800     albertel 5902:             foreach my $user (sort(keys(%allusers))) {
                   5903:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5904:             }
                   5905:             $alluserstr=~s/:$//;
                   5906:             return split(/:/,$alluserstr);
                   5907:         } else {
1.800     albertel 5908:             return ('missing user name');
1.253     stredwic 5909:         }
                   5910:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5911:         my @all_domains = sort(&all_domains());
                   5912:          foreach my $domain (@all_domains) {
                   5913:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5914:          }
                   5915:          return @all_domains;
                   5916:      } else {
1.800     albertel 5917:         return ('missing domain');
1.275     stredwic 5918:     }
                   5919: }
                   5920: 
                   5921: # --------------------------------------------- GetFileTimestamp
                   5922: # This function utilizes dirlist and returns the date stamp for
                   5923: # when it was last modified.  It will also return an error of -1
                   5924: # if an error occurs
                   5925: 
1.410     matthew  5926: ##
                   5927: ## FIXME: This subroutine assumes its caller knows something about the
                   5928: ## directory structure of the home server for the student ($root).
                   5929: ## Not a good assumption to make.  Since this is for looking up files
                   5930: ## in user directories, the full path should be constructed by lond, not
                   5931: ## whatever machine we request data from.
                   5932: ##
1.275     stredwic 5933: sub GetFileTimestamp {
                   5934:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5935:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5936:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5937:     my $subdir=$studentName.'__';
                   5938:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5939:     my $proname="$studentDomain/$subdir/$studentName";
                   5940:     $proname .= '/'.$filename;
1.375     matthew  5941:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5942:                                               $studentName, $root);
1.275     stredwic 5943:     my @stats = split('&', $fileStat);
                   5944:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5945:         # @stats contains first the filename, then the stat output
                   5946:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5947:     } else {
                   5948:         return -1;
1.253     stredwic 5949:     }
1.26      www      5950: }
                   5951: 
1.712     albertel 5952: sub stat_file {
                   5953:     my ($uri) = @_;
1.787     albertel 5954:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5955: 
1.712     albertel 5956:     my ($udom,$uname,$file,$dir);
                   5957:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5958: 	($udom,$uname,$file) =
1.811     albertel 5959: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5960: 	$file = 'userfiles/'.$file;
1.740     www      5961: 	$dir = &propath($udom,$uname);
1.712     albertel 5962:     }
                   5963:     if ($uri =~ m-^/res/-) {
                   5964: 	($udom,$uname) = 
1.807     albertel 5965: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5966: 	$file = $uri;
                   5967:     }
                   5968: 
                   5969:     if (!$udom || !$uname || !$file) {
                   5970: 	# unable to handle the uri
                   5971: 	return ();
                   5972:     }
                   5973: 
                   5974:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5975:     my @stats = split('&', $result);
1.721     banghart 5976:     
1.712     albertel 5977:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5978: 	shift(@stats); #filename is first
                   5979: 	return @stats;
                   5980:     }
                   5981:     return ();
                   5982: }
                   5983: 
1.26      www      5984: # -------------------------------------------------------- Value of a Condition
                   5985: 
1.713     albertel 5986: # gets the value of a specific preevaluated condition
                   5987: #    stored in the string  $env{user.state.<cid>}
                   5988: # or looks up a condition reference in the bighash and if if hasn't
                   5989: # already been evaluated recurses into docondval to get the value of
                   5990: # the condition, then memoizing it to 
                   5991: #   $env{user.state.<cid>.<condition>}
1.40      www      5992: sub directcondval {
                   5993:     my $number=shift;
1.620     albertel 5994:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5995: 	&Apache::lonuserstate::evalstate();
                   5996:     }
1.713     albertel 5997:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5998: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5999:     } elsif ($number =~ /^_/) {
                   6000: 	my $sub_condition;
                   6001: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6002: 		&GDBM_READER(),0640)) {
                   6003: 	    $sub_condition=$bighash{'conditions'.$number};
                   6004: 	    untie(%bighash);
                   6005: 	}
                   6006: 	my $value = &docondval($sub_condition);
                   6007: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6008: 	return $value;
                   6009:     }
1.620     albertel 6010:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6011:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6012:     } else {
                   6013:        return 2;
                   6014:     }
                   6015: }
                   6016: 
1.713     albertel 6017: # get the collection of conditions for this resource
1.26      www      6018: sub condval {
                   6019:     my $condidx=shift;
1.54      www      6020:     my $allpathcond='';
1.713     albertel 6021:     foreach my $cond (split(/\|/,$condidx)) {
                   6022: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6023: 	    $allpathcond.=
                   6024: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6025: 	}
1.191     harris41 6026:     }
1.54      www      6027:     $allpathcond=~s/\|$//;
1.713     albertel 6028:     return &docondval($allpathcond);
                   6029: }
                   6030: 
                   6031: #evaluates an expression of conditions
                   6032: sub docondval {
                   6033:     my ($allpathcond) = @_;
                   6034:     my $result=0;
                   6035:     if ($env{'request.course.id'}
                   6036: 	&& defined($allpathcond)) {
                   6037: 	my $operand='|';
                   6038: 	my @stack;
                   6039: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6040: 	    if ($chunk eq '(') {
                   6041: 		push @stack,($operand,$result);
                   6042: 	    } elsif ($chunk eq ')') {
                   6043: 		my $before=pop @stack;
                   6044: 		if (pop @stack eq '&') {
                   6045: 		    $result=$result>$before?$before:$result;
                   6046: 		} else {
                   6047: 		    $result=$result>$before?$result:$before;
                   6048: 		}
                   6049: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6050: 		$operand=$chunk;
                   6051: 	    } else {
                   6052: 		my $new=directcondval($chunk);
                   6053: 		if ($operand eq '&') {
                   6054: 		    $result=$result>$new?$new:$result;
                   6055: 		} else {
                   6056: 		    $result=$result>$new?$result:$new;
                   6057: 		}
                   6058: 	    }
                   6059: 	}
1.26      www      6060:     }
                   6061:     return $result;
1.421     albertel 6062: }
                   6063: 
                   6064: # ---------------------------------------------------- Devalidate courseresdata
                   6065: 
                   6066: sub devalidatecourseresdata {
                   6067:     my ($coursenum,$coursedomain)=@_;
                   6068:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6069:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6070: }
                   6071: 
1.763     www      6072: 
1.200     www      6073: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6074: #
                   6075: #  Parameters:
                   6076: #      $coursenum    - Number of the course.
                   6077: #      $coursedomain - Domain at which the course was created.
                   6078: #  Returns:
                   6079: #     A hash of the course parameters along (I think) with timestamps
                   6080: #     and version info.
1.877     foxr     6081: 
1.624     albertel 6082: sub get_courseresdata {
                   6083:     my ($coursenum,$coursedomain)=@_;
1.200     www      6084:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6085:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6086:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6087:     my %dumpreply;
1.417     albertel 6088:     unless (defined($cached)) {
1.624     albertel 6089: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6090: 	$result=\%dumpreply;
1.251     albertel 6091: 	my ($tmp) = keys(%dumpreply);
                   6092: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6093: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6094: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6095: 	    return $tmp;
1.416     albertel 6096: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6097: 	    $result=undef;
1.599     albertel 6098: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6099: 	}
                   6100:     }
1.624     albertel 6101:     return $result;
                   6102: }
                   6103: 
1.633     albertel 6104: sub devalidateuserresdata {
                   6105:     my ($uname,$udom)=@_;
                   6106:     my $hashid="$udom:$uname";
                   6107:     &devalidate_cache_new('userres',$hashid);
                   6108: }
                   6109: 
1.624     albertel 6110: sub get_userresdata {
                   6111:     my ($uname,$udom)=@_;
                   6112:     #most student don\'t have any data set, check if there is some data
                   6113:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6114: 
                   6115:     my $hashid="$udom:$uname";
                   6116:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6117:     if (!defined($cached)) {
                   6118: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6119: 	$result=\%resourcedata;
                   6120: 	&do_cache_new('userres',$hashid,$result,600);
                   6121:     }
                   6122:     my ($tmp)=keys(%$result);
                   6123:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6124: 	return $result;
                   6125:     }
                   6126:     #error 2 occurs when the .db doesn't exist
                   6127:     if ($tmp!~/error: 2 /) {
1.672     albertel 6128: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6129: 		 " Trying to get resource data for ".
                   6130: 		 $uname." at ".$udom.": ".
                   6131: 		 $tmp."</font>");
                   6132:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6133: 	#&EXT_cache_set($udom,$uname);
                   6134: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6135: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6136:     }
                   6137:     return $tmp;
                   6138: }
1.879     foxr     6139: #----------------------------------------------- resdata - return resource data
                   6140: #  Purpose:
                   6141: #    Return resource data for either users or for a course.
                   6142: #  Parameters:
                   6143: #     $name      - Course/user name.
                   6144: #     $domain    - Name of the domain the user/course is registered on.
                   6145: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6146: #     @which     - Array of names of resources desired.
                   6147: #  Returns:
                   6148: #     The value of the first reasource in @which that is found in the
                   6149: #     resource hash.
                   6150: #  Exceptional Conditions:
                   6151: #     If the $type passed in is not valid (not the string 'course' or 
                   6152: #     'user', an undefined  reference is returned.
                   6153: #     If none of the resources are found, an undef is returned
1.624     albertel 6154: sub resdata {
                   6155:     my ($name,$domain,$type,@which)=@_;
                   6156:     my $result;
                   6157:     if ($type eq 'course') {
                   6158: 	$result=&get_courseresdata($name,$domain);
                   6159:     } elsif ($type eq 'user') {
                   6160: 	$result=&get_userresdata($name,$domain);
                   6161:     }
                   6162:     if (!ref($result)) { return $result; }    
1.251     albertel 6163:     foreach my $item (@which) {
1.417     albertel 6164: 	if (defined($result->{$item})) {
                   6165: 	    return $result->{$item};
1.251     albertel 6166: 	}
1.250     albertel 6167:     }
1.291     albertel 6168:     return undef;
1.200     www      6169: }
                   6170: 
1.379     matthew  6171: #
                   6172: # EXT resource caching routines
                   6173: #
                   6174: 
                   6175: sub clear_EXT_cache_status {
1.383     albertel 6176:     &delenv('cache.EXT.');
1.379     matthew  6177: }
                   6178: 
                   6179: sub EXT_cache_status {
                   6180:     my ($target_domain,$target_user) = @_;
1.383     albertel 6181:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6182:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6183:         # We know already the user has no data
                   6184:         return 1;
                   6185:     } else {
                   6186:         return 0;
                   6187:     }
                   6188: }
                   6189: 
                   6190: sub EXT_cache_set {
                   6191:     my ($target_domain,$target_user) = @_;
1.383     albertel 6192:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6193:     #&appenv($cachename => time);
1.379     matthew  6194: }
                   6195: 
1.28      www      6196: # --------------------------------------------------------- Value of a Variable
1.58      www      6197: sub EXT {
1.715     albertel 6198: 
1.395     albertel 6199:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6200:     unless ($varname) { return ''; }
1.218     albertel 6201:     #get real user name/domain, courseid and symb
                   6202:     my $courseid;
1.359     albertel 6203:     my $publicuser;
1.427     www      6204:     if ($symbparm) {
                   6205: 	$symbparm=&get_symb_from_alias($symbparm);
                   6206:     }
1.218     albertel 6207:     if (!($uname && $udom)) {
1.790     albertel 6208:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6209:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6210:     } else {
1.620     albertel 6211: 	$courseid=$env{'request.course.id'};
1.218     albertel 6212:     }
1.48      www      6213:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6214:     my $rest;
1.320     albertel 6215:     if (defined($therest[0])) {
1.48      www      6216:        $rest=join('.',@therest);
                   6217:     } else {
                   6218:        $rest='';
                   6219:     }
1.320     albertel 6220: 
1.57      www      6221:     my $qualifierrest=$qualifier;
                   6222:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6223:     my $spacequalifierrest=$space;
                   6224:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6225:     if ($realm eq 'user') {
1.48      www      6226: # --------------------------------------------------------------- user.resource
                   6227: 	if ($space eq 'resource') {
1.651     albertel 6228: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6229: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6230: 		 &&
1.744     albertel 6231: 		 ($symbparm eq &symbread()) ) {	
                   6232: 		# if we are in the middle of processing the resource the
                   6233: 		# get the value we are planning on committing
                   6234:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6235:                     return $Apache::lonhomework::results{$qualifierrest};
                   6236:                 } else {
                   6237:                     return $Apache::lonhomework::history{$qualifierrest};
                   6238:                 }
1.335     albertel 6239: 	    } else {
1.359     albertel 6240: 		my %restored;
1.620     albertel 6241: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6242: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6243: 		} else {
                   6244: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6245: 		}
1.335     albertel 6246: 		return $restored{$qualifierrest};
                   6247: 	    }
1.48      www      6248: # ----------------------------------------------------------------- user.access
                   6249:         } elsif ($space eq 'access') {
1.218     albertel 6250: 	    # FIXME - not supporting calls for a specific user
1.48      www      6251:             return &allowed($qualifier,$rest);
                   6252: # ------------------------------------------ user.preferences, user.environment
                   6253:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6254: 	    if (($uname eq $env{'user.name'}) &&
                   6255: 		($udom eq $env{'user.domain'})) {
                   6256: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6257: 	    } else {
1.359     albertel 6258: 		my %returnhash;
                   6259: 		if (!$publicuser) {
                   6260: 		    %returnhash=&userenvironment($udom,$uname,
                   6261: 						 $qualifierrest);
                   6262: 		}
1.218     albertel 6263: 		return $returnhash{$qualifierrest};
                   6264: 	    }
1.48      www      6265: # ----------------------------------------------------------------- user.course
                   6266:         } elsif ($space eq 'course') {
1.218     albertel 6267: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6268:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6269: # ------------------------------------------------------------------- user.role
                   6270:         } elsif ($space eq 'role') {
1.218     albertel 6271: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6272:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6273:             if ($qualifier eq 'value') {
                   6274: 		return $role;
                   6275:             } elsif ($qualifier eq 'extent') {
                   6276:                 return $where;
                   6277:             }
                   6278: # ----------------------------------------------------------------- user.domain
                   6279:         } elsif ($space eq 'domain') {
1.218     albertel 6280:             return $udom;
1.48      www      6281: # ------------------------------------------------------------------- user.name
                   6282:         } elsif ($space eq 'name') {
1.218     albertel 6283:             return $uname;
1.48      www      6284: # ---------------------------------------------------- Any other user namespace
1.29      www      6285:         } else {
1.359     albertel 6286: 	    my %reply;
                   6287: 	    if (!$publicuser) {
                   6288: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6289: 	    }
                   6290: 	    return $reply{$qualifierrest};
1.48      www      6291:         }
1.236     www      6292:     } elsif ($realm eq 'query') {
                   6293: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6294:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6295: 						[$spacequalifierrest]);
1.620     albertel 6296: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6297:    } elsif ($realm eq 'request') {
1.48      www      6298: # ------------------------------------------------------------- request.browser
                   6299:         if ($space eq 'browser') {
1.430     www      6300: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6301: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6302: 		    return 1;
                   6303: 		} else {
                   6304: 		    return 0;
                   6305: 		}
                   6306: 	    } else {
1.620     albertel 6307: 		return $env{'browser.'.$qualifier};
1.430     www      6308: 	    }
1.57      www      6309: # ------------------------------------------------------------ request.filename
                   6310:         } else {
1.620     albertel 6311:             return $env{'request.'.$spacequalifierrest};
1.29      www      6312:         }
1.28      www      6313:     } elsif ($realm eq 'course') {
1.48      www      6314: # ---------------------------------------------------------- course.description
1.620     albertel 6315:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6316:     } elsif ($realm eq 'resource') {
1.165     www      6317: 
1.620     albertel 6318: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6319: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6320: 	}
1.693     albertel 6321: 
                   6322: 	if ($space eq 'title') {
                   6323: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6324: 	    return &gettitle($symbparm);
                   6325: 	}
                   6326: 	
                   6327: 	if ($space eq 'map') {
                   6328: 	    my ($map) = &decode_symb($symbparm);
                   6329: 	    return &symbread($map);
                   6330: 	}
1.905     albertel 6331: 	if ($space eq 'filename') {
                   6332: 	    if ($symbparm) {
                   6333: 		return &clutter((&decode_symb($symbparm))[2]);
                   6334: 	    }
                   6335: 	    return &hreflocation('',$env{'request.filename'});
                   6336: 	}
1.693     albertel 6337: 
                   6338: 	my ($section, $group, @groups);
1.593     albertel 6339: 	my ($courselevelm,$courselevel);
1.539     albertel 6340: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6341: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6342: 
1.218     albertel 6343: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6344: 
1.60      www      6345: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6346: 	    my $symbp=$symbparm;
1.735     albertel 6347: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6348: 
                   6349: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6350: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6351: 
1.620     albertel 6352: 	    if (($env{'user.name'} eq $uname) &&
                   6353: 		($env{'user.domain'} eq $udom)) {
                   6354: 		$section=$env{'request.course.sec'};
1.733     raeburn  6355:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6356:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6357: 	    } else {
1.539     albertel 6358: 		if (! defined($usection)) {
1.551     albertel 6359: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6360: 		} else {
                   6361: 		    $section = $usection;
                   6362: 		}
1.733     raeburn  6363:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6364: 	    }
                   6365: 
                   6366: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6367: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6368: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6369: 
1.593     albertel 6370: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6371: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6372: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6373: 
1.60      www      6374: # ----------------------------------------------------------- first, check user
1.624     albertel 6375: 
                   6376: 	    my $userreply=&resdata($uname,$udom,'user',
                   6377: 				       ($courselevelr,$courselevelm,
                   6378: 					$courselevel));
                   6379: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6380: 
1.594     albertel 6381: # ------------------------------------------------ second, check some of course
1.684     raeburn  6382:             my $coursereply;
1.691     raeburn  6383:             if (@groups > 0) {
                   6384:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6385:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6386:                 if (defined($coursereply)) { return $coursereply; }
                   6387:             }
1.96      www      6388: 
1.684     raeburn  6389: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6390: 				     $env{'course.'.$courseid.'.domain'},
                   6391: 				     'course',
                   6392: 				     ($seclevelr,$seclevelm,$seclevel,
                   6393: 				      $courselevelr));
1.287     albertel 6394: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6395: 
1.60      www      6396: # ------------------------------------------------------ third, check map parms
1.218     albertel 6397: 	    my %parmhash=();
                   6398: 	    my $thisparm='';
                   6399: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6400: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6401: 		    &GDBM_READER(),0640)) {
1.218     albertel 6402: 		$thisparm=$parmhash{$symbparm};
                   6403: 		untie(%parmhash);
                   6404: 	    }
                   6405: 	    if ($thisparm) { return $thisparm; }
                   6406: 	}
1.594     albertel 6407: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6408: 
1.218     albertel 6409: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6410: 	my $filename;
                   6411: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6412: 	if ($symbparm) {
1.409     www      6413: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6414: 	} else {
1.620     albertel 6415: 	    $filename=$env{'request.filename'};
1.282     albertel 6416: 	}
                   6417: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6418: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6419: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6420: 	if (defined($metadata)) { return $metadata; }
1.142     www      6421: 
1.594     albertel 6422: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6423: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6424: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6425: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6426: 				     $env{'course.'.$courseid.'.domain'},
                   6427: 				     'course',
                   6428: 				     ($courselevelm,$courselevel));
1.593     albertel 6429: 	    if (defined($coursereply)) { return $coursereply; }
                   6430: 	}
1.145     www      6431: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6432: 	unless ($space eq '0') {
1.336     albertel 6433: 	    my @parts=split(/_/,$space);
                   6434: 	    my $id=pop(@parts);
                   6435: 	    my $part=join('_',@parts);
                   6436: 	    if ($part eq '') { $part='0'; }
                   6437: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6438: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6439: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6440: 	}
1.395     albertel 6441: 	if ($recurse) { return undef; }
                   6442: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6443: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6444: 
1.48      www      6445: # ---------------------------------------------------- Any other user namespace
                   6446:     } elsif ($realm eq 'environment') {
                   6447: # ----------------------------------------------------------------- environment
1.620     albertel 6448: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6449: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6450: 	} else {
1.770     albertel 6451: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6452: 		return '';
                   6453: 	    }
1.219     albertel 6454: 	    my %returnhash=&userenvironment($udom,$uname,
                   6455: 					    $spacequalifierrest);
                   6456: 	    return $returnhash{$spacequalifierrest};
                   6457: 	}
1.28      www      6458:     } elsif ($realm eq 'system') {
1.48      www      6459: # ----------------------------------------------------------------- system.time
                   6460: 	if ($space eq 'time') {
                   6461: 	    return time;
                   6462:         }
1.696     albertel 6463:     } elsif ($realm eq 'server') {
                   6464: # ----------------------------------------------------------------- system.time
                   6465: 	if ($space eq 'name') {
                   6466: 	    return $ENV{'SERVER_NAME'};
                   6467:         }
1.28      www      6468:     }
1.48      www      6469:     return '';
1.61      www      6470: }
                   6471: 
1.691     raeburn  6472: sub check_group_parms {
                   6473:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6474:     my @groupitems = ();
                   6475:     my $resultitem;
                   6476:     my @levels = ($symbparm,$mapparm,$what);
                   6477:     foreach my $group (@{$groups}) {
                   6478:         foreach my $level (@levels) {
                   6479:              my $item = $courseid.'.['.$group.'].'.$level;
                   6480:              push(@groupitems,$item);
                   6481:         }
                   6482:     }
                   6483:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6484:                             $env{'course.'.$courseid.'.domain'},
                   6485:                                      'course',@groupitems);
                   6486:     return $coursereply;
                   6487: }
                   6488: 
                   6489: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6490:     my ($courseid,@groups) = @_;
                   6491:     @groups = sort(@groups);
1.691     raeburn  6492:     return @groups;
                   6493: }
                   6494: 
1.395     albertel 6495: sub packages_tab_default {
                   6496:     my ($uri,$varname)=@_;
                   6497:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6498: 
                   6499:     my (@extension,@specifics,$do_default);
                   6500:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6501: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6502: 	if ($pack_type eq 'default') {
                   6503: 	    $do_default=1;
                   6504: 	} elsif ($pack_type eq 'extension') {
                   6505: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6506: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6507: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6508: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6509: 	}
                   6510:     }
                   6511:     # first look for a package that matches the requested part id
                   6512:     foreach my $package (@specifics) {
                   6513: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6514: 	next if ($pack_part ne $part);
                   6515: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6516: 	    return $packagetab{"$pack_type&$name&default"};
                   6517: 	}
                   6518:     }
                   6519:     # look for any possible matching non extension_ package
                   6520:     foreach my $package (@specifics) {
                   6521: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6522: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6523: 	    return $packagetab{"$pack_type&$name&default"};
                   6524: 	}
1.585     albertel 6525: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6526: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6527: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6528: 	}
                   6529:     }
1.738     albertel 6530:     # look for any posible extension_ match
                   6531:     foreach my $package (@extension) {
                   6532: 	my ($package,$pack_type)=@{$package};
                   6533: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6534: 	    return $packagetab{"$pack_type&$name&default"};
                   6535: 	}
                   6536: 	if (defined($packagetab{$package."&$name&default"})) {
                   6537: 	    return $packagetab{$package."&$name&default"};
                   6538: 	}
                   6539:     }
                   6540:     # look for a global default setting
                   6541:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6542: 	return $packagetab{"default&$name&default"};
                   6543:     }
1.395     albertel 6544:     return undef;
                   6545: }
                   6546: 
1.334     albertel 6547: sub add_prefix_and_part {
                   6548:     my ($prefix,$part)=@_;
                   6549:     my $keyroot;
                   6550:     if (defined($prefix) && $prefix !~ /^__/) {
                   6551: 	# prefix that has a part already
                   6552: 	$keyroot=$prefix;
                   6553:     } elsif (defined($prefix)) {
                   6554: 	# prefix that is missing a part
                   6555: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6556:     } else {
                   6557: 	# no prefix at all
                   6558: 	if (defined($part)) { $keyroot='_'.$part; }
                   6559:     }
                   6560:     return $keyroot;
                   6561: }
                   6562: 
1.71      www      6563: # ---------------------------------------------------------------- Get metadata
                   6564: 
1.599     albertel 6565: my %metaentry;
1.71      www      6566: sub metadata {
1.176     www      6567:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6568:     $uri=&declutter($uri);
1.288     albertel 6569:     # if it is a non metadata possible uri return quickly
1.529     albertel 6570:     if (($uri eq '') || 
                   6571: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6572: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6573:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6574: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6575: 	return undef;
1.288     albertel 6576:     }
1.73      www      6577:     my $filename=$uri;
                   6578:     $uri=~s/\.meta$//;
1.172     www      6579: #
                   6580: # Is the metadata already cached?
1.177     www      6581: # Look at timestamp of caching
1.172     www      6582: # Everything is cached by the main uri, libraries are never directly cached
                   6583: #
1.428     albertel 6584:     if (!defined($liburi)) {
1.599     albertel 6585: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6586: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6587:     }
                   6588:     {
1.172     www      6589: #
                   6590: # Is this a recursive call for a library?
                   6591: #
1.599     albertel 6592: #	if (! exists($metacache{$uri})) {
                   6593: #	    $metacache{$uri}={};
                   6594: #	}
1.171     www      6595:         if ($liburi) {
                   6596: 	    $liburi=&declutter($liburi);
                   6597:             $filename=$liburi;
1.401     bowersj2 6598:         } else {
1.599     albertel 6599: 	    &devalidate_cache_new('meta',$uri);
                   6600: 	    undef(%metaentry);
1.401     bowersj2 6601: 	}
1.140     www      6602:         my %metathesekeys=();
1.73      www      6603:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6604: 	my $metastring;
1.768     albertel 6605: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6606: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6607: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6608: 	    $metastring=&getfile($file);
1.489     albertel 6609: 	}
1.208     albertel 6610:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6611:         my $token;
1.140     www      6612:         undef %metathesekeys;
1.71      www      6613:         while ($token=$parser->get_token) {
1.339     albertel 6614: 	    if ($token->[0] eq 'S') {
                   6615: 		if (defined($token->[2]->{'package'})) {
1.172     www      6616: #
                   6617: # This is a package - get package info
                   6618: #
1.339     albertel 6619: 		    my $package=$token->[2]->{'package'};
                   6620: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6621: 		    if (defined($token->[2]->{'id'})) { 
                   6622: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6623: 		    }
1.599     albertel 6624: 		    if ($metaentry{':packages'}) {
                   6625: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6626: 		    } else {
1.599     albertel 6627: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6628: 		    }
1.736     albertel 6629: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6630: 			my $part=$keyroot;
                   6631: 			$part=~s/^\_//;
1.736     albertel 6632: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6633: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6634: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6635: 			    # ignore package.tab specified default values
                   6636:                             # here &package_tab_default() will fetch those
                   6637: 			    if ($subp eq 'default') { next; }
1.736     albertel 6638: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6639: 			    my $unikey;
                   6640: 			    if ($pack =~ /_0$/) {
                   6641: 				$unikey='parameter_0_'.$name;
                   6642: 				$part=0;
                   6643: 			    } else {
                   6644: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6645: 			    }
1.339     albertel 6646: 			    if ($subp eq 'display') {
                   6647: 				$value.=' [Part: '.$part.']';
                   6648: 			    }
1.599     albertel 6649: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6650: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6651: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6652: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6653: 			    }
1.599     albertel 6654: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6655: 				$metaentry{':'.$unikey}=
                   6656: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6657: 			    }
1.339     albertel 6658: 			}
                   6659: 		    }
                   6660: 		} else {
1.172     www      6661: #
                   6662: # This is not a package - some other kind of start tag
1.339     albertel 6663: #
                   6664: 		    my $entry=$token->[1];
                   6665: 		    my $unikey;
                   6666: 		    if ($entry eq 'import') {
                   6667: 			$unikey='';
                   6668: 		    } else {
                   6669: 			$unikey=$entry;
                   6670: 		    }
                   6671: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6672: 
                   6673: 		    if (defined($token->[2]->{'id'})) { 
                   6674: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6675: 		    }
1.175     www      6676: 
1.339     albertel 6677: 		    if ($entry eq 'import') {
1.175     www      6678: #
                   6679: # Importing a library here
1.339     albertel 6680: #
                   6681: 			if ($depthcount<20) {
                   6682: 			    my $location=$parser->get_text('/import');
                   6683: 			    my $dir=$filename;
                   6684: 			    $dir=~s|[^/]*$||;
                   6685: 			    $location=&filelocation($dir,$location);
1.736     albertel 6686: 			    my $metadata = 
                   6687: 				&metadata($uri,'keys', $location,$unikey,
                   6688: 					  $depthcount+1);
                   6689: 			    foreach my $meta (split(',',$metadata)) {
                   6690: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6691: 				$metathesekeys{$meta}=1;
1.339     albertel 6692: 			    }
                   6693: 			}
                   6694: 		    } else { 
                   6695: 			
                   6696: 			if (defined($token->[2]->{'name'})) { 
                   6697: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6698: 			}
                   6699: 			$metathesekeys{$unikey}=1;
1.736     albertel 6700: 			foreach my $param (@{$token->[3]}) {
                   6701: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6702: 				$token->[2]->{$param};
1.339     albertel 6703: 			}
                   6704: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6705: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6706: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6707: 		 # only ws inside the tag, and not in default, so use default
                   6708: 		 # as value
1.599     albertel 6709: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6710: 			} elsif ( $internaltext =~ /\S/ ) {
                   6711: 		  # something interesting inside the tag
                   6712: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6713: 			} else {
1.908     albertel 6714: 		  # no interesting values, don't set a default
1.339     albertel 6715: 			}
1.172     www      6716: # end of not-a-package not-a-library import
1.339     albertel 6717: 		    }
1.172     www      6718: # end of not-a-package start tag
1.339     albertel 6719: 		}
1.172     www      6720: # the next is the end of "start tag"
1.339     albertel 6721: 	    }
                   6722: 	}
1.483     albertel 6723: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6724: 	$extension = lc($extension);
                   6725: 	if ($extension eq 'htm') { $extension='html'; }
                   6726: 
1.737     albertel 6727: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6728: 	    #no specific packages #how's our extension
                   6729: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6730: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6731: 					 \%metathesekeys);
                   6732: 	}
1.883     albertel 6733: 
                   6734: 	if (!exists($metaentry{':packages'})
                   6735: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6736: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6737: 		#no specific packages well let's get default then
                   6738: 		if ($key!~/^default&/) { next; }
1.488     albertel 6739: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6740: 					     \%metathesekeys);
                   6741: 	    }
                   6742: 	}
1.338     www      6743: # are there custom rights to evaluate
1.599     albertel 6744: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6745: 
1.338     www      6746:     #
                   6747:     # Importing a rights file here
1.339     albertel 6748:     #
                   6749: 	    unless ($depthcount) {
1.599     albertel 6750: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6751: 		my $dir=$filename;
                   6752: 		$dir=~s|[^/]*$||;
                   6753: 		$location=&filelocation($dir,$location);
1.736     albertel 6754: 		my $rights_metadata =
                   6755: 		    &metadata($uri,'keys',$location,'_rights',
                   6756: 			      $depthcount+1);
                   6757: 		foreach my $rights (split(',',$rights_metadata)) {
                   6758: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6759: 		    $metathesekeys{$rights}=1;
1.339     albertel 6760: 		}
                   6761: 	    }
                   6762: 	}
1.737     albertel 6763: 	# uniqifiy package listing
                   6764: 	my %seen;
                   6765: 	my @uniq_packages =
                   6766: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6767: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6768: 
                   6769: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6770: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6771: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6772: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6773: # this is the end of "was not already recently cached
1.71      www      6774:     }
1.599     albertel 6775:     return $metaentry{':'.$what};
1.261     albertel 6776: }
                   6777: 
1.488     albertel 6778: sub metadata_create_package_def {
1.483     albertel 6779:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6780:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6781:     if ($subp eq 'default') { next; }
                   6782:     
1.599     albertel 6783:     if (defined($metaentry{':packages'})) {
                   6784: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6785:     } else {
1.599     albertel 6786: 	$metaentry{':packages'}=$package;
1.483     albertel 6787:     }
                   6788:     my $value=$packagetab{$key};
                   6789:     my $unikey;
                   6790:     $unikey='parameter_0_'.$name;
1.599     albertel 6791:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6792:     $$metathesekeys{$unikey}=1;
1.599     albertel 6793:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6794: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6795:     }
1.599     albertel 6796:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6797: 	$metaentry{':'.$unikey}=
                   6798: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6799:     }
                   6800: }
                   6801: 
1.261     albertel 6802: sub metadata_generate_part0 {
                   6803:     my ($metadata,$metacache,$uri) = @_;
                   6804:     my %allnames;
1.737     albertel 6805:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6806: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6807: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6808: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6809: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6810: 	    $allnames{$name}=$part;
                   6811: 	  }
                   6812: 	}
                   6813:     }
                   6814:     foreach my $name (keys(%allnames)) {
                   6815:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6816:       my $key=":parameter_0_$name";
1.261     albertel 6817:       $$metacache{"$key.part"}='0';
                   6818:       $$metacache{"$key.name"}=$name;
1.428     albertel 6819:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6820: 					   $allnames{$name}.'_'.$name.
                   6821: 					   '.type'};
1.428     albertel 6822:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6823: 			     '.display'};
1.644     www      6824:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6825:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6826:       $$metacache{"$key.display"}=$olddis;
                   6827:     }
1.71      www      6828: }
                   6829: 
1.764     albertel 6830: # ------------------------------------------------------ Devalidate title cache
                   6831: 
                   6832: sub devalidate_title_cache {
                   6833:     my ($url)=@_;
                   6834:     if (!$env{'request.course.id'}) { return; }
                   6835:     my $symb=&symbread($url);
                   6836:     if (!$symb) { return; }
                   6837:     my $key=$env{'request.course.id'}."\0".$symb;
                   6838:     &devalidate_cache_new('title',$key);
                   6839: }
                   6840: 
1.301     www      6841: # ------------------------------------------------- Get the title of a resource
                   6842: 
                   6843: sub gettitle {
                   6844:     my $urlsymb=shift;
                   6845:     my $symb=&symbread($urlsymb);
1.534     albertel 6846:     if ($symb) {
1.620     albertel 6847: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6848: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6849: 	if (defined($cached)) { 
                   6850: 	    return $result;
                   6851: 	}
1.534     albertel 6852: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6853: 	my $title='';
1.907     albertel 6854: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   6855: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   6856: 	} else {
                   6857: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6858: 		    &GDBM_READER(),0640)) {
                   6859: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6860: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   6861: 		untie(%bighash);
                   6862: 	    }
1.534     albertel 6863: 	}
                   6864: 	$title=~s/\&colon\;/\:/gs;
                   6865: 	if ($title) {
1.599     albertel 6866: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6867: 	}
                   6868: 	$urlsymb=$url;
                   6869:     }
                   6870:     my $title=&metadata($urlsymb,'title');
                   6871:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6872:     return $title;
1.301     www      6873: }
1.613     albertel 6874: 
1.614     albertel 6875: sub get_slot {
                   6876:     my ($which,$cnum,$cdom)=@_;
                   6877:     if (!$cnum || !$cdom) {
1.790     albertel 6878: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6879: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6880: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6881:     }
1.703     albertel 6882:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6883:     my %slotinfo;
                   6884:     if (exists($remembered{$key})) {
                   6885: 	$slotinfo{$which} = $remembered{$key};
                   6886:     } else {
                   6887: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6888: 	&Apache::lonhomework::showhash(%slotinfo);
                   6889: 	my ($tmp)=keys(%slotinfo);
                   6890: 	if ($tmp=~/^error:/) { return (); }
                   6891: 	$remembered{$key} = $slotinfo{$which};
                   6892:     }
1.616     albertel 6893:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6894: 	return %{$slotinfo{$which}};
                   6895:     }
                   6896:     return $slotinfo{$which};
1.614     albertel 6897: }
1.31      www      6898: # ------------------------------------------------- Update symbolic store links
                   6899: 
                   6900: sub symblist {
                   6901:     my ($mapname,%newhash)=@_;
1.438     www      6902:     $mapname=&deversion(&declutter($mapname));
1.31      www      6903:     my %hash;
1.620     albertel 6904:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6905:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6906:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6907: 	    foreach my $url (keys %newhash) {
                   6908: 		next if ($url eq 'last_known'
                   6909: 			 && $env{'form.no_update_last_known'});
                   6910: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6911: 						    $newhash{$url}->[1],
                   6912: 						    $newhash{$url}->[0]);
1.191     harris41 6913:             }
1.31      www      6914:             if (untie(%hash)) {
                   6915: 		return 'ok';
                   6916:             }
                   6917:         }
                   6918:     }
                   6919:     return 'error';
1.212     www      6920: }
                   6921: 
                   6922: # --------------------------------------------------------------- Verify a symb
                   6923: 
                   6924: sub symbverify {
1.510     www      6925:     my ($symb,$thisurl)=@_;
                   6926:     my $thisfn=$thisurl;
1.439     www      6927:     $thisfn=&declutter($thisfn);
1.215     www      6928: # direct jump to resource in page or to a sequence - will construct own symbs
                   6929:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6930: # check URL part
1.409     www      6931:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6932: 
1.431     www      6933:     unless ($url eq $thisfn) { return 0; }
1.213     www      6934: 
1.216     www      6935:     $symb=&symbclean($symb);
1.510     www      6936:     $thisurl=&deversion($thisurl);
1.439     www      6937:     $thisfn=&deversion($thisfn);
1.213     www      6938: 
                   6939:     my %bighash;
                   6940:     my $okay=0;
1.431     www      6941: 
1.620     albertel 6942:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6943:                             &GDBM_READER(),0640)) {
1.510     www      6944:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6945:         unless ($ids) { 
1.510     www      6946:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6947:         }
                   6948:         if ($ids) {
                   6949: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6950: 	    foreach my $id (split(/\,/,$ids)) {
                   6951: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6952:                if (
                   6953:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6954:    eq $symb) { 
1.620     albertel 6955: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6956: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6957: 		       $okay=1; 
                   6958: 		   }
                   6959: 	       }
1.216     www      6960: 	   }
                   6961:         }
1.213     www      6962: 	untie(%bighash);
                   6963:     }
                   6964:     return $okay;
1.31      www      6965: }
                   6966: 
1.210     www      6967: # --------------------------------------------------------------- Clean-up symb
                   6968: 
                   6969: sub symbclean {
                   6970:     my $symb=shift;
1.568     albertel 6971:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6972: # remove version from map
                   6973:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6974: 
1.210     www      6975: # remove version from URL
                   6976:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6977: 
1.507     www      6978: # remove wrapper
                   6979: 
1.510     www      6980:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6981:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6982:     return $symb;
1.409     www      6983: }
                   6984: 
                   6985: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6986: 
                   6987: sub encode_symb {
                   6988:     my ($map,$resid,$url)=@_;
                   6989:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6990: }
1.409     www      6991: 
                   6992: sub decode_symb {
1.568     albertel 6993:     my $symb=shift;
                   6994:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6995:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6996:     return (&fixversion($map),$resid,&fixversion($url));
                   6997: }
                   6998: 
                   6999: sub fixversion {
                   7000:     my $fn=shift;
1.609     banghart 7001:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7002:     my %bighash;
                   7003:     my $uri=&clutter($fn);
1.620     albertel 7004:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7005: # is this cached?
1.599     albertel 7006:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7007:     if (defined($cached)) { return $result; }
                   7008: # unfortunately not cached, or expired
1.620     albertel 7009:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7010: 	    &GDBM_READER(),0640)) {
                   7011:  	if ($bighash{'version_'.$uri}) {
                   7012:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7013:  	    unless (($version eq 'mostrecent') || 
                   7014: 		    ($version==&getversion($uri))) {
1.440     www      7015:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7016:  	    }
                   7017:  	}
                   7018:  	untie %bighash;
1.413     www      7019:     }
1.599     albertel 7020:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7021: }
                   7022: 
                   7023: sub deversion {
                   7024:     my $url=shift;
                   7025:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7026:     return $url;
1.210     www      7027: }
                   7028: 
1.31      www      7029: # ------------------------------------------------------ Return symb list entry
                   7030: 
                   7031: sub symbread {
1.249     www      7032:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7033:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7034:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7035: # no filename provided? try from environment
1.44      www      7036:     unless ($thisfn) {
1.620     albertel 7037:         if ($env{'request.symb'}) {
                   7038: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7039: 	}
1.620     albertel 7040: 	$thisfn=$env{'request.filename'};
1.44      www      7041:     }
1.569     albertel 7042:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7043: # is that filename actually a symb? Verify, clean, and return
                   7044:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7045: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7046: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7047: 	}
1.242     www      7048:     }
1.44      www      7049:     $thisfn=declutter($thisfn);
1.31      www      7050:     my %hash;
1.37      www      7051:     my %bighash;
                   7052:     my $syval='';
1.620     albertel 7053:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7054:         my $targetfn = $thisfn;
1.609     banghart 7055:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7056:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7057:         }
1.687     albertel 7058: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7059: 	    $targetfn=$1;
                   7060: 	}
1.620     albertel 7061:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7062:                       &GDBM_READER(),0640)) {
1.481     raeburn  7063: 	    $syval=$hash{$targetfn};
1.37      www      7064:             untie(%hash);
                   7065:         }
                   7066: # ---------------------------------------------------------- There was an entry
                   7067:         if ($syval) {
1.601     albertel 7068: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7069: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7070: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7071: 		    #return $env{$cache_str}='';
1.601     albertel 7072: 		#}    
                   7073: 		#$syval.=$1;
                   7074: 	    #}
1.37      www      7075:         } else {
                   7076: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7077:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7078:                             &GDBM_READER(),0640)) {
1.37      www      7079: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7080:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7081:               unless ($ids) { 
                   7082:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7083:               }
                   7084:               unless ($ids) {
                   7085: # alias?
                   7086: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7087:               }
1.37      www      7088:               if ($ids) {
                   7089: # ------------------------------------------------------------------- Has ID(s)
                   7090:                  my @possibilities=split(/\,/,$ids);
1.39      www      7091:                  if ($#possibilities==0) {
                   7092: # ----------------------------------------------- There is only one possibility
1.37      www      7093: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7094: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7095: 						    $resid,$thisfn);
1.249     www      7096:                  } elsif (!$donotrecurse) {
1.39      www      7097: # ------------------------------------------ There is more than one possibility
                   7098:                      my $realpossible=0;
1.800     albertel 7099:                      foreach my $id (@possibilities) {
                   7100: 			 my $file=$bighash{'src_'.$id};
1.39      www      7101:                          if (&allowed('bre',$file)) {
1.800     albertel 7102:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7103:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7104: 				$realpossible++;
1.626     albertel 7105:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7106: 						    $resid,$thisfn);
1.39      www      7107:                             }
                   7108: 			 }
1.191     harris41 7109:                      }
1.39      www      7110: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7111:                  } else {
                   7112:                      $syval='';
1.37      www      7113:                  }
                   7114: 	      }
                   7115:               untie(%bighash)
1.481     raeburn  7116:            }
1.31      www      7117:         }
1.62      www      7118:         if ($syval) {
1.620     albertel 7119: 	    return $env{$cache_str}=$syval;
1.62      www      7120:         }
1.31      www      7121:     }
1.44      www      7122:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7123:     return $env{$cache_str}='';
1.31      www      7124: }
                   7125: 
                   7126: # ---------------------------------------------------------- Return random seed
                   7127: 
1.32      www      7128: sub numval {
                   7129:     my $txt=shift;
                   7130:     $txt=~tr/A-J/0-9/;
                   7131:     $txt=~tr/a-j/0-9/;
                   7132:     $txt=~tr/K-T/0-9/;
                   7133:     $txt=~tr/k-t/0-9/;
                   7134:     $txt=~tr/U-Z/0-5/;
                   7135:     $txt=~tr/u-z/0-5/;
                   7136:     $txt=~s/\D//g;
1.564     albertel 7137:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7138:     return int($txt);
1.368     albertel 7139: }
                   7140: 
1.484     albertel 7141: sub numval2 {
                   7142:     my $txt=shift;
                   7143:     $txt=~tr/A-J/0-9/;
                   7144:     $txt=~tr/a-j/0-9/;
                   7145:     $txt=~tr/K-T/0-9/;
                   7146:     $txt=~tr/k-t/0-9/;
                   7147:     $txt=~tr/U-Z/0-5/;
                   7148:     $txt=~tr/u-z/0-5/;
                   7149:     $txt=~s/\D//g;
                   7150:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7151:     my $total;
                   7152:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7153:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7154:     return int($total);
                   7155: }
                   7156: 
1.575     albertel 7157: sub numval3 {
                   7158:     use integer;
                   7159:     my $txt=shift;
                   7160:     $txt=~tr/A-J/0-9/;
                   7161:     $txt=~tr/a-j/0-9/;
                   7162:     $txt=~tr/K-T/0-9/;
                   7163:     $txt=~tr/k-t/0-9/;
                   7164:     $txt=~tr/U-Z/0-5/;
                   7165:     $txt=~tr/u-z/0-5/;
                   7166:     $txt=~s/\D//g;
                   7167:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7168:     my $total;
                   7169:     foreach my $val (@txts) { $total+=$val; }
                   7170:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7171:     return $total;
                   7172: }
                   7173: 
1.675     albertel 7174: sub digest {
                   7175:     my ($data)=@_;
                   7176:     my $digest=&Digest::MD5::md5($data);
                   7177:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7178:     my ($e,$f);
                   7179:     {
                   7180:         use integer;
                   7181:         $e=($a+$b);
                   7182:         $f=($c+$d);
                   7183:         if ($_64bit) {
                   7184:             $e=(($e<<32)>>32);
                   7185:             $f=(($f<<32)>>32);
                   7186:         }
                   7187:     }
                   7188:     if (wantarray) {
                   7189: 	return ($e,$f);
                   7190:     } else {
                   7191: 	my $g;
                   7192: 	{
                   7193: 	    use integer;
                   7194: 	    $g=($e+$f);
                   7195: 	    if ($_64bit) {
                   7196: 		$g=(($g<<32)>>32);
                   7197: 	    }
                   7198: 	}
                   7199: 	return $g;
                   7200:     }
                   7201: }
                   7202: 
1.368     albertel 7203: sub latest_rnd_algorithm_id {
1.675     albertel 7204:     return '64bit5';
1.366     albertel 7205: }
1.32      www      7206: 
1.503     albertel 7207: sub get_rand_alg {
                   7208:     my ($courseid)=@_;
1.790     albertel 7209:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7210:     if ($courseid) {
1.620     albertel 7211: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7212:     }
                   7213:     return &latest_rnd_algorithm_id();
                   7214: }
                   7215: 
1.562     albertel 7216: sub validCODE {
                   7217:     my ($CODE)=@_;
                   7218:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7219:     return 0;
                   7220: }
                   7221: 
1.491     albertel 7222: sub getCODE {
1.620     albertel 7223:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7224:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7225: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7226: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7227: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7228:     }
                   7229:     return undef;
                   7230: }
                   7231: 
1.31      www      7232: sub rndseed {
1.155     albertel 7233:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7234:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7235:     if (!defined($symb)) {
1.366     albertel 7236: 	unless ($symb=$wsymb) { return time; }
                   7237:     }
                   7238:     if (!$courseid) { $courseid=$wcourseid; }
                   7239:     if (!$domain) { $domain=$wdomain; }
                   7240:     if (!$username) { $username=$wusername }
1.503     albertel 7241:     my $which=&get_rand_alg();
1.803     albertel 7242: 
1.491     albertel 7243:     if (defined(&getCODE())) {
1.675     albertel 7244: 	if ($which eq '64bit5') {
                   7245: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7246: 	} elsif ($which eq '64bit4') {
1.575     albertel 7247: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7248: 	} else {
                   7249: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7250: 	}
1.675     albertel 7251:     } elsif ($which eq '64bit5') {
                   7252: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7253:     } elsif ($which eq '64bit4') {
                   7254: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7255:     } elsif ($which eq '64bit3') {
                   7256: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7257:     } elsif ($which eq '64bit2') {
                   7258: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7259:     } elsif ($which eq '64bit') {
                   7260: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7261:     }
                   7262:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7263: }
                   7264: 
                   7265: sub rndseed_32bit {
                   7266:     my ($symb,$courseid,$domain,$username)=@_;
                   7267:     {
                   7268: 	use integer;
                   7269: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7270: 	my $symbseed=numval($symb) << 22;
                   7271: 	my $namechck=unpack("%32C*",$username) << 17;
                   7272: 	my $nameseed=numval($username) << 12;
                   7273: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7274: 	my $courseseed=unpack("%32C*",$courseid);
                   7275: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7276: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7277: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7278: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7279: 	return $num;
                   7280:     }
                   7281: }
                   7282: 
                   7283: sub rndseed_64bit {
                   7284:     my ($symb,$courseid,$domain,$username)=@_;
                   7285:     {
                   7286: 	use integer;
                   7287: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7288: 	my $symbseed=numval($symb) << 10;
                   7289: 	my $namechck=unpack("%32S*",$username);
                   7290: 	
                   7291: 	my $nameseed=numval($username) << 21;
                   7292: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7293: 	my $courseseed=unpack("%32S*",$courseid);
                   7294: 	
                   7295: 	my $num1=$symbchck+$symbseed+$namechck;
                   7296: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7297: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7298: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7299: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7300: 	return "$num1,$num2";
1.155     albertel 7301:     }
1.366     albertel 7302: }
                   7303: 
1.443     albertel 7304: sub rndseed_64bit2 {
                   7305:     my ($symb,$courseid,$domain,$username)=@_;
                   7306:     {
                   7307: 	use integer;
                   7308: 	# strings need to be an even # of cahracters long, it it is odd the
                   7309:         # last characters gets thrown away
                   7310: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7311: 	my $symbseed=numval($symb) << 10;
                   7312: 	my $namechck=unpack("%32S*",$username.' ');
                   7313: 	
                   7314: 	my $nameseed=numval($username) << 21;
1.501     albertel 7315: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7316: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7317: 	
                   7318: 	my $num1=$symbchck+$symbseed+$namechck;
                   7319: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7320: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7321: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7322: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7323: 	return "$num1,$num2";
                   7324:     }
                   7325: }
                   7326: 
                   7327: sub rndseed_64bit3 {
                   7328:     my ($symb,$courseid,$domain,$username)=@_;
                   7329:     {
                   7330: 	use integer;
                   7331: 	# strings need to be an even # of cahracters long, it it is odd the
                   7332:         # last characters gets thrown away
                   7333: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7334: 	my $symbseed=numval2($symb) << 10;
                   7335: 	my $namechck=unpack("%32S*",$username.' ');
                   7336: 	
                   7337: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7338: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7339: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7340: 	
                   7341: 	my $num1=$symbchck+$symbseed+$namechck;
                   7342: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7343: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7344: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7345: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7346: 	
1.503     albertel 7347: 	return "$num1:$num2";
1.443     albertel 7348:     }
                   7349: }
                   7350: 
1.575     albertel 7351: sub rndseed_64bit4 {
                   7352:     my ($symb,$courseid,$domain,$username)=@_;
                   7353:     {
                   7354: 	use integer;
                   7355: 	# strings need to be an even # of cahracters long, it it is odd the
                   7356:         # last characters gets thrown away
                   7357: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7358: 	my $symbseed=numval3($symb) << 10;
                   7359: 	my $namechck=unpack("%32S*",$username.' ');
                   7360: 	
                   7361: 	my $nameseed=numval3($username) << 21;
                   7362: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7363: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7364: 	
                   7365: 	my $num1=$symbchck+$symbseed+$namechck;
                   7366: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7367: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7368: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7369: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7370: 	
                   7371: 	return "$num1:$num2";
                   7372:     }
                   7373: }
                   7374: 
1.675     albertel 7375: sub rndseed_64bit5 {
                   7376:     my ($symb,$courseid,$domain,$username)=@_;
                   7377:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7378:     return "$num1:$num2";
                   7379: }
                   7380: 
1.366     albertel 7381: sub rndseed_CODE_64bit {
                   7382:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7383:     {
1.366     albertel 7384: 	use integer;
1.443     albertel 7385: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7386: 	my $symbseed=numval2($symb);
1.491     albertel 7387: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7388: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7389: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7390: 	my $num1=$symbseed+$CODEchck;
                   7391: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7392: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7393: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7394: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7395: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7396: 	return "$num1:$num2";
1.366     albertel 7397:     }
                   7398: }
                   7399: 
1.575     albertel 7400: sub rndseed_CODE_64bit4 {
                   7401:     my ($symb,$courseid,$domain,$username)=@_;
                   7402:     {
                   7403: 	use integer;
                   7404: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7405: 	my $symbseed=numval3($symb);
                   7406: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7407: 	my $CODEseed=numval3(&getCODE());
                   7408: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7409: 	my $num1=$symbseed+$CODEchck;
                   7410: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7411: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7412: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7413: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7414: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7415: 	return "$num1:$num2";
                   7416:     }
                   7417: }
                   7418: 
1.675     albertel 7419: sub rndseed_CODE_64bit5 {
                   7420:     my ($symb,$courseid,$domain,$username)=@_;
                   7421:     my $code = &getCODE();
                   7422:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7423:     return "$num1:$num2";
                   7424: }
                   7425: 
1.366     albertel 7426: sub setup_random_from_rndseed {
                   7427:     my ($rndseed)=@_;
1.503     albertel 7428:     if ($rndseed =~/([,:])/) {
                   7429: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7430: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7431:     } else {
                   7432: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7433:     }
1.36      albertel 7434: }
                   7435: 
1.474     albertel 7436: sub latest_receipt_algorithm_id {
1.835     albertel 7437:     return 'receipt3';
1.474     albertel 7438: }
                   7439: 
1.480     www      7440: sub recunique {
                   7441:     my $fucourseid=shift;
                   7442:     my $unique;
1.835     albertel 7443:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7444: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7445: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7446:     } else {
                   7447: 	$unique=$perlvar{'lonReceipt'};
                   7448:     }
                   7449:     return unpack("%32C*",$unique);
                   7450: }
                   7451: 
                   7452: sub recprefix {
                   7453:     my $fucourseid=shift;
                   7454:     my $prefix;
1.835     albertel 7455:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7456: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7457: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7458:     } else {
                   7459: 	$prefix=$perlvar{'lonHostID'};
                   7460:     }
                   7461:     return unpack("%32C*",$prefix);
                   7462: }
                   7463: 
1.76      www      7464: sub ireceipt {
1.474     albertel 7465:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7466: 
                   7467:     my $return =&recprefix($fucourseid).'-';
                   7468: 
                   7469:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7470: 	$env{'request.state'} eq 'construct') {
                   7471: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7472: 	return $return;
                   7473:     }
                   7474: 
1.76      www      7475:     my $cuname=unpack("%32C*",$funame);
                   7476:     my $cudom=unpack("%32C*",$fudom);
                   7477:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7478:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7479:     my $cunique=&recunique($fucourseid);
1.474     albertel 7480:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7481:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7482: 
1.790     albertel 7483: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7484: 			       
                   7485: 	$return.= ($cunique%$cuname+
                   7486: 		   $cunique%$cudom+
                   7487: 		   $cusymb%$cuname+
                   7488: 		   $cusymb%$cudom+
                   7489: 		   $cucourseid%$cuname+
                   7490: 		   $cucourseid%$cudom+
                   7491: 		   $cpart%$cuname+
                   7492: 		   $cpart%$cudom);
                   7493:     } else {
                   7494: 	$return.= ($cunique%$cuname+
                   7495: 		   $cunique%$cudom+
                   7496: 		   $cusymb%$cuname+
                   7497: 		   $cusymb%$cudom+
                   7498: 		   $cucourseid%$cuname+
                   7499: 		   $cucourseid%$cudom);
                   7500:     }
                   7501:     return $return;
1.76      www      7502: }
                   7503: 
                   7504: sub receipt {
1.474     albertel 7505:     my ($part)=@_;
1.790     albertel 7506:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7507:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7508: }
1.260     ng       7509: 
1.790     albertel 7510: sub whichuser {
                   7511:     my ($passedsymb)=@_;
                   7512:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7513:     if (defined($env{'form.grade_symb'})) {
                   7514: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7515: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7516: 	if (!$allowed &&
                   7517: 	    exists($env{'request.course.sec'}) &&
                   7518: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7519: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7520: 			      '/'.$env{'request.course.sec'});
                   7521: 	}
                   7522: 	if ($allowed) {
                   7523: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7524: 	    $courseid=$tmp_courseid;
                   7525: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7526: 	    ($name)=&get_env_multiple('form.grade_username');
                   7527: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7528: 	}
                   7529:     }
                   7530:     if (!$passedsymb) {
                   7531: 	$symb=&symbread();
                   7532:     } else {
                   7533: 	$symb=$passedsymb;
                   7534:     }
                   7535:     $courseid=$env{'request.course.id'};
                   7536:     $domain=$env{'user.domain'};
                   7537:     $name=$env{'user.name'};
                   7538:     if ($name eq 'public' && $domain eq 'public') {
                   7539: 	if (!defined($env{'form.username'})) {
                   7540: 	    $env{'form.username'}.=time.rand(10000000);
                   7541: 	}
                   7542: 	$name.=$env{'form.username'};
                   7543:     }
                   7544:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7545: 
                   7546: }
                   7547: 
1.36      albertel 7548: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7549: # returns either the contents of the file or 
                   7550: # -1 if the file doesn't exist
1.481     raeburn  7551: #
                   7552: # if the target is a file that was uploaded via DOCS, 
                   7553: # a check will be made to see if a current copy exists on the local server,
                   7554: # if it does this will be served, otherwise a copy will be retrieved from
                   7555: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7556: # the local server.   
1.472     albertel 7557: 
1.36      albertel 7558: sub getfile {
1.538     albertel 7559:     my ($file) = @_;
1.609     banghart 7560:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7561:     &repcopy($file);
                   7562:     return &readfile($file);
                   7563: }
                   7564: 
                   7565: sub repcopy_userfile {
                   7566:     my ($file)=@_;
1.609     banghart 7567:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7568:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7569:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7570: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7571:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7572:     if (-e "$file") {
1.828     www      7573: # we already have a local copy, check it out
1.538     albertel 7574: 	my @fileinfo = stat($file);
1.828     www      7575: 	my $rtncode;
                   7576: 	my $info;
1.538     albertel 7577: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7578: 	if ($lwpresp ne 'ok') {
1.828     www      7579: # there is no such file anymore, even though we had a local copy
1.482     albertel 7580: 	    if ($rtncode eq '404') {
1.538     albertel 7581: 		unlink($file);
1.482     albertel 7582: 	    }
                   7583: 	    return -1;
                   7584: 	}
                   7585: 	if ($info < $fileinfo[9]) {
1.828     www      7586: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7587: 	    return 'ok';
1.828     www      7588: 	} else {
                   7589: # the file is outdated, get rid of it
                   7590: 	    unlink($file);
1.482     albertel 7591: 	}
1.828     www      7592:     }
                   7593: # one way or the other, at this point, we don't have the file
                   7594: # construct the correct path for the file
                   7595:     my @parts = ($cdom,$cnum); 
                   7596:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7597: 	push @parts, split(/\//,$1);
                   7598:     }
                   7599:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7600:     foreach my $part (@parts) {
                   7601: 	$path .= '/'.$part;
                   7602: 	if (!-e $path) {
                   7603: 	    mkdir($path,0770);
1.482     albertel 7604: 	}
                   7605:     }
1.828     www      7606: # now the path exists for sure
                   7607: # get a user agent
                   7608:     my $ua=new LWP::UserAgent;
                   7609:     my $transferfile=$file.'.in.transfer';
                   7610: # FIXME: this should flock
                   7611:     if (-e $transferfile) { return 'ok'; }
                   7612:     my $request;
                   7613:     $uri=~s/^\///;
1.838     albertel 7614:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7615:     my $response=$ua->request($request,$transferfile);
                   7616: # did it work?
                   7617:     if ($response->is_error()) {
                   7618: 	unlink($transferfile);
                   7619: 	&logthis("Userfile repcopy failed for $uri");
                   7620: 	return -1;
                   7621:     }
                   7622: # worked, rename the transfer file
                   7623:     rename($transferfile,$file);
1.607     raeburn  7624:     return 'ok';
1.481     raeburn  7625: }
                   7626: 
1.517     albertel 7627: sub tokenwrapper {
                   7628:     my $uri=shift;
1.552     albertel 7629:     $uri=~s|^http\://([^/]+)||;
                   7630:     $uri=~s|^/||;
1.620     albertel 7631:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7632:     my $token=$1;
1.552     albertel 7633:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7634:     if ($udom && $uname && $file) {
                   7635: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7636:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7637:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7638:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7639:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7640:     } else {
                   7641:         return '/adm/notfound.html';
                   7642:     }
                   7643: }
                   7644: 
1.828     www      7645: # call with reqtype HEAD: get last modification time
                   7646: # call with reqtype GET: get the file contents
                   7647: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7648: #
1.481     raeburn  7649: sub getuploaded {
                   7650:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7651:     $uri=~s/^\///;
1.838     albertel 7652:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7653:     my $ua=new LWP::UserAgent;
                   7654:     my $request=new HTTP::Request($reqtype,$uri);
                   7655:     my $response=$ua->request($request);
                   7656:     $$rtncode = $response->code;
1.482     albertel 7657:     if (! $response->is_success()) {
                   7658: 	return 'failed';
                   7659:     }      
                   7660:     if ($reqtype eq 'HEAD') {
1.486     www      7661: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7662:     } elsif ($reqtype eq 'GET') {
                   7663: 	$$info = $response->content;
1.472     albertel 7664:     }
1.482     albertel 7665:     return 'ok';
1.36      albertel 7666: }
                   7667: 
1.481     raeburn  7668: sub readfile {
                   7669:     my $file = shift;
                   7670:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7671:     my $fh;
                   7672:     open($fh,"<$file");
                   7673:     my $a='';
1.800     albertel 7674:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7675:     return $a;
                   7676: }
                   7677: 
1.36      albertel 7678: sub filelocation {
1.590     banghart 7679:     my ($dir,$file) = @_;
                   7680:     my $location;
                   7681:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7682: 
                   7683:     if ($file =~ m-^/adm/-) {
                   7684: 	$file=~s-^/adm/wrapper/-/-;
                   7685: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7686:     }
1.882     albertel 7687: 
1.590     banghart 7688:     if ($file=~m:^/~:) { # is a contruction space reference
                   7689:         $location = $file;
                   7690:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7691:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7692: 	# is a correct contruction space reference
                   7693:         $location = $file;
1.609     banghart 7694:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7695:         my ($udom,$uname,$filename)=
1.811     albertel 7696:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7697:         my $home=&homeserver($uname,$udom);
                   7698:         my $is_me=0;
                   7699:         my @ids=&current_machine_ids();
                   7700:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7701:         if ($is_me) {
1.740     www      7702:   	    $location=&propath($udom,$uname).
1.590     banghart 7703:   	      '/userfiles/'.$filename;
                   7704:         } else {
                   7705:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7706:   	      $udom.'/'.$uname.'/'.$filename;
                   7707:         }
1.882     albertel 7708:     } elsif ($file =~ m-^/adm/-) {
                   7709: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7710:     } else {
                   7711:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7712:         $file=~s:^/res/:/:;
                   7713:         if ( !( $file =~ m:^/:) ) {
                   7714:             $location = $dir. '/'.$file;
                   7715:         } else {
                   7716:             $location = '/home/httpd/html/res'.$file;
                   7717:         }
1.59      albertel 7718:     }
1.590     banghart 7719:     $location=~s://+:/:g; # remove duplicate /
                   7720:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7721:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7722:     return $location;
1.46      www      7723: }
1.36      albertel 7724: 
1.46      www      7725: sub hreflocation {
                   7726:     my ($dir,$file)=@_;
1.460     albertel 7727:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7728: 	$file=filelocation($dir,$file);
1.700     albertel 7729:     } elsif ($file=~m-^/adm/-) {
                   7730: 	$file=~s-^/adm/wrapper/-/-;
                   7731: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7732:     }
                   7733:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7734: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7735:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7736: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7737:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7738: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7739: 	    -/uploaded/$1/$2/-x;
1.46      www      7740:     }
1.462     albertel 7741:     return $file;
1.465     albertel 7742: }
                   7743: 
                   7744: sub current_machine_domains {
1.853     albertel 7745:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7746: }
                   7747: 
                   7748: sub machine_domains {
                   7749:     my ($hostname) = @_;
1.465     albertel 7750:     my @domains;
1.838     albertel 7751:     my %hostname = &all_hostnames();
1.465     albertel 7752:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7753: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7754: 	if ($hostname eq $name) {
1.844     albertel 7755: 	    push(@domains,&host_domain($id));
1.465     albertel 7756: 	}
                   7757:     }
                   7758:     return @domains;
                   7759: }
                   7760: 
                   7761: sub current_machine_ids {
1.853     albertel 7762:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7763: }
                   7764: 
                   7765: sub machine_ids {
                   7766:     my ($hostname) = @_;
                   7767:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7768:     my @ids;
1.888     albertel 7769:     my %name_to_host = &all_names();
1.889     albertel 7770:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7771: 	return @{ $name_to_host{$hostname} };
                   7772:     }
                   7773:     return;
1.31      www      7774: }
                   7775: 
1.824     raeburn  7776: sub additional_machine_domains {
                   7777:     my @domains;
                   7778:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7779:     while( my $line = <$fh>) {
                   7780:         $line =~ s/\s//g;
                   7781:         push(@domains,$line);
                   7782:     }
                   7783:     return @domains;
                   7784: }
                   7785: 
                   7786: sub default_login_domain {
                   7787:     my $domain = $perlvar{'lonDefDomain'};
                   7788:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7789:     foreach my $posdom (&current_machine_domains(),
                   7790:                         &additional_machine_domains()) {
                   7791:         if (lc($posdom) eq lc($testdomain)) {
                   7792:             $domain=$posdom;
                   7793:             last;
                   7794:         }
                   7795:     }
                   7796:     return $domain;
                   7797: }
                   7798: 
1.31      www      7799: # ------------------------------------------------------------- Declutters URLs
                   7800: 
                   7801: sub declutter {
                   7802:     my $thisfn=shift;
1.569     albertel 7803:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7804:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7805:     $thisfn=~s/^\///;
1.697     albertel 7806:     $thisfn=~s|^adm/wrapper/||;
                   7807:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7808:     $thisfn=~s/^res\///;
1.235     www      7809:     $thisfn=~s/\?.+$//;
1.268     www      7810:     return $thisfn;
                   7811: }
                   7812: 
                   7813: # ------------------------------------------------------------- Clutter up URLs
                   7814: 
                   7815: sub clutter {
                   7816:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7817:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7818: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7819:        $thisfn='/res'.$thisfn; 
                   7820:     }
1.694     albertel 7821:     if ($thisfn !~m|/adm|) {
1.695     albertel 7822: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7823: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7824: 	} else {
                   7825: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7826: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7827: 	    if ($embstyle eq 'ssi'
                   7828: 		|| ($embstyle eq 'hdn')
                   7829: 		|| ($embstyle eq 'rat')
                   7830: 		|| ($embstyle eq 'prv')
                   7831: 		|| ($embstyle eq 'ign')) {
                   7832: 		#do nothing with these
                   7833: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7834: 		|| ($embstyle eq 'emb')
                   7835: 		|| ($embstyle eq 'wrp')) {
                   7836: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7837: 	    } elsif ($embstyle eq 'unk'
                   7838: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7839: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7840: 	    } else {
1.718     www      7841: #		&logthis("Got a blank emb style");
1.695     albertel 7842: 	    }
1.694     albertel 7843: 	}
                   7844:     }
1.31      www      7845:     return $thisfn;
1.12      www      7846: }
                   7847: 
1.787     albertel 7848: sub clutter_with_no_wrapper {
                   7849:     my $uri = &clutter(shift);
                   7850:     if ($uri =~ m-^/adm/-) {
                   7851: 	$uri =~ s-^/adm/wrapper/-/-;
                   7852: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7853:     }
                   7854:     return $uri;
                   7855: }
                   7856: 
1.557     albertel 7857: sub freeze_escape {
                   7858:     my ($value)=@_;
                   7859:     if (ref($value)) {
                   7860: 	$value=&nfreeze($value);
                   7861: 	return '__FROZEN__'.&escape($value);
                   7862:     }
                   7863:     return &escape($value);
                   7864: }
                   7865: 
1.11      www      7866: 
1.557     albertel 7867: sub thaw_unescape {
                   7868:     my ($value)=@_;
                   7869:     if ($value =~ /^__FROZEN__/) {
                   7870: 	substr($value,0,10,undef);
                   7871: 	$value=&unescape($value);
                   7872: 	return &thaw($value);
                   7873:     }
                   7874:     return &unescape($value);
                   7875: }
                   7876: 
1.436     albertel 7877: sub correct_line_ends {
                   7878:     my ($result)=@_;
                   7879:     $$result =~s/\r\n/\n/mg;
                   7880:     $$result =~s/\r/\n/mg;
1.415     albertel 7881: }
1.1       albertel 7882: # ================================================================ Main Program
                   7883: 
1.184     www      7884: sub goodbye {
1.204     albertel 7885:    &logthis("Starting Shut down");
1.443     albertel 7886: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7887:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7888: #converted
1.599     albertel 7889: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7890:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7891: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7892: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7893: #1.1 only
1.870     albertel 7894: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7895: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7896: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7897: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7898:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7899:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7900:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7901:    &flushcourselogs();
                   7902:    &logthis("Shutting down");
                   7903: }
                   7904: 
1.852     albertel 7905: sub get_dns {
1.869     albertel 7906:     my ($url,$func,$ignore_cache) = @_;
                   7907:     if (!$ignore_cache) {
                   7908: 	my ($content,$cached)=
                   7909: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7910: 	if ($cached) {
                   7911: 	    &$func($content);
                   7912: 	    return;
                   7913: 	}
                   7914:     }
                   7915: 
                   7916:     my %alldns;
1.852     albertel 7917:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7918:     foreach my $dns (<$config>) {
                   7919: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7920: 	$alldns{$1} = 1;
                   7921:     }
                   7922:     while (%alldns) {
                   7923: 	my ($dns) = keys(%alldns);
                   7924: 	delete($alldns{$dns});
1.852     albertel 7925: 	my $ua=new LWP::UserAgent;
                   7926: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7927: 	my $response=$ua->request($request);
                   7928: 	next if ($response->is_error());
                   7929: 	my @content = split("\n",$response->content);
1.869     albertel 7930: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7931: 	&$func(\@content);
1.869     albertel 7932: 	return;
1.852     albertel 7933:     }
                   7934:     close($config);
1.871     albertel 7935:     my $which = (split('/',$url))[3];
                   7936:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7937:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7938:     my @content = <$config>;
                   7939:     &$func(\@content);
                   7940:     return;
1.852     albertel 7941: }
1.327     albertel 7942: # ------------------------------------------------------------ Read domain file
                   7943: {
1.852     albertel 7944:     my $loaded;
1.846     albertel 7945:     my %domain;
                   7946: 
1.852     albertel 7947:     sub parse_domain_tab {
                   7948: 	my ($lines) = @_;
                   7949: 	foreach my $line (@$lines) {
                   7950: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7951: 
1.846     albertel 7952: 	    chomp($line);
1.852     albertel 7953: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7954: 	    my %this_domain;
                   7955: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7956: 			       'lang_def', 'city', 'longi', 'lati',
                   7957: 			       'primary') {
                   7958: 		$this_domain{$field} = shift(@elements);
                   7959: 	    }
                   7960: 	    $domain{$name} = \%this_domain;
1.852     albertel 7961: 	}
                   7962:     }
1.864     albertel 7963: 
                   7964:     sub reset_domain_info {
                   7965: 	undef($loaded);
                   7966: 	undef(%domain);
                   7967:     }
                   7968: 
1.852     albertel 7969:     sub load_domain_tab {
1.869     albertel 7970: 	my ($ignore_cache) = @_;
                   7971: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7972: 	my $fh;
                   7973: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7974: 	    my @lines = <$fh>;
                   7975: 	    &parse_domain_tab(\@lines);
1.448     albertel 7976: 	}
1.852     albertel 7977: 	close($fh);
                   7978: 	$loaded = 1;
1.327     albertel 7979:     }
1.846     albertel 7980: 
                   7981:     sub domain {
1.852     albertel 7982: 	&load_domain_tab() if (!$loaded);
                   7983: 
1.846     albertel 7984: 	my ($name,$what) = @_;
                   7985: 	return if ( !exists($domain{$name}) );
                   7986: 
                   7987: 	if (!$what) {
                   7988: 	    return $domain{$name}{'description'};
                   7989: 	}
                   7990: 	return $domain{$name}{$what};
                   7991:     }
1.327     albertel 7992: }
                   7993: 
                   7994: 
1.1       albertel 7995: # ------------------------------------------------------------- Read hosts file
                   7996: {
1.838     albertel 7997:     my %hostname;
1.844     albertel 7998:     my %hostdom;
1.845     albertel 7999:     my %libserv;
1.852     albertel 8000:     my $loaded;
1.888     albertel 8001:     my %name_to_host;
1.852     albertel 8002: 
                   8003:     sub parse_hosts_tab {
                   8004: 	my ($file) = @_;
                   8005: 	foreach my $configline (@$file) {
                   8006: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8007: 	    next if ($configline =~ /^\^/);
                   8008: 	    chomp($configline);
                   8009: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8010: 	    $name=~s/\s//g;
                   8011: 	    if ($id && $domain && $role && $name) {
                   8012: 		$hostname{$id}=$name;
1.888     albertel 8013: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8014: 		$hostdom{$id}=$domain;
                   8015: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8016: 	    }
                   8017: 	}
                   8018:     }
1.864     albertel 8019:     
                   8020:     sub reset_hosts_info {
1.897     albertel 8021: 	&purge_remembered();
1.864     albertel 8022: 	&reset_domain_info();
                   8023: 	&reset_hosts_ip_info();
1.892     albertel 8024: 	undef(%name_to_host);
1.864     albertel 8025: 	undef(%hostname);
                   8026: 	undef(%hostdom);
                   8027: 	undef(%libserv);
                   8028: 	undef($loaded);
                   8029:     }
1.1       albertel 8030: 
1.852     albertel 8031:     sub load_hosts_tab {
1.869     albertel 8032: 	my ($ignore_cache) = @_;
                   8033: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8034: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8035: 	my @config = <$config>;
                   8036: 	&parse_hosts_tab(\@config);
                   8037: 	close($config);
                   8038: 	$loaded=1;
1.1       albertel 8039:     }
1.852     albertel 8040: 
1.838     albertel 8041:     sub hostname {
1.852     albertel 8042: 	&load_hosts_tab() if (!$loaded);
                   8043: 
1.838     albertel 8044: 	my ($lonid) = @_;
                   8045: 	return $hostname{$lonid};
                   8046:     }
1.845     albertel 8047: 
1.838     albertel 8048:     sub all_hostnames {
1.852     albertel 8049: 	&load_hosts_tab() if (!$loaded);
                   8050: 
1.838     albertel 8051: 	return %hostname;
                   8052:     }
1.845     albertel 8053: 
1.888     albertel 8054:     sub all_names {
                   8055: 	&load_hosts_tab() if (!$loaded);
                   8056: 
                   8057: 	return %name_to_host;
                   8058:     }
                   8059: 
1.845     albertel 8060:     sub is_library {
1.852     albertel 8061: 	&load_hosts_tab() if (!$loaded);
                   8062: 
1.845     albertel 8063: 	return exists($libserv{$_[0]});
                   8064:     }
                   8065: 
                   8066:     sub all_library {
1.852     albertel 8067: 	&load_hosts_tab() if (!$loaded);
                   8068: 
1.845     albertel 8069: 	return %libserv;
                   8070:     }
                   8071: 
1.841     albertel 8072:     sub get_servers {
1.852     albertel 8073: 	&load_hosts_tab() if (!$loaded);
                   8074: 
1.841     albertel 8075: 	my ($domain,$type) = @_;
                   8076: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8077: 	                                          : %hostname;
                   8078: 	my %result;
1.842     albertel 8079: 	if (ref($domain) eq 'ARRAY') {
                   8080: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8081: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8082: 		    $result{$host} = $hostname;
                   8083: 		}
                   8084: 	    }
                   8085: 	} else {
                   8086: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8087: 		if ($hostdom{$host} eq $domain) {
                   8088: 		    $result{$host} = $hostname;
                   8089: 		}
1.841     albertel 8090: 	    }
                   8091: 	}
                   8092: 	return %result;
                   8093:     }
1.845     albertel 8094: 
1.844     albertel 8095:     sub host_domain {
1.852     albertel 8096: 	&load_hosts_tab() if (!$loaded);
                   8097: 
1.844     albertel 8098: 	my ($lonid) = @_;
                   8099: 	return $hostdom{$lonid};
                   8100:     }
                   8101: 
1.841     albertel 8102:     sub all_domains {
1.852     albertel 8103: 	&load_hosts_tab() if (!$loaded);
                   8104: 
1.841     albertel 8105: 	my %seen;
                   8106: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8107: 	return @uniq;
                   8108:     }
1.1       albertel 8109: }
                   8110: 
1.847     albertel 8111: { 
                   8112:     my %iphost;
1.856     albertel 8113:     my %name_to_ip;
                   8114:     my %lonid_to_ip;
1.869     albertel 8115: 
1.847     albertel 8116:     sub get_hosts_from_ip {
                   8117: 	my ($ip) = @_;
                   8118: 	my %iphosts = &get_iphost();
                   8119: 	if (ref($iphosts{$ip})) {
                   8120: 	    return @{$iphosts{$ip}};
                   8121: 	}
                   8122: 	return;
1.839     albertel 8123:     }
1.864     albertel 8124:     
                   8125:     sub reset_hosts_ip_info {
                   8126: 	undef(%iphost);
                   8127: 	undef(%name_to_ip);
                   8128: 	undef(%lonid_to_ip);
                   8129:     }
1.856     albertel 8130: 
                   8131:     sub get_host_ip {
                   8132: 	my ($lonid) = @_;
                   8133: 	if (exists($lonid_to_ip{$lonid})) {
                   8134: 	    return $lonid_to_ip{$lonid};
                   8135: 	}
                   8136: 	my $name=&hostname($lonid);
                   8137:    	my $ip = gethostbyname($name);
                   8138: 	return if (!$ip || length($ip) ne 4);
                   8139: 	$ip=inet_ntoa($ip);
                   8140: 	$name_to_ip{$name}   = $ip;
                   8141: 	$lonid_to_ip{$lonid} = $ip;
                   8142: 	return $ip;
                   8143:     }
1.847     albertel 8144:     
                   8145:     sub get_iphost {
1.869     albertel 8146: 	my ($ignore_cache) = @_;
1.894     albertel 8147: 
1.869     albertel 8148: 	if (!$ignore_cache) {
                   8149: 	    if (%iphost) {
                   8150: 		return %iphost;
                   8151: 	    }
                   8152: 	    my ($ip_info,$cached)=
                   8153: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8154: 	    if ($cached) {
                   8155: 		%iphost      = %{$ip_info->[0]};
                   8156: 		%name_to_ip  = %{$ip_info->[1]};
                   8157: 		%lonid_to_ip = %{$ip_info->[2]};
                   8158: 		return %iphost;
                   8159: 	    }
                   8160: 	}
1.894     albertel 8161: 
                   8162: 	# get yesterday's info for fallback
                   8163: 	my %old_name_to_ip;
                   8164: 	my ($ip_info,$cached)=
                   8165: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8166: 	if ($cached) {
                   8167: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8168: 	}
                   8169: 
1.888     albertel 8170: 	my %name_to_host = &all_names();
                   8171: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8172: 	    my $ip;
                   8173: 	    if (!exists($name_to_ip{$name})) {
                   8174: 		$ip = gethostbyname($name);
                   8175: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8176: 		    if (defined($old_name_to_ip{$name})) {
                   8177: 			$ip = $old_name_to_ip{$name};
                   8178: 			&logthis("Can't find $name defaulting to old $ip");
                   8179: 		    } else {
                   8180: 			&logthis("Name $name no IP found");
                   8181: 			next;
                   8182: 		    }
                   8183: 		} else {
                   8184: 		    $ip=inet_ntoa($ip);
1.847     albertel 8185: 		}
                   8186: 		$name_to_ip{$name} = $ip;
                   8187: 	    } else {
                   8188: 		$ip = $name_to_ip{$name};
1.653     albertel 8189: 	    }
1.888     albertel 8190: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8191: 		$lonid_to_ip{$id} = $ip;
                   8192: 	    }
                   8193: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8194: 	}
1.869     albertel 8195: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8196: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8197: 				      48*60*60);
1.869     albertel 8198: 
1.847     albertel 8199: 	return %iphost;
1.598     albertel 8200:     }
                   8201: }
                   8202: 
1.862     albertel 8203: BEGIN {
                   8204: 
                   8205: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8206:     unless ($readit) {
                   8207: {
                   8208:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8209:     %perlvar = (%perlvar,%{$configvars});
                   8210: }
                   8211: 
                   8212: 
1.1       albertel 8213: # ------------------------------------------------------ Read spare server file
                   8214: {
1.448     albertel 8215:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8216: 
                   8217:     while (my $configline=<$config>) {
                   8218:        chomp($configline);
1.284     matthew  8219:        if ($configline) {
1.784     albertel 8220: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8221: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8222: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8223:        }
                   8224:     }
1.448     albertel 8225:     close($config);
1.1       albertel 8226: }
1.11      www      8227: # ------------------------------------------------------------ Read permissions
                   8228: {
1.448     albertel 8229:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8230: 
                   8231:     while (my $configline=<$config>) {
1.448     albertel 8232: 	chomp($configline);
                   8233: 	if ($configline) {
                   8234: 	    my ($role,$perm)=split(/ /,$configline);
                   8235: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8236: 	}
1.11      www      8237:     }
1.448     albertel 8238:     close($config);
1.11      www      8239: }
                   8240: 
                   8241: # -------------------------------------------- Read plain texts for permissions
                   8242: {
1.448     albertel 8243:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8244: 
                   8245:     while (my $configline=<$config>) {
1.448     albertel 8246: 	chomp($configline);
                   8247: 	if ($configline) {
1.742     raeburn  8248: 	    my ($short,@plain)=split(/:/,$configline);
                   8249:             %{$prp{$short}} = ();
                   8250: 	    if (@plain > 0) {
                   8251:                 $prp{$short}{'std'} = $plain[0];
                   8252:                 for (my $i=1; $i<@plain; $i++) {
                   8253:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8254:                 }
                   8255:             }
1.448     albertel 8256: 	}
1.135     www      8257:     }
1.448     albertel 8258:     close($config);
1.135     www      8259: }
                   8260: 
                   8261: # ---------------------------------------------------------- Read package table
                   8262: {
1.448     albertel 8263:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8264: 
                   8265:     while (my $configline=<$config>) {
1.483     albertel 8266: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8267: 	chomp($configline);
                   8268: 	my ($short,$plain)=split(/:/,$configline);
                   8269: 	my ($pack,$name)=split(/\&/,$short);
                   8270: 	if ($plain ne '') {
                   8271: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8272: 	    $packagetab{$short}=$plain; 
                   8273: 	}
1.11      www      8274:     }
1.448     albertel 8275:     close($config);
1.329     matthew  8276: }
                   8277: 
                   8278: # ------------- set up temporary directory
                   8279: {
                   8280:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8281: 
1.11      www      8282: }
                   8283: 
1.794     albertel 8284: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8285: 				'compress_threshold'=> 20_000,
                   8286:  			        });
1.185     www      8287: 
1.281     www      8288: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8289: $dumpcount=0;
1.22      www      8290: 
1.163     harris41 8291: &logtouch();
1.672     albertel 8292: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8293: $readit=1;
1.564     albertel 8294:     {
                   8295: 	use integer;
                   8296: 	my $test=(2**32)+1;
1.568     albertel 8297: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8298: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8299:     }
1.195     www      8300: }
1.1       albertel 8301: }
1.179     www      8302: 
1.1       albertel 8303: 1;
1.191     harris41 8304: __END__
                   8305: 
1.243     albertel 8306: =pod
                   8307: 
1.191     harris41 8308: =head1 NAME
                   8309: 
1.243     albertel 8310: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8311: 
                   8312: =head1 SYNOPSIS
                   8313: 
1.243     albertel 8314: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8315: 
                   8316:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8317: 
1.243     albertel 8318: Common parameters:
                   8319: 
                   8320: =over 4
                   8321: 
                   8322: =item *
                   8323: 
                   8324: $uname : an internal username (if $cname expecting a course Id specifically)
                   8325: 
                   8326: =item *
                   8327: 
                   8328: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8329: 
                   8330: =item *
                   8331: 
                   8332: $symb : a resource instance identifier
                   8333: 
                   8334: =item *
                   8335: 
                   8336: $namespace : the name of a .db file that contains the data needed or
                   8337: being set.
                   8338: 
                   8339: =back
                   8340: 
1.394     bowersj2 8341: =head1 OVERVIEW
1.191     harris41 8342: 
1.394     bowersj2 8343: lonnet provides subroutines which interact with the
                   8344: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8345: about classes, users, and resources.
1.243     albertel 8346: 
                   8347: For many of these objects you can also use this to store data about
                   8348: them or modify them in various ways.
1.191     harris41 8349: 
1.394     bowersj2 8350: =head2 Symbs
1.191     harris41 8351: 
1.394     bowersj2 8352: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8353: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8354: map, the resource number of the resource in the map, and the URL of
                   8355: the resource itself. The latter is somewhat redundant, but might help
                   8356: if maps change.
                   8357: 
                   8358: An example is
                   8359: 
                   8360:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8361: 
                   8362: The respective map entry is
                   8363: 
                   8364:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8365:   title="Problem 2">
                   8366:  </resource>
                   8367: 
                   8368: Symbs are used by the random number generator, as well as to store and
                   8369: restore data specific to a certain instance of for example a problem.
                   8370: 
                   8371: =head2 Storing And Retrieving Data
                   8372: 
                   8373: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8374: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8375: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8376: is is the non-critical message twin of cstore. These functions are for
                   8377: handlers to store a perl hash to a user's permanent data space in an
                   8378: easy manner, and to retrieve it again on another call. It is expected
                   8379: that a handler would use this once at the beginning to retrieve data,
                   8380: and then again once at the end to send only the new data back.
                   8381: 
                   8382: The data is stored in the user's data directory on the user's
                   8383: homeserver under the ID of the course.
                   8384: 
                   8385: The hash that is returned by restore will have all of the previous
                   8386: value for all of the elements of the hash.
                   8387: 
                   8388: Example:
                   8389: 
                   8390:  #creating a hash
                   8391:  my %hash;
                   8392:  $hash{'foo'}='bar';
                   8393: 
                   8394:  #storing it
                   8395:  &Apache::lonnet::cstore(\%hash);
                   8396: 
                   8397:  #changing a value
                   8398:  $hash{'foo'}='notbar';
                   8399: 
                   8400:  #adding a new value
                   8401:  $hash{'bar'}='foo';
                   8402:  &Apache::lonnet::cstore(\%hash);
                   8403: 
                   8404:  #retrieving the hash
                   8405:  my %history=&Apache::lonnet::restore();
                   8406: 
                   8407:  #print the hash
                   8408:  foreach my $key (sort(keys(%history))) {
                   8409:    print("\%history{$key} = $history{$key}");
                   8410:  }
                   8411: 
                   8412: Will print out:
1.191     harris41 8413: 
1.394     bowersj2 8414:  %history{1:foo} = bar
                   8415:  %history{1:keys} = foo:timestamp
                   8416:  %history{1:timestamp} = 990455579
                   8417:  %history{2:bar} = foo
                   8418:  %history{2:foo} = notbar
                   8419:  %history{2:keys} = foo:bar:timestamp
                   8420:  %history{2:timestamp} = 990455580
                   8421:  %history{bar} = foo
                   8422:  %history{foo} = notbar
                   8423:  %history{timestamp} = 990455580
                   8424:  %history{version} = 2
                   8425: 
                   8426: Note that the special hash entries C<keys>, C<version> and
                   8427: C<timestamp> were added to the hash. C<version> will be equal to the
                   8428: total number of versions of the data that have been stored. The
                   8429: C<timestamp> attribute will be the UNIX time the hash was
                   8430: stored. C<keys> is available in every historical section to list which
                   8431: keys were added or changed at a specific historical revision of a
                   8432: hash.
                   8433: 
                   8434: B<Warning>: do not store the hash that restore returns directly. This
                   8435: will cause a mess since it will restore the historical keys as if the
                   8436: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8437: 
1.394     bowersj2 8438: Calling convention:
1.191     harris41 8439: 
1.394     bowersj2 8440:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8441:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8442: 
1.394     bowersj2 8443: For more detailed information, see lonnet specific documentation.
1.191     harris41 8444: 
1.394     bowersj2 8445: =head1 RETURN MESSAGES
1.191     harris41 8446: 
1.394     bowersj2 8447: =over 4
1.191     harris41 8448: 
1.394     bowersj2 8449: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8450: 
1.394     bowersj2 8451: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8452: when the connection is brought back up
1.191     harris41 8453: 
1.394     bowersj2 8454: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8455: for later delivery
1.191     harris41 8456: 
1.394     bowersj2 8457: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8458: 
1.394     bowersj2 8459: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8460: that was requested
1.191     harris41 8461: 
1.243     albertel 8462: =back
1.191     harris41 8463: 
1.243     albertel 8464: =head1 PUBLIC SUBROUTINES
1.191     harris41 8465: 
1.243     albertel 8466: =head2 Session Environment Functions
1.191     harris41 8467: 
1.243     albertel 8468: =over 4
1.191     harris41 8469: 
1.394     bowersj2 8470: =item * 
                   8471: X<appenv()>
                   8472: B<appenv(%hash)>: the value of %hash is written to
                   8473: the user envirnoment file, and will be restored for each access this
1.620     albertel 8474: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8475: process
1.191     harris41 8476: 
                   8477: =item *
1.394     bowersj2 8478: X<delenv()>
                   8479: B<delenv($regexp)>: removes all items from the session
                   8480: environment file that matches the regular expression in $regexp. The
1.620     albertel 8481: values are also delted from the current processes %env.
1.191     harris41 8482: 
1.795     albertel 8483: =item * get_env_multiple($name) 
                   8484: 
                   8485: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8486: values may be defined and end up as an array ref.
                   8487: 
                   8488: returns an array of values
                   8489: 
1.243     albertel 8490: =back
                   8491: 
                   8492: =head2 User Information
1.191     harris41 8493: 
1.243     albertel 8494: =over 4
1.191     harris41 8495: 
                   8496: =item *
1.394     bowersj2 8497: X<queryauthenticate()>
                   8498: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8499: authentication scheme
                   8500: 
                   8501: =item *
1.394     bowersj2 8502: X<authenticate()>
                   8503: B<authenticate($uname,$upass,$udom)>: try to
                   8504: authenticate user from domain's lib servers (first use the current
                   8505: one). C<$upass> should be the users password.
1.191     harris41 8506: 
                   8507: =item *
1.394     bowersj2 8508: X<homeserver()>
                   8509: B<homeserver($uname,$udom)>: find the server which has
                   8510: the user's directory and files (there must be only one), this caches
                   8511: the answer, and also caches if there is a borken connection.
1.191     harris41 8512: 
                   8513: =item *
1.394     bowersj2 8514: X<idget()>
                   8515: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8516: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8517: username, and only 1 username per ID in a specific domain) (returns
                   8518: hash: id=>name,id=>name)
1.191     harris41 8519: 
                   8520: =item *
1.394     bowersj2 8521: X<idrget()>
                   8522: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8523: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8524: 
                   8525: =item *
1.394     bowersj2 8526: X<idput()>
                   8527: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8528: 
                   8529: =item *
1.394     bowersj2 8530: X<rolesinit()>
                   8531: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8532: 
                   8533: =item *
1.551     albertel 8534: X<getsection()>
                   8535: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8536: course $cname, return section name/number or '' for "not in course"
                   8537: and '-1' for "no section"
                   8538: 
                   8539: =item *
1.394     bowersj2 8540: X<userenvironment()>
                   8541: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8542: passed in @what from the requested user's environment, returns a hash
                   8543: 
1.858     raeburn  8544: =item * 
                   8545: X<userlog_query()>
1.859     albertel 8546: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8547: activity.log file. %filters defines filters applied when parsing the
                   8548: log file. These can be start or end timestamps, or the type of action
                   8549: - log to look for Login or Logout events, check for Checkin or
                   8550: Checkout, role for role selection. The response is in the form
                   8551: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8552: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8553: 
1.243     albertel 8554: =back
                   8555: 
                   8556: =head2 User Roles
                   8557: 
                   8558: =over 4
                   8559: 
                   8560: =item *
                   8561: 
1.810     raeburn  8562: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8563:  F: full access
                   8564:  U,I,K: authentication modes (cxx only)
                   8565:  '': forbidden
                   8566:  1: user needs to choose course
                   8567:  2: browse allowed
1.766     albertel 8568:  A: passphrase authentication needed
1.243     albertel 8569: 
                   8570: =item *
                   8571: 
                   8572: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8573: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8574: and course level
                   8575: 
                   8576: =item *
                   8577: 
                   8578: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8579: explanation of a user role term
                   8580: 
1.832     raeburn  8581: =item *
                   8582: 
1.858     raeburn  8583: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8584: All arguments are optional. Returns a hash of a roles, either for
                   8585: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8586: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8587: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8588: and value is set to colon-separated start and end times for the role.
                   8589: If no username and domain are specified, will default to current
                   8590: user/domain. Types, roles, and roledoms are references to arrays,
                   8591: of role statuses (active, future or previous), roles 
                   8592: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8593: to restrict the list of roles reported. If no array ref is 
                   8594: provided for types, will default to return only active roles.
1.834     albertel 8595: 
1.243     albertel 8596: =back
                   8597: 
                   8598: =head2 User Modification
                   8599: 
                   8600: =over 4
                   8601: 
                   8602: =item *
                   8603: 
                   8604: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8605: user for the level given by URL.  Optional start and end dates (leave empty
                   8606: string or zero for "no date")
1.191     harris41 8607: 
                   8608: =item *
                   8609: 
1.243     albertel 8610: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8611: change a users, password, possible return values are: ok,
                   8612: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8613: refused
1.191     harris41 8614: 
                   8615: =item *
                   8616: 
1.243     albertel 8617: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8618: 
                   8619: =item *
                   8620: 
1.243     albertel 8621: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8622: modify user
1.191     harris41 8623: 
                   8624: =item *
                   8625: 
1.286     matthew  8626: modifystudent
                   8627: 
                   8628: modify a students enrollment and identification information.
                   8629: The course id is resolved based on the current users environment.  
                   8630: This means the envoking user must be a course coordinator or otherwise
                   8631: associated with a course.
                   8632: 
1.297     matthew  8633: This call is essentially a wrapper for lonnet::modifyuser and
                   8634: lonnet::modify_student_enrollment
1.286     matthew  8635: 
                   8636: Inputs: 
                   8637: 
                   8638: =over 4
                   8639: 
                   8640: =item B<$udom> Students loncapa domain
                   8641: 
                   8642: =item B<$uname> Students loncapa login name
                   8643: 
                   8644: =item B<$uid> Students id/student number
                   8645: 
                   8646: =item B<$umode> Students authentication mode
                   8647: 
                   8648: =item B<$upass> Students password
                   8649: 
                   8650: =item B<$first> Students first name
                   8651: 
                   8652: =item B<$middle> Students middle name
                   8653: 
                   8654: =item B<$last> Students last name
                   8655: 
                   8656: =item B<$gene> Students generation
                   8657: 
                   8658: =item B<$usec> Students section in course
                   8659: 
                   8660: =item B<$end> Unix time of the roles expiration
                   8661: 
                   8662: =item B<$start> Unix time of the roles start date
                   8663: 
                   8664: =item B<$forceid> If defined, allow $uid to be changed
                   8665: 
                   8666: =item B<$desiredhome> server to use as home server for student
                   8667: 
                   8668: =back
1.297     matthew  8669: 
                   8670: =item *
                   8671: 
                   8672: modify_student_enrollment
                   8673: 
                   8674: Change a students enrollment status in a class.  The environment variable
                   8675: 'role.request.course' must be defined for this function to proceed.
                   8676: 
                   8677: Inputs:
                   8678: 
                   8679: =over 4
                   8680: 
                   8681: =item $udom, students domain
                   8682: 
                   8683: =item $uname, students name
                   8684: 
                   8685: =item $uid, students user id
                   8686: 
                   8687: =item $first, students first name
                   8688: 
                   8689: =item $middle
                   8690: 
                   8691: =item $last
                   8692: 
                   8693: =item $gene
                   8694: 
                   8695: =item $usec
                   8696: 
                   8697: =item $end
                   8698: 
                   8699: =item $start
                   8700: 
                   8701: =back
                   8702: 
1.191     harris41 8703: 
                   8704: =item *
                   8705: 
1.243     albertel 8706: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8707: custom role; give a custom role to a user for the level given by URL.  Specify
                   8708: name and domain of role author, and role name
1.191     harris41 8709: 
                   8710: =item *
                   8711: 
1.243     albertel 8712: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8713: 
                   8714: =item *
                   8715: 
1.243     albertel 8716: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8717: 
                   8718: =back
                   8719: 
                   8720: =head2 Course Infomation
                   8721: 
                   8722: =over 4
1.191     harris41 8723: 
                   8724: =item *
                   8725: 
1.631     albertel 8726: coursedescription($courseid) : returns a hash of information about the
                   8727: specified course id, including all environment settings for the
                   8728: course, the description of the course will be in the hash under the
                   8729: key 'description'
1.191     harris41 8730: 
                   8731: =item *
                   8732: 
1.624     albertel 8733: resdata($name,$domain,$type,@which) : request for current parameter
                   8734: setting for a specific $type, where $type is either 'course' or 'user',
                   8735: @what should be a list of parameters to ask about. This routine caches
                   8736: answers for 5 minutes.
1.243     albertel 8737: 
1.877     foxr     8738: =item *
                   8739: 
                   8740: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8741: data base, returning a hash that is keyed by the resource name and has
                   8742: values that are the resource value.  I believe that the timestamps and
                   8743: versions are also returned.
                   8744: 
                   8745: 
1.243     albertel 8746: =back
                   8747: 
                   8748: =head2 Course Modification
                   8749: 
                   8750: =over 4
1.191     harris41 8751: 
                   8752: =item *
                   8753: 
1.243     albertel 8754: writecoursepref($courseid,%prefs) : write preferences (environment
                   8755: database) for a course
1.191     harris41 8756: 
                   8757: =item *
                   8758: 
1.243     albertel 8759: createcourse($udom,$description,$url) : make/modify course
                   8760: 
                   8761: =back
                   8762: 
                   8763: =head2 Resource Subroutines
                   8764: 
                   8765: =over 4
1.191     harris41 8766: 
                   8767: =item *
                   8768: 
1.243     albertel 8769: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8770: 
                   8771: =item *
                   8772: 
1.243     albertel 8773: repcopy($filename) : subscribes to the requested file, and attempts to
                   8774: replicate from the owning library server, Might return
1.607     raeburn  8775: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8776: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8777: resource. Expects the local filesystem pathname
                   8778: (/home/httpd/html/res/....)
                   8779: 
                   8780: =back
                   8781: 
                   8782: =head2 Resource Information
                   8783: 
                   8784: =over 4
1.191     harris41 8785: 
                   8786: =item *
                   8787: 
1.243     albertel 8788: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8789: a vairety of different possible values, $varname should be a request
                   8790: string, and the other parameters can be used to specify who and what
                   8791: one is asking about.
                   8792: 
                   8793: Possible values for $varname are environment.lastname (or other item
                   8794: from the envirnment hash), user.name (or someother aspect about the
                   8795: user), resource.0.maxtries (or some other part and parameter of a
                   8796: resource)
1.204     albertel 8797: 
                   8798: =item *
                   8799: 
1.243     albertel 8800: directcondval($number) : get current value of a condition; reads from a state
                   8801: string
1.204     albertel 8802: 
                   8803: =item *
                   8804: 
1.243     albertel 8805: condval($condidx) : value of condition index based on state
1.204     albertel 8806: 
                   8807: =item *
                   8808: 
1.243     albertel 8809: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8810: resource's metadata, $what should be either a specific key, or either
                   8811: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8812: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8813: 
                   8814: this function automatically caches all requests
1.191     harris41 8815: 
                   8816: =item *
                   8817: 
1.243     albertel 8818: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8819: network of library servers; returns file handle of where SQL and regex results
                   8820: will be stored for query
1.191     harris41 8821: 
                   8822: =item *
                   8823: 
1.243     albertel 8824: symbread($filename) : return symbolic list entry (filename argument optional);
                   8825: returns the data handle
1.191     harris41 8826: 
                   8827: =item *
                   8828: 
1.243     albertel 8829: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8830: a possible symb for the URL in $thisfn, and if is an encryypted
                   8831: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8832: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8833: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8834: 
1.191     harris41 8835: 
                   8836: =item *
                   8837: 
1.243     albertel 8838: symbclean($symb) : removes versions numbers from a symb, returns the
                   8839: cleaned symb
1.191     harris41 8840: 
                   8841: =item *
                   8842: 
1.243     albertel 8843: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8844: course map, user must be in a course for it to work.
1.191     harris41 8845: 
                   8846: =item *
                   8847: 
1.243     albertel 8848: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8849: 
                   8850: =item *
                   8851: 
1.243     albertel 8852: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8853: a random seed, all arguments are optional, if they aren't sent it uses the
                   8854: environment to derive them. Note: if symb isn't sent and it can't get one
                   8855: from &symbread it will use the current time as its return value
1.191     harris41 8856: 
                   8857: =item *
                   8858: 
1.243     albertel 8859: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8860: unfakeable, receipt
1.191     harris41 8861: 
                   8862: =item *
                   8863: 
1.620     albertel 8864: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8865: 
                   8866: =item *
                   8867: 
1.243     albertel 8868: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8869: 
                   8870: =item *
                   8871: 
1.243     albertel 8872: 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 8873: 
                   8874: =item *
                   8875: 
1.243     albertel 8876: 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 8877: 
                   8878: =item *
                   8879: 
1.243     albertel 8880: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8881: 
                   8882: =item *
                   8883: 
1.243     albertel 8884: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8885: forcing spreadsheet to reevaluate the resource scores next time.
                   8886: 
                   8887: =back
                   8888: 
                   8889: =head2 Storing/Retreiving Data
                   8890: 
                   8891: =over 4
1.191     harris41 8892: 
                   8893: =item *
                   8894: 
1.243     albertel 8895: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8896: for this url; hashref needs to be given and should be a \%hashname; the
                   8897: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8898: be derived from the env
1.191     harris41 8899: 
                   8900: =item *
                   8901: 
1.243     albertel 8902: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8903: uses critical subroutine
1.191     harris41 8904: 
                   8905: =item *
                   8906: 
1.243     albertel 8907: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8908: all args are optional
1.191     harris41 8909: 
                   8910: =item *
                   8911: 
1.717     albertel 8912: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8913: dumps the complete (or key matching regexp) namespace into a hash
                   8914: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8915: normally &store()ed into
                   8916: 
                   8917: $range should be either an integer '100' (give me the first 100
                   8918:                                            matching records)
                   8919:               or be  two integers sperated by a - with no spaces
                   8920:                  '30-50' (give me the 30th through the 50th matching
                   8921:                           records)
                   8922: 
                   8923: 
                   8924: =item *
                   8925: 
                   8926: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8927: replaces a &store() version of data with a replacement set of data
                   8928: for a particular resource in a namespace passed in the $storehash hash 
                   8929: reference
                   8930: 
                   8931: =item *
                   8932: 
1.243     albertel 8933: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8934: works very similar to store/cstore, but all data is stored in a
                   8935: temporary location and can be reset using tmpreset, $storehash should
                   8936: be a hash reference, returns nothing on success
1.191     harris41 8937: 
                   8938: =item *
                   8939: 
1.243     albertel 8940: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8941: similar to restore, but all data is stored in a temporary location and
                   8942: can be reset using tmpreset. Returns a hash of values on success,
                   8943: error string otherwise.
1.191     harris41 8944: 
                   8945: =item *
                   8946: 
1.243     albertel 8947: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8948: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8949: 
                   8950: =item *
                   8951: 
1.243     albertel 8952: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8953: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8954: 
                   8955: =item *
                   8956: 
1.243     albertel 8957: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8958: namesp ($udom and $uname are optional)
1.191     harris41 8959: 
                   8960: =item *
                   8961: 
1.702     albertel 8962: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8963: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8964: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8965: 
1.702     albertel 8966: $range should be either an integer '100' (give me the first 100
                   8967:                                            matching records)
                   8968:               or be  two integers sperated by a - with no spaces
                   8969:                  '30-50' (give me the 30th through the 50th matching
                   8970:                           records)
1.449     matthew  8971: =item *
                   8972: 
                   8973: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8974: $store can be a scalar, an array reference, or if the amount to be 
                   8975: incremented is > 1, a hash reference.
                   8976: 
                   8977: ($udom and $uname are optional)
1.191     harris41 8978: 
                   8979: =item *
                   8980: 
1.243     albertel 8981: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8982: ($udom and $uname are optional)
1.191     harris41 8983: 
                   8984: =item *
                   8985: 
1.243     albertel 8986: cput($namespace,$storehash,$udom,$uname) : critical put
                   8987: ($udom and $uname are optional)
1.191     harris41 8988: 
                   8989: =item *
                   8990: 
1.748     albertel 8991: newput($namespace,$storehash,$udom,$uname) :
                   8992: 
                   8993: Attempts to store the items in the $storehash, but only if they don't
                   8994: currently exist, if this succeeds you can be certain that you have 
                   8995: successfully created a new key value pair in the $namespace db.
                   8996: 
                   8997: 
                   8998: Args:
                   8999:  $namespace: name of database to store values to
                   9000:  $storehash: hashref to store to the db
                   9001:  $udom: (optional) domain of user containing the db
                   9002:  $uname: (optional) name of user caontaining the db
                   9003: 
                   9004: Returns:
                   9005:  'ok' -> succeeded in storing all keys of $storehash
                   9006:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9007:                         least <key> already existed in the db (other
                   9008:                         requested keys may also already exist)
                   9009:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9010:  'con_lost' -> unable to contact request server
                   9011:  'refused' -> action was not allowed by remote machine
                   9012: 
                   9013: 
                   9014: =item *
                   9015: 
1.243     albertel 9016: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9017: reference filled in from namesp (encrypts the return communication)
                   9018: ($udom and $uname are optional)
1.191     harris41 9019: 
                   9020: =item *
                   9021: 
1.243     albertel 9022: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9023: critical subroutine
                   9024: 
1.806     raeburn  9025: =item *
                   9026: 
1.860     raeburn  9027: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9028: array reference filled in from namespace found in domain level on either
                   9029: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9030: 
                   9031: =item *
                   9032: 
1.860     raeburn  9033: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9034: domain level either on specified domain server ($uhome) or primary domain 
                   9035: server ($udom and $uhome are optional)
1.806     raeburn  9036: 
1.243     albertel 9037: =back
                   9038: 
                   9039: =head2 Network Status Functions
                   9040: 
                   9041: =over 4
1.191     harris41 9042: 
                   9043: =item *
                   9044: 
                   9045: dirlist($uri) : return directory list based on URI
                   9046: 
                   9047: =item *
                   9048: 
1.243     albertel 9049: spareserver() : find server with least workload from spare.tab
                   9050: 
                   9051: =back
                   9052: 
                   9053: =head2 Apache Request
                   9054: 
                   9055: =over 4
1.191     harris41 9056: 
                   9057: =item *
                   9058: 
1.243     albertel 9059: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9060: localhost, posts hash
                   9061: 
                   9062: =back
                   9063: 
                   9064: =head2 Data to String to Data
                   9065: 
                   9066: =over 4
1.191     harris41 9067: 
                   9068: =item *
                   9069: 
1.243     albertel 9070: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9071: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9072: 
                   9073: =item *
                   9074: 
1.243     albertel 9075: hashref2str($hashref) : convert a hashref into a string complete with
                   9076: escaping and '=' and '&' separators, supports elements that are
                   9077: arrayrefs and hashrefs
1.191     harris41 9078: 
                   9079: =item *
                   9080: 
1.243     albertel 9081: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9082: with escaping and '&' separators, supports elements that are arrayrefs
                   9083: and hashrefs
1.191     harris41 9084: 
                   9085: =item *
                   9086: 
1.243     albertel 9087: str2hash($string) : convert string to hash using unescaping and
                   9088: splitting on '=' and '&', supports elements that are arrayrefs and
                   9089: hashrefs
1.191     harris41 9090: 
                   9091: =item *
                   9092: 
1.243     albertel 9093: str2array($string) : convert string to hash using unescaping and
                   9094: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9095: 
                   9096: =back
                   9097: 
                   9098: =head2 Logging Routines
                   9099: 
                   9100: =over 4
                   9101: 
                   9102: These routines allow one to make log messages in the lonnet.log and
                   9103: lonnet.perm logfiles.
1.191     harris41 9104: 
                   9105: =item *
                   9106: 
1.243     albertel 9107: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9108: 
                   9109: =item *
                   9110: 
1.243     albertel 9111: logthis() : append message to the normal lonnet.log file, it gets
                   9112: preiodically rolled over and deleted.
1.191     harris41 9113: 
                   9114: =item *
                   9115: 
1.243     albertel 9116: logperm() : append a permanent message to lonnet.perm.log, this log
                   9117: file never gets deleted by any automated portion of the system, only
                   9118: messages of critical importance should go in here.
                   9119: 
                   9120: =back
                   9121: 
                   9122: =head2 General File Helper Routines
                   9123: 
                   9124: =over 4
1.191     harris41 9125: 
                   9126: =item *
                   9127: 
1.481     raeburn  9128: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9129: (a) files in /uploaded
                   9130:   (i) If a local copy of the file exists - 
                   9131:       compares modification date of local copy with last-modified date for 
                   9132:       definitive version stored on home server for course. If local copy is 
                   9133:       stale, requests a new version from the home server and stores it. 
                   9134:       If the original has been removed from the home server, then local copy 
                   9135:       is unlinked.
                   9136:   (ii) If local copy does not exist -
                   9137:       requests the file from the home server and stores it. 
                   9138:   
                   9139:   If $caller is 'uploadrep':  
                   9140:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9141:     for request for files originally uploaded via DOCS. 
                   9142:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9143:   
                   9144:   Otherwise:
                   9145:      This indicates a call from the content generation phase of the request.
                   9146:      -  returns the entire contents of the file or -1.
                   9147:      
                   9148: (b) files in /res
                   9149:    - returns the entire contents of a file or -1; 
                   9150:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9151: 
1.712     albertel 9152: 
                   9153: =item *
                   9154: 
                   9155: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9156:                   reference
                   9157: 
                   9158: returns either a stat() list of data about the file or an empty list
                   9159: if the file doesn't exist or couldn't find out about it (connection
                   9160: problems or user unknown)
                   9161: 
1.191     harris41 9162: =item *
                   9163: 
1.243     albertel 9164: filelocation($dir,$file) : returns file system location of a file
                   9165: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9166: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9167: and a file of ../bob will become /a/bob)
1.191     harris41 9168: 
                   9169: =item *
                   9170: 
                   9171: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9172: filelocation except for hrefs
                   9173: 
                   9174: =item *
                   9175: 
                   9176: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9177: 
1.243     albertel 9178: =back
                   9179: 
1.608     albertel 9180: =head2 Usererfile file routines (/uploaded*)
                   9181: 
                   9182: =over 4
                   9183: 
                   9184: =item *
                   9185: 
                   9186: userfileupload(): main rotine for putting a file in a user or course's
                   9187:                   filespace, arguments are,
                   9188: 
1.620     albertel 9189:  formname - required - this is the name of the element in $env where the
1.608     albertel 9190:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9191:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9192:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9193:  coursedoc - if true, store the file in the course of the active role
                   9194:              of the current user
                   9195:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9196:          if undefined, it will be placed in "unknown"
                   9197: 
                   9198:  (This routine calls clean_filename() to remove any dangerous
                   9199:  characters from the filename, and then calls finuserfileupload() to
                   9200:  complete the transaction)
                   9201: 
                   9202:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9203:  and /adm/notfound.html if unsuccessful
                   9204: 
                   9205: =item *
                   9206: 
                   9207: clean_filename(): routine for cleaing a filename up for storage in
                   9208:                  userfile space, argument is:
                   9209: 
                   9210:  filename - proposed filename
                   9211: 
                   9212: returns: the new clean filename
                   9213: 
                   9214: =item *
                   9215: 
                   9216: finishuserfileupload(): routine that creaes and sends the file to
                   9217: userspace, probably shouldn't be called directly
                   9218: 
                   9219:   docuname: username or courseid of destination for the file
                   9220:   docudom: domain of user/course of destination for the file
                   9221:   formname: same as for userfileupload()
                   9222:   fname: filename (inculding subdirectories) for the file
                   9223: 
                   9224:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9225:  and /adm/notfound.html if unsuccessful
                   9226: 
                   9227: =item *
                   9228: 
                   9229: renameuserfile(): renames an existing userfile to a new name
                   9230: 
                   9231:   Args:
                   9232:    docuname: username or courseid of destination for the file
                   9233:    docudom: domain of user/course of destination for the file
                   9234:    old: current file name (including any subdirs under userfiles)
                   9235:    new: desired file name (including any subdirs under userfiles)
                   9236: 
                   9237: =item *
                   9238: 
                   9239: mkdiruserfile(): creates a directory is a userfiles dir
                   9240: 
                   9241:   Args:
                   9242:    docuname: username or courseid of destination for the file
                   9243:    docudom: domain of user/course of destination for the file
                   9244:    dir: dir to create (including any subdirs under userfiles)
                   9245: 
                   9246: =item *
                   9247: 
                   9248: removeuserfile(): removes a file that exists in userfiles
                   9249: 
                   9250:   Args:
                   9251:    docuname: username or courseid of destination for the file
                   9252:    docudom: domain of user/course of destination for the file
                   9253:    fname: filname to delete (including any subdirs under userfiles)
                   9254: 
                   9255: =item *
                   9256: 
                   9257: removeuploadedurl(): convience function for removeuserfile()
                   9258: 
                   9259:   Args:
                   9260:    url:  a full /uploaded/... url to delete
                   9261: 
1.747     albertel 9262: =item * 
                   9263: 
                   9264: get_portfile_permissions():
                   9265:   Args:
                   9266:     domain: domain of user or course contain the portfolio files
                   9267:     user: name of user or num of course contain the portfolio files
                   9268:   Returns:
                   9269:     hashref of a dump of the proper file_permissions.db
                   9270:    
                   9271: 
                   9272: =item * 
                   9273: 
                   9274: get_access_controls():
                   9275: 
                   9276: Args:
                   9277:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9278:   group: (optional) the group you want the files associated with
                   9279:   file: (optional) the file you want access info on
                   9280: 
                   9281: Returns:
1.749     raeburn  9282:     a hash (keys are file names) of hashes containing
                   9283:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9284:         values are XML containing access control settings (see below) 
1.747     albertel 9285: 
                   9286: Internal notes:
                   9287: 
1.749     raeburn  9288:  access controls are stored in file_permissions.db as key=value pairs.
                   9289:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9290:         where scope -> public,guest,course,group,domains or users.
                   9291:               end -> UNIX time for end of access (0 -> no end date)
                   9292:               start -> UNIX time for start of access
                   9293: 
                   9294:     value -> XML description of access control
                   9295:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9296:             <start></start>
                   9297:             <end></end>
                   9298: 
                   9299:             <password></password>  for scope type = guest
                   9300: 
                   9301:             <domain></domain>     for scope type = course or group
                   9302:             <number></number>
                   9303:             <roles id="">
                   9304:              <role></role>
                   9305:              <access></access>
                   9306:              <section></section>
                   9307:              <group></group>
                   9308:             </roles>
                   9309: 
                   9310:             <dom></dom>         for scope type = domains
                   9311: 
                   9312:             <users>             for scope type = users
                   9313:              <user>
                   9314:               <uname></uname>
                   9315:               <udom></udom>
                   9316:              </user>
                   9317:             </users>
                   9318:            </scope> 
                   9319:               
                   9320:  Access data is also aggregated for each file in an additional key=value pair:
                   9321:  key -> path to file/file_name\0accesscontrol 
                   9322:  value -> reference to hash
                   9323:           hash contains key = value pairs
                   9324:           where key = uniqueID:scope_end_start
                   9325:                 value = UNIX time record was last updated
                   9326: 
                   9327:           Used to improve speed of look-ups of access controls for each file.  
                   9328:  
                   9329:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9330: 
                   9331: modify_access_controls():
                   9332: 
                   9333: Modifies access controls for a portfolio file
                   9334: Args
                   9335: 1. file name
                   9336: 2. reference to hash of required changes,
                   9337: 3. domain
                   9338: 4. username
                   9339:   where domain,username are the domain of the portfolio owner 
                   9340:   (either a user or a course) 
                   9341: 
                   9342: Returns:
                   9343: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9344: 2. result of deletions ('ok' or 'error', with error message).
                   9345: 3. reference to hash of any new or updated access controls.
                   9346: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9347:    key = integer (inbound ID)
                   9348:    value = uniqueID  
1.747     albertel 9349: 
1.608     albertel 9350: =back
                   9351: 
1.243     albertel 9352: =head2 HTTP Helper Routines
                   9353: 
                   9354: =over 4
                   9355: 
1.191     harris41 9356: =item *
                   9357: 
                   9358: escape() : unpack non-word characters into CGI-compatible hex codes
                   9359: 
                   9360: =item *
                   9361: 
                   9362: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9363: 
1.243     albertel 9364: =back
                   9365: 
                   9366: =head1 PRIVATE SUBROUTINES
                   9367: 
                   9368: =head2 Underlying communication routines (Shouldn't call)
                   9369: 
                   9370: =over 4
                   9371: 
                   9372: =item *
                   9373: 
                   9374: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9375: 
                   9376: =item *
                   9377: 
                   9378: reply() : uses subreply to send a message to remote machine, logs all failures
                   9379: 
                   9380: =item *
                   9381: 
                   9382: critical() : passes a critical message to another server; if cannot
                   9383: get through then place message in connection buffer directory and
                   9384: returns con_delayed, if incapable of saving message, returns
                   9385: con_failed
                   9386: 
                   9387: =item *
                   9388: 
                   9389: reconlonc() : tries to reconnect lonc client processes.
                   9390: 
                   9391: =back
                   9392: 
                   9393: =head2 Resource Access Logging
                   9394: 
                   9395: =over 4
                   9396: 
                   9397: =item *
                   9398: 
                   9399: flushcourselogs() : flush (save) buffer logs and access logs
                   9400: 
                   9401: =item *
                   9402: 
                   9403: courselog($what) : save message for course in hash
                   9404: 
                   9405: =item *
                   9406: 
                   9407: courseacclog($what) : save message for course using &courselog().  Perform
                   9408: special processing for specific resource types (problems, exams, quizzes, etc).
                   9409: 
1.191     harris41 9410: =item *
                   9411: 
                   9412: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9413: as a PerlChildExitHandler
1.243     albertel 9414: 
                   9415: =back
                   9416: 
                   9417: =head2 Other
                   9418: 
                   9419: =over 4
                   9420: 
                   9421: =item *
                   9422: 
                   9423: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9424: 
                   9425: =back
                   9426: 
                   9427: =cut
1.877     foxr     9428: 

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