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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.903   ! albertel    4: # $Id: lonnet.pm,v 1.902 2007/07/28 21:14:09 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.891     albertel  217:     my ($lonid) = @_;
                    218:     my $hostname = &hostname($lonid);
                    219:     if ($lonid) {
                    220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    221: 	if ($hostname && -e $peerfile) {
                    222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    224: 					     Type    => SOCK_STREAM,
                    225: 					     Timeout => 10);
                    226: 	    if ($client) {
                    227: 		print $client ("reset_retries\n");
                    228: 		my $answer=<$client>;
                    229: 		#reset just this one.
                    230: 	    }
                    231: 	}
                    232: 	return;
                    233:     }
                    234: 
1.836     www       235:     &logthis("Trying to reconnect lonc");
1.1       albertel  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  237:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  238: 	my $loncpid=<$fh>;
                    239:         chomp($loncpid);
                    240:         if (kill 0 => $loncpid) {
                    241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    242:             kill USR1 => $loncpid;
                    243:             sleep 1;
1.836     www       244:          } else {
1.12      www       245: 	    &logthis(
1.672     albertel  246:                "<font color=\"blue\">WARNING:".
1.12      www       247:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  248:         }
                    249:     } else {
1.836     www       250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  251:     }
                    252: }
                    253: 
                    254: # ------------------------------------------------------ Critical communication
1.12      www       255: 
1.1       albertel  256: sub critical {
                    257:     my ($cmd,$server)=@_;
1.838     albertel  258:     unless (&hostname($server)) {
1.672     albertel  259:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       260:                " Critical message to unknown server ($server)</font>");
                    261:         return 'no_such_host';
                    262:     }
1.1       albertel  263:     my $answer=reply($cmd,$server);
                    264:     if ($answer eq 'con_lost') {
                    265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  266: 	my $answer=reply($cmd,$server);
1.1       albertel  267:         if ($answer eq 'con_lost') {
                    268:             my $now=time;
                    269:             my $middlename=$cmd;
1.5       www       270:             $middlename=substr($middlename,0,16);
1.1       albertel  271:             $middlename=~s/\W//g;
                    272:             my $dfilename=
1.305     www       273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    274:             $dumpcount++;
1.1       albertel  275:             {
1.448     albertel  276: 		my $dfh;
                    277: 		if (open($dfh,">$dfilename")) {
                    278: 		    print $dfh "$cmd\n"; 
                    279: 		    close($dfh);
                    280: 		}
1.1       albertel  281:             }
                    282:             sleep 2;
                    283:             my $wcmd='';
                    284:             {
1.448     albertel  285: 		my $dfh;
                    286: 		if (open($dfh,"<$dfilename")) {
                    287: 		    $wcmd=<$dfh>; 
                    288: 		    close($dfh);
                    289: 		}
1.1       albertel  290:             }
                    291:             chomp($wcmd);
1.7       www       292:             if ($wcmd eq $cmd) {
1.672     albertel  293: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       294:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  295:                 &logperm("D:$server:$cmd");
                    296: 	        return 'con_delayed';
                    297:             } else {
1.672     albertel  298:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       299:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  300:                 &logperm("F:$server:$cmd");
                    301:                 return 'con_failed';
                    302:             }
                    303:         }
                    304:     }
                    305:     return $answer;
1.405     albertel  306: }
                    307: 
1.755     albertel  308: # ------------------------------------------- check if return value is an error
                    309: 
                    310: sub error {
                    311:     my ($result) = @_;
1.756     albertel  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  313: 	if ($2 == 2) { return undef; }
                    314: 	return $1;
                    315:     }
                    316:     return undef;
                    317: }
                    318: 
1.783     albertel  319: sub convert_and_load_session_env {
                    320:     my ($lonidsdir,$handle)=@_;
                    321:     my @profile;
                    322:     {
                    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');
                    864:     if ($homeserver ne '') {
                    865:         my $response=&reply("instdirsrch:$udom".':'.
                    866:                             &escape($srch->{'srchby'}).':'.
                    867:                             &escape($srch->{'srchterm'}).':'.
                    868:                             $srch->{'srchtype'},$homeserver);
1.900     albertel  869:         if ($response ne 'refused') {
1.901     albertel  870:             my @matches = split(/&/,$response);
1.899     raeburn   871:             foreach my $match (@matches) {
                    872:                 my ($key,$value) = split(/=/,$match);
                    873:                 my %userhash = &str2hash(&unescape($value));
                    874:                 $results{&unescape($key).':'.$udom} = \%userhash;
                    875:             }
                    876:         }
                    877:     }
                    878:     return %results;
                    879: }
                    880: 
                    881: sub usersearch {
                    882:     my ($srch) = @_;
                    883:     my $dom = $srch->{'srchdomain'};
                    884:     my %results;
                    885:     my %libserv = &all_library();
                    886:     my $query = 'usersearch';
                    887:     foreach my $tryserver (keys(%libserv)) {
                    888:         if (&host_domain($tryserver) eq $dom) {
                    889:             my $host=&hostname($tryserver);
                    890:             my $queryid=
                    891:                 &reply("querysend:".&escape($query).':'.&escape($dom).':'.
                    892:                        &escape($srch->{'srchby'}).'%%'.
                    893:                        &escape($srch->{'srchtype'}).':'.
                    894:                        &escape($srch->{'srchterm'}),$tryserver);
                    895:             if ($queryid !~/^\Q$host\E\_/) {
                    896:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   897:                 next;
1.899     raeburn   898:             }
                    899:             my $reply = &get_query_reply($queryid);
                    900:             my $maxtries = 1;
                    901:             my $tries = 1;
                    902:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    903:                 $reply = &get_query_reply($queryid);
                    904:                 $tries ++;
                    905:             }
                    906:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    907:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    908:             } else {
1.900     albertel  909:                 my @matches = split(/&/,$reply);
1.899     raeburn   910:                 foreach my $match (@matches) {
                    911:                     my @items = split(/:/,$match);
                    912:                     my ($uname,$udom,%userhash);
                    913:                     foreach my $entry (@items) {
                    914:                         my ($key,$value) = split(/=/,$entry);
                    915:                         $key = &unescape($key);
                    916:                         $value = &unescape($value);
                    917:                         $userhash{$key} = $value;
                    918:                         if ($key eq 'username') {
                    919:                             $uname = $value;
                    920:                         } elsif ($key eq 'domain') {
                    921:                             $udom = $value;
                    922:                         } 
                    923:                     }
                    924:                     $results{$uname.':'.$udom} = \%userhash;
                    925:                 }
                    926:             }
                    927:         }
                    928:     }
                    929:     return %results;
                    930: }
                    931: 
1.344     www       932: # --------------------------------------------------- Assign a key to a student
                    933: 
                    934: sub assign_access_key {
1.364     www       935: #
                    936: # a valid key looks like uname:udom#comments
                    937: # comments are being appended
                    938: #
1.498     www       939:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    940:     $kdom=
1.620     albertel  941:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       942:     $knum=
1.620     albertel  943:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       944:     $cdom=
1.620     albertel  945:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       946:     $cnum=
1.620     albertel  947:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    948:     $udom=$env{'user.name'} unless (defined($udom));
                    949:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       950:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       951:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  952:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       953:                                                   # assigned to this person
                    954:                                                   # - this should not happen,
1.345     www       955:                                                   # unless something went wrong
                    956:                                                   # the first time around
                    957: # ready to assign
1.364     www       958:         $logentry=$1.'; '.$logentry;
1.496     www       959:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       960:                                                  $kdom,$knum) eq 'ok') {
1.345     www       961: # key now belongs to user
1.346     www       962: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       963:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    964:                 &appenv('environment.'.$envkey => $ckey);
                    965:                 return 'ok';
                    966:             } else {
                    967:                 return 
                    968:   'error: Count not permanently assign key, will need to be re-entered later.';
                    969: 	    }
                    970:         } else {
                    971:             return 'error: Could not assign key, try again later.';
                    972:         }
1.364     www       973:     } elsif (!$existing{$ckey}) {
1.345     www       974: # the key does not exist
                    975: 	return 'error: The key does not exist';
                    976:     } else {
                    977: # the key is somebody else's
                    978: 	return 'error: The key is already in use';
                    979:     }
1.344     www       980: }
                    981: 
1.364     www       982: # ------------------------------------------ put an additional comment on a key
                    983: 
                    984: sub comment_access_key {
                    985: #
                    986: # a valid key looks like uname:udom#comments
                    987: # comments are being appended
                    988: #
                    989:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    990:     $cdom=
1.620     albertel  991:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       992:     $cnum=
1.620     albertel  993:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       994:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    995:     if ($existing{$ckey}) {
                    996:         $existing{$ckey}.='; '.$logentry;
                    997: # ready to assign
1.367     www       998:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       999:                                                  $cdom,$cnum) eq 'ok') {
                   1000: 	    return 'ok';
                   1001:         } else {
                   1002: 	    return 'error: Count not store comment.';
                   1003:         }
                   1004:     } else {
                   1005: # the key does not exist
                   1006: 	return 'error: The key does not exist';
                   1007:     }
                   1008: }
                   1009: 
1.344     www      1010: # ------------------------------------------------------ Generate a set of keys
                   1011: 
                   1012: sub generate_access_keys {
1.364     www      1013:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1014:     $cdom=
1.620     albertel 1015:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1016:     $cnum=
1.620     albertel 1017:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1018:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1019:     unless (($cdom) && ($cnum)) { return 0; }
                   1020:     if ($number>10000) { return 0; }
                   1021:     sleep(2); # make sure don't get same seed twice
                   1022:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1023:     my $total=0;
                   1024:     for (my $i=1;$i<=$number;$i++) {
                   1025:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1026:                   sprintf("%lx",int(100000*rand)).'-'.
                   1027:                   sprintf("%lx",int(100000*rand));
                   1028:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1029:        $newkey=~s/0/h/g; # and also 0 and O
                   1030:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1031:        if ($existing{$newkey}) {
                   1032:            $i--;
                   1033:        } else {
1.364     www      1034: 	  if (&put('accesskeys',
                   1035:               { $newkey => '# generated '.localtime().
1.620     albertel 1036:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1037:                            '; '.$logentry },
                   1038: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1039:               $total++;
                   1040: 	  }
                   1041:        }
                   1042:     }
1.620     albertel 1043:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1044:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1045:     return $total;
                   1046: }
                   1047: 
                   1048: # ------------------------------------------------------- Validate an accesskey
                   1049: 
                   1050: sub validate_access_key {
                   1051:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1052:     $cdom=
1.620     albertel 1053:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1054:     $cnum=
1.620     albertel 1055:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1056:     $udom=$env{'user.domain'} unless (defined($udom));
                   1057:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1058:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1059:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1060: }
                   1061: 
                   1062: # ------------------------------------- Find the section of student in a course
1.652     albertel 1063: sub devalidate_getsection_cache {
                   1064:     my ($udom,$unam,$courseid)=@_;
                   1065:     my $hashid="$udom:$unam:$courseid";
                   1066:     &devalidate_cache_new('getsection',$hashid);
                   1067: }
1.298     matthew  1068: 
1.815     albertel 1069: sub courseid_to_courseurl {
                   1070:     my ($courseid) = @_;
                   1071:     #already url style courseid
                   1072:     return $courseid if ($courseid =~ m{^/});
                   1073: 
                   1074:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1075: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1076: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1077: 	return "/$cdom/$cnum";
                   1078:     }
                   1079: 
                   1080:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1081:     if (exists($courseinfo{'num'})) {
                   1082: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1083:     }
                   1084: 
                   1085:     return undef;
                   1086: }
                   1087: 
1.298     matthew  1088: sub getsection {
                   1089:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1090:     my $cachetime=1800;
1.551     albertel 1091: 
                   1092:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1093:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1094:     if (defined($cached)) { return $result; }
                   1095: 
1.298     matthew  1096:     my %Pending; 
                   1097:     my %Expired;
                   1098:     #
                   1099:     # Each role can either have not started yet (pending), be active, 
                   1100:     #    or have expired.
                   1101:     #
                   1102:     # If there is an active role, we are done.
                   1103:     #
                   1104:     # If there is more than one role which has not started yet, 
                   1105:     #     choose the one which will start sooner
                   1106:     # If there is one role which has not started yet, return it.
                   1107:     #
                   1108:     # If there is more than one expired role, choose the one which ended last.
                   1109:     # If there is a role which has expired, return it.
                   1110:     #
1.815     albertel 1111:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1112:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1113:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1114:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1115:         my $section=$1;
                   1116:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1117:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1118:         my $now=time;
1.548     albertel 1119:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1120:             $Expired{$end}=$section;
                   1121:             next;
                   1122:         }
1.548     albertel 1123:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1124:             $Pending{$start}=$section;
                   1125:             next;
                   1126:         }
1.599     albertel 1127:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1128:     }
                   1129:     #
                   1130:     # Presumedly there will be few matching roles from the above
                   1131:     # loop and the sorting time will be negligible.
                   1132:     if (scalar(keys(%Pending))) {
                   1133:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1134:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1135:     } 
                   1136:     if (scalar(keys(%Expired))) {
                   1137:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1138:         my $time = pop(@sorted);
1.599     albertel 1139:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1140:     }
1.599     albertel 1141:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1142: }
1.70      www      1143: 
1.599     albertel 1144: sub save_cache {
                   1145:     &purge_remembered();
1.722     albertel 1146:     #&Apache::loncommon::validate_page();
1.620     albertel 1147:     undef(%env);
1.780     albertel 1148:     undef($env_loaded);
1.599     albertel 1149: }
1.452     albertel 1150: 
1.599     albertel 1151: my $to_remember=-1;
                   1152: my %remembered;
                   1153: my %accessed;
                   1154: my $kicks=0;
                   1155: my $hits=0;
1.849     albertel 1156: sub make_key {
                   1157:     my ($name,$id) = @_;
1.872     albertel 1158:     if (length($id) > 65 
                   1159: 	&& length(&escape($id)) > 200) {
                   1160: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1161:     }
1.849     albertel 1162:     return &escape($name.':'.$id);
                   1163: }
                   1164: 
1.599     albertel 1165: sub devalidate_cache_new {
                   1166:     my ($name,$id,$debug) = @_;
                   1167:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1168:     $id=&make_key($name,$id);
1.599     albertel 1169:     $memcache->delete($id);
                   1170:     delete($remembered{$id});
                   1171:     delete($accessed{$id});
                   1172: }
                   1173: 
                   1174: sub is_cached_new {
                   1175:     my ($name,$id,$debug) = @_;
1.849     albertel 1176:     $id=&make_key($name,$id);
1.599     albertel 1177:     if (exists($remembered{$id})) {
                   1178: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1179: 	$accessed{$id}=[&gettimeofday()];
                   1180: 	$hits++;
                   1181: 	return ($remembered{$id},1);
                   1182:     }
                   1183:     my $value = $memcache->get($id);
                   1184:     if (!(defined($value))) {
                   1185: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1186: 	return (undef,undef);
1.416     albertel 1187:     }
1.599     albertel 1188:     if ($value eq '__undef__') {
                   1189: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1190: 	$value=undef;
                   1191:     }
                   1192:     &make_room($id,$value,$debug);
                   1193:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1194:     return ($value,1);
                   1195: }
                   1196: 
                   1197: sub do_cache_new {
                   1198:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1199:     $id=&make_key($name,$id);
1.599     albertel 1200:     my $setvalue=$value;
                   1201:     if (!defined($setvalue)) {
                   1202: 	$setvalue='__undef__';
                   1203:     }
1.623     albertel 1204:     if (!defined($time) ) {
                   1205: 	$time=600;
                   1206:     }
1.599     albertel 1207:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.872     albertel 1208:     if (!($memcache->set($id,$setvalue,$time))) {
                   1209: 	&logthis("caching of id -> $id  failed");
                   1210:     }
1.600     albertel 1211:     # need to make a copy of $value
                   1212:     #&make_room($id,$value,$debug);
1.599     albertel 1213:     return $value;
                   1214: }
                   1215: 
                   1216: sub make_room {
                   1217:     my ($id,$value,$debug)=@_;
                   1218:     $remembered{$id}=$value;
                   1219:     if ($to_remember<0) { return; }
                   1220:     $accessed{$id}=[&gettimeofday()];
                   1221:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1222:     my $to_kick;
                   1223:     my $max_time=0;
                   1224:     foreach my $other (keys(%accessed)) {
                   1225: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1226: 	    $to_kick=$other;
                   1227: 	    $max_time=&tv_interval($accessed{$other});
                   1228: 	}
                   1229:     }
                   1230:     delete($remembered{$to_kick});
                   1231:     delete($accessed{$to_kick});
                   1232:     $kicks++;
                   1233:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1234:     return;
                   1235: }
                   1236: 
1.599     albertel 1237: sub purge_remembered {
1.604     albertel 1238:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1239:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1240:     undef(%remembered);
                   1241:     undef(%accessed);
1.428     albertel 1242: }
1.70      www      1243: # ------------------------------------- Read an entry from a user's environment
                   1244: 
                   1245: sub userenvironment {
                   1246:     my ($udom,$unam,@what)=@_;
                   1247:     my %returnhash=();
                   1248:     my @answer=split(/\&/,
                   1249:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1250:                       &homeserver($unam,$udom)));
                   1251:     my $i;
                   1252:     for ($i=0;$i<=$#what;$i++) {
                   1253: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1254:     }
                   1255:     return %returnhash;
1.1       albertel 1256: }
                   1257: 
1.617     albertel 1258: # ---------------------------------------------------------- Get a studentphoto
                   1259: sub studentphoto {
                   1260:     my ($udom,$unam,$ext) = @_;
                   1261:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1262:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1263:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1264:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1265:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1266:             } else {
                   1267:                 my ($result,$perm_reqd)=
1.707     albertel 1268: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1269:                 if ($result eq 'ok') {
                   1270:                     if (!($perm_reqd eq 'yes')) {
                   1271:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1272:                     }
                   1273:                 }
                   1274:             }
                   1275:         }
                   1276:     } else {
                   1277:         my ($result,$perm_reqd) = 
1.707     albertel 1278: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1279:         if ($result eq 'ok') {
                   1280:             if (!($perm_reqd eq 'yes')) {
                   1281:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1282:             }
                   1283:         }
                   1284:     }
                   1285:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1286: }
                   1287: 
                   1288: sub retrievestudentphoto {
                   1289:     my ($udom,$unam,$ext,$type) = @_;
                   1290:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1291:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1292:     if ($ret eq 'ok') {
                   1293:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1294:         if ($type eq 'thumbnail') {
                   1295:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1296:         }
                   1297:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1298:         return $tokenurl;
                   1299:     } else {
                   1300:         if ($type eq 'thumbnail') {
                   1301:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1302:         } else { 
                   1303:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1304:         }
1.617     albertel 1305:     }
                   1306: }
                   1307: 
1.263     www      1308: # -------------------------------------------------------------------- New chat
                   1309: 
                   1310: sub chatsend {
1.724     raeburn  1311:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1312:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1313:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1314:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1315:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1316: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1317: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1318: }
                   1319: 
                   1320: # ------------------------------------------ Find current version of a resource
                   1321: 
                   1322: sub getversion {
                   1323:     my $fname=&clutter(shift);
                   1324:     unless ($fname=~/^\/res\//) { return -1; }
                   1325:     return &currentversion(&filelocation('',$fname));
                   1326: }
                   1327: 
                   1328: sub currentversion {
                   1329:     my $fname=shift;
1.599     albertel 1330:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1331:     if (defined($cached)) { return $result; }
1.292     www      1332:     my $author=$fname;
                   1333:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1334:     my ($udom,$uname)=split(/\//,$author);
                   1335:     my $home=homeserver($uname,$udom);
                   1336:     if ($home eq 'no_host') { 
                   1337:         return -1; 
                   1338:     }
                   1339:     my $answer=reply("currentversion:$fname",$home);
                   1340:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1341: 	return -1;
                   1342:     }
1.599     albertel 1343:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1344: }
                   1345: 
1.1       albertel 1346: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1347: 
1.1       albertel 1348: sub subscribe {
                   1349:     my $fname=shift;
1.761     raeburn  1350:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1351:     $fname=~s/[\n\r]//g;
1.1       albertel 1352:     my $author=$fname;
                   1353:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1354:     my ($udom,$uname)=split(/\//,$author);
                   1355:     my $home=homeserver($uname,$udom);
1.335     albertel 1356:     if ($home eq 'no_host') {
                   1357:         return 'not_found';
1.1       albertel 1358:     }
                   1359:     my $answer=reply("sub:$fname",$home);
1.64      www      1360:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1361: 	$answer.=' by '.$home;
                   1362:     }
1.1       albertel 1363:     return $answer;
                   1364: }
                   1365:     
1.8       www      1366: # -------------------------------------------------------------- Replicate file
                   1367: 
                   1368: sub repcopy {
                   1369:     my $filename=shift;
1.23      www      1370:     $filename=~s/\/+/\//g;
1.607     raeburn  1371:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1372:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1373:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1374: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1375: 	return &repcopy_userfile($filename);
                   1376:     }
1.532     albertel 1377:     $filename=~s/[\n\r]//g;
1.8       www      1378:     my $transname="$filename.in.transfer";
1.828     www      1379: # FIXME: this should flock
1.607     raeburn  1380:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1381:     my $remoteurl=subscribe($filename);
1.64      www      1382:     if ($remoteurl =~ /^con_lost by/) {
                   1383: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1384:            return 'unavailable';
1.8       www      1385:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1386: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1387: 	   return 'not_found';
1.64      www      1388:     } elsif ($remoteurl =~ /^rejected by/) {
                   1389: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1390:            return 'forbidden';
1.20      www      1391:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1392:            return 'ok';
1.8       www      1393:     } else {
1.290     www      1394:         my $author=$filename;
                   1395:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1396:         my ($udom,$uname)=split(/\//,$author);
                   1397:         my $home=homeserver($uname,$udom);
                   1398:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1399:            my @parts=split(/\//,$filename);
                   1400:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1401:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1402:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1403: 	       return 'bad_request';
1.8       www      1404:            }
                   1405:            my $count;
                   1406:            for ($count=5;$count<$#parts;$count++) {
                   1407:                $path.="/$parts[$count]";
                   1408:                if ((-e $path)!=1) {
                   1409: 		   mkdir($path,0777);
                   1410:                }
                   1411:            }
                   1412:            my $ua=new LWP::UserAgent;
                   1413:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1414:            my $response=$ua->request($request,$transname);
                   1415:            if ($response->is_error()) {
                   1416: 	       unlink($transname);
                   1417:                my $message=$response->status_line;
1.672     albertel 1418:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1419:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1420:                return 'unavailable';
1.8       www      1421:            } else {
1.16      www      1422: 	       if ($remoteurl!~/\.meta$/) {
                   1423:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1424:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1425:                   if ($mresponse->is_error()) {
                   1426: 		      unlink($filename.'.meta');
                   1427:                       &logthis(
1.672     albertel 1428:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1429:                   }
                   1430: 	       }
1.8       www      1431:                rename($transname,$filename);
1.607     raeburn  1432:                return 'ok';
1.8       www      1433:            }
1.290     www      1434:        }
1.8       www      1435:     }
1.330     www      1436: }
                   1437: 
                   1438: # ------------------------------------------------ Get server side include body
                   1439: sub ssi_body {
1.381     albertel 1440:     my ($filelink,%form)=@_;
1.606     matthew  1441:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1442:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1443:     }
1.330     www      1444:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1445:                                      &ssi($filelink,%form));
1.778     albertel 1446:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1447:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1448:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1449:     return $output;
1.8       www      1450: }
                   1451: 
1.15      www      1452: # --------------------------------------------------------- Server Side Include
                   1453: 
1.782     albertel 1454: sub absolute_url {
                   1455:     my ($host_name) = @_;
                   1456:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1457:     if ($host_name eq '') {
                   1458: 	$host_name = $ENV{'SERVER_NAME'};
                   1459:     }
                   1460:     return $protocol.$host_name;
                   1461: }
                   1462: 
1.15      www      1463: sub ssi {
                   1464: 
1.23      www      1465:     my ($fn,%form)=@_;
1.15      www      1466: 
                   1467:     my $ua=new LWP::UserAgent;
1.23      www      1468:     
                   1469:     my $request;
1.711     albertel 1470: 
                   1471:     $form{'no_update_last_known'}=1;
1.895     albertel 1472:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1473:     if (%form) {
1.782     albertel 1474:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1475:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1476:     } else {
1.782     albertel 1477:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1478:     }
                   1479: 
1.15      www      1480:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1481:     my $response=$ua->request($request);
                   1482: 
1.324     www      1483:     return $response->content;
                   1484: }
                   1485: 
                   1486: sub externalssi {
                   1487:     my ($url)=@_;
                   1488:     my $ua=new LWP::UserAgent;
                   1489:     my $request=new HTTP::Request('GET',$url);
                   1490:     my $response=$ua->request($request);
1.15      www      1491:     return $response->content;
                   1492: }
1.254     www      1493: 
1.492     albertel 1494: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1495: 
                   1496: sub allowuploaded {
                   1497:     my ($srcurl,$url)=@_;
                   1498:     $url=&clutter(&declutter($url));
                   1499:     my $dir=$url;
                   1500:     $dir=~s/\/[^\/]+$//;
                   1501:     my %httpref=();
                   1502:     my $httpurl=&hreflocation('',$url);
                   1503:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1504:     &Apache::lonnet::appenv(%httpref);
1.254     www      1505: }
1.477     raeburn  1506: 
1.478     albertel 1507: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1508: # input: action, courseID, current domain, intended
1.637     raeburn  1509: #        path to file, source of file, instruction to parse file for objects,
                   1510: #        ref to hash for embedded objects,
                   1511: #        ref to hash for codebase of java objects.
                   1512: #
1.485     raeburn  1513: # output: url to file (if action was uploaddoc), 
                   1514: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1515: #
1.478     albertel 1516: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1517: # course.
1.477     raeburn  1518: #
1.478     albertel 1519: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1520: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1521: #          course's home server.
1.477     raeburn  1522: #
1.478     albertel 1523: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1524: #          be copied from $source (current location) to 
                   1525: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1526: #         and will then be copied to
                   1527: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1528: #         course's home server.
1.485     raeburn  1529: #
1.481     raeburn  1530: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1531: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1532: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1533: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1534: #         in course's home server.
1.637     raeburn  1535: #
1.477     raeburn  1536: 
                   1537: sub process_coursefile {
1.638     albertel 1538:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1539:     my $fetchresult;
1.638     albertel 1540:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1541:     if ($action eq 'propagate') {
1.638     albertel 1542:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1543: 			     $home);
1.481     raeburn  1544:     } else {
1.477     raeburn  1545:         my $fpath = '';
                   1546:         my $fname = $file;
1.478     albertel 1547:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1548:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1549:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1550:         if ($action eq 'copy') {
                   1551:             if ($source eq '') {
                   1552:                 $fetchresult = 'no source file';
                   1553:                 return $fetchresult;
                   1554:             } else {
                   1555:                 my $destination = $filepath.'/'.$fname;
                   1556:                 rename($source,$destination);
                   1557:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1558:                                  $home);
1.481     raeburn  1559:             }
                   1560:         } elsif ($action eq 'uploaddoc') {
                   1561:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1562:             print $fh $env{'form.'.$source};
1.481     raeburn  1563:             close($fh);
1.637     raeburn  1564:             if ($parser eq 'parse') {
                   1565:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1566:                 unless ($parse_result eq 'ok') {
                   1567:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1568:                 }
                   1569:             }
1.477     raeburn  1570:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1571:                                  $home);
1.481     raeburn  1572:             if ($fetchresult eq 'ok') {
                   1573:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1574:             } else {
                   1575:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1576:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1577:                 return '/adm/notfound.html';
                   1578:             }
1.477     raeburn  1579:         }
                   1580:     }
1.485     raeburn  1581:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1582:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1583:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1584:     }
                   1585:     return $fetchresult;
                   1586: }
                   1587: 
1.637     raeburn  1588: sub build_filepath {
                   1589:     my ($fpath) = @_;
                   1590:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1591:     unless ($fpath eq '') {
                   1592:         my @parts=split('/',$fpath);
                   1593:         foreach my $part (@parts) {
                   1594:             $filepath.= '/'.$part;
                   1595:             if ((-e $filepath)!=1) {
                   1596:                 mkdir($filepath,0777);
                   1597:             }
                   1598:         }
                   1599:     }
                   1600:     return $filepath;
                   1601: }
                   1602: 
                   1603: sub store_edited_file {
1.638     albertel 1604:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1605:     my $file = $primary_url;
                   1606:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1607:     my $fpath = '';
                   1608:     my $fname = $file;
                   1609:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1610:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1611:     my $filepath = &build_filepath($fpath);
                   1612:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1613:     print $fh $content;
                   1614:     close($fh);
1.638     albertel 1615:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1616:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1617: 			  $home);
1.637     raeburn  1618:     if ($$fetchresult eq 'ok') {
                   1619:         return '/uploaded/'.$fpath.'/'.$fname;
                   1620:     } else {
1.638     albertel 1621:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1622: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1623:         return '/adm/notfound.html';
                   1624:     }
                   1625: }
                   1626: 
1.531     albertel 1627: sub clean_filename {
1.831     albertel 1628:     my ($fname,$args)=@_;
1.315     www      1629: # Replace Windows backslashes by forward slashes
1.257     www      1630:     $fname=~s/\\/\//g;
1.831     albertel 1631:     if (!$args->{'keep_path'}) {
                   1632:         # Get rid of everything but the actual filename
                   1633: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1634:     }
1.315     www      1635: # Replace spaces by underscores
                   1636:     $fname=~s/\s+/\_/g;
                   1637: # Replace all other weird characters by nothing
1.831     albertel 1638:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1639: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1640: # numbers
                   1641:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1642:     return $fname;
                   1643: }
                   1644: 
1.608     albertel 1645: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1646: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1647: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1648: #        $coursedoc - if true up to the current course
                   1649: #                     if false
                   1650: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1651: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1652: #        $allfiles - reference to hash for embedded objects
                   1653: #        $codebase - reference to hash for codebase of java objects
                   1654: #        $desuname - username for permanent storage of uploaded file
                   1655: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1656: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1657: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1658: # 
1.686     albertel 1659: # output: url of file in userspace, or error: <message> 
                   1660: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1661: 
                   1662: 
1.531     albertel 1663: sub userfileupload {
1.860     raeburn  1664:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1665:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1666:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1667:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1668:     $fname=&clean_filename($fname);
1.315     www      1669: # See if there is anything left
1.257     www      1670:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1671:     chop($env{'form.'.$formname});
1.523     raeburn  1672:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1673:         my $now = time;
                   1674:         my $filepath = 'tmp/helprequests/'.$now;
                   1675:         my @parts=split(/\//,$filepath);
                   1676:         my $fullpath = $perlvar{'lonDaemons'};
                   1677:         for (my $i=0;$i<@parts;$i++) {
                   1678:             $fullpath .= '/'.$parts[$i];
                   1679:             if ((-e $fullpath)!=1) {
                   1680:                 mkdir($fullpath,0777);
                   1681:             }
                   1682:         }
                   1683:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1684:         print $fh $env{'form.'.$formname};
1.523     raeburn  1685:         close($fh);
1.741     raeburn  1686:         return $fullpath.'/'.$fname;
                   1687:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1688:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1689:                        '_'.$env{'user.domain'}.'/pending';
                   1690:         my @parts=split(/\//,$filepath);
                   1691:         my $fullpath = $perlvar{'lonDaemons'};
                   1692:         for (my $i=0;$i<@parts;$i++) {
                   1693:             $fullpath .= '/'.$parts[$i];
                   1694:             if ((-e $fullpath)!=1) {
                   1695:                 mkdir($fullpath,0777);
                   1696:             }
                   1697:         }
                   1698:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1699:         print $fh $env{'form.'.$formname};
                   1700:         close($fh);
                   1701:         return $fullpath.'/'.$fname;
1.523     raeburn  1702:     }
1.719     banghart 1703:     
1.258     www      1704: # Create the directory if not present
1.493     albertel 1705:     $fname="$subdir/$fname";
1.259     www      1706:     if ($coursedoc) {
1.638     albertel 1707: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1708: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1709:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1710:             return &finishuserfileupload($docuname,$docudom,
                   1711: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1712: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1713:         } else {
1.620     albertel 1714:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1715:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1716: 				       $fname,$formname,$parser,
                   1717: 				       $allfiles,$codebase);
1.481     raeburn  1718:         }
1.719     banghart 1719:     } elsif (defined($destuname)) {
                   1720:         my $docuname=$destuname;
                   1721:         my $docudom=$destudom;
1.860     raeburn  1722: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1723: 				     $parser,$allfiles,$codebase,
                   1724:                                      $thumbwidth,$thumbheight);
1.719     banghart 1725:         
1.259     www      1726:     } else {
1.638     albertel 1727:         my $docuname=$env{'user.name'};
                   1728:         my $docudom=$env{'user.domain'};
1.714     raeburn  1729:         if (exists($env{'form.group'})) {
                   1730:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1731:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1732:         }
1.860     raeburn  1733: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1734: 				     $parser,$allfiles,$codebase,
                   1735:                                      $thumbwidth,$thumbheight);
1.259     www      1736:     }
1.271     www      1737: }
                   1738: 
                   1739: sub finishuserfileupload {
1.860     raeburn  1740:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1741:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1742:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1743:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1744:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1745:     $file=$fname;
                   1746:     if ($fname=~m|/|) {
                   1747:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1748: 	$path.=$fnamepath.'/';
                   1749:     }
1.259     www      1750:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1751:     my $count;
                   1752:     for ($count=4;$count<=$#parts;$count++) {
                   1753:         $filepath.="/$parts[$count]";
                   1754:         if ((-e $filepath)!=1) {
                   1755: 	    mkdir($filepath,0777);
                   1756:         }
                   1757:     }
                   1758: # Save the file
                   1759:     {
1.701     albertel 1760: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1761: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1762: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1763: 	    return '/adm/notfound.html';
                   1764: 	}
                   1765: 	if (!print FH ($env{'form.'.$formname})) {
                   1766: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1767: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1768: 	    return '/adm/notfound.html';
                   1769: 	}
1.570     albertel 1770: 	close(FH);
1.258     www      1771:     }
1.637     raeburn  1772:     if ($parser eq 'parse') {
1.638     albertel 1773:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1774: 						   $codebase);
1.637     raeburn  1775:         unless ($parse_result eq 'ok') {
1.638     albertel 1776:             &logthis('Failed to parse '.$filepath.$file.
                   1777: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1778:         }
                   1779:     }
1.860     raeburn  1780:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1781:         my $input = $filepath.'/'.$file;
                   1782:         my $output = $filepath.'/'.'tn-'.$file;
                   1783:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1784:         system("convert -sample $thumbsize $input $output");
                   1785:         if (-e $filepath.'/'.'tn-'.$file) {
                   1786:             $fetchthumb  = 1; 
                   1787:         }
                   1788:     }
1.858     raeburn  1789:  
1.259     www      1790: # Notify homeserver to grep it
                   1791: #
1.638     albertel 1792:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1793:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1794:     if ($fetchresult eq 'ok') {
1.860     raeburn  1795:         if ($fetchthumb) {
                   1796:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1797:             if ($thumbresult ne 'ok') {
                   1798:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1799:                          $docuhome.': '.$thumbresult);
                   1800:             }
                   1801:         }
1.259     www      1802: #
1.258     www      1803: # Return the URL to it
1.494     albertel 1804:         return '/uploaded/'.$path.$file;
1.263     www      1805:     } else {
1.494     albertel 1806:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1807: 		 ': '.$fetchresult);
1.263     www      1808:         return '/adm/notfound.html';
1.858     raeburn  1809:     }
1.493     albertel 1810: }
                   1811: 
1.637     raeburn  1812: sub extract_embedded_items {
1.648     raeburn  1813:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1814:     my @state = ();
                   1815:     my %javafiles = (
                   1816:                       codebase => '',
                   1817:                       code => '',
                   1818:                       archive => ''
                   1819:                     );
                   1820:     my %mediafiles = (
                   1821:                       src => '',
                   1822:                       movie => '',
                   1823:                      );
1.648     raeburn  1824:     my $p;
                   1825:     if ($content) {
                   1826:         $p = HTML::LCParser->new($content);
                   1827:     } else {
                   1828:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1829:     }
1.641     albertel 1830:     while (my $t=$p->get_token()) {
1.640     albertel 1831: 	if ($t->[0] eq 'S') {
                   1832: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1833: 	    push(@state, $tagname);
1.648     raeburn  1834:             if (lc($tagname) eq 'allow') {
                   1835:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1836:             }
1.640     albertel 1837: 	    if (lc($tagname) eq 'img') {
                   1838: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1839: 	    }
1.886     albertel 1840: 	    if (lc($tagname) eq 'a') {
                   1841: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1842: 	    }
1.645     raeburn  1843:             if (lc($tagname) eq 'script') {
                   1844:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1845:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1846:                 } else {
                   1847:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1848:                 }
                   1849:             }
                   1850:             if (lc($tagname) eq 'link') {
                   1851:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1852:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1853:                 }
                   1854:             }
1.640     albertel 1855: 	    if (lc($tagname) eq 'object' ||
                   1856: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1857: 		foreach my $item (keys(%javafiles)) {
                   1858: 		    $javafiles{$item} = '';
                   1859: 		}
                   1860: 	    }
                   1861: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1862: 		my $name = lc($attr->{'name'});
                   1863: 		foreach my $item (keys(%javafiles)) {
                   1864: 		    if ($name eq $item) {
                   1865: 			$javafiles{$item} = $attr->{'value'};
                   1866: 			last;
                   1867: 		    }
                   1868: 		}
                   1869: 		foreach my $item (keys(%mediafiles)) {
                   1870: 		    if ($name eq $item) {
                   1871: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1872: 			last;
                   1873: 		    }
                   1874: 		}
                   1875: 	    }
                   1876: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1877: 		foreach my $item (keys(%javafiles)) {
                   1878: 		    if ($attr->{$item}) {
                   1879: 			$javafiles{$item} = $attr->{$item};
                   1880: 			last;
                   1881: 		    }
                   1882: 		}
                   1883: 		foreach my $item (keys(%mediafiles)) {
                   1884: 		    if ($attr->{$item}) {
                   1885: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1886: 			last;
                   1887: 		    }
                   1888: 		}
                   1889: 	    }
                   1890: 	} elsif ($t->[0] eq 'E') {
                   1891: 	    my ($tagname) = ($t->[1]);
                   1892: 	    if ($javafiles{'codebase'} ne '') {
                   1893: 		$javafiles{'codebase'} .= '/';
                   1894: 	    }  
                   1895: 	    if (lc($tagname) eq 'applet' ||
                   1896: 		lc($tagname) eq 'object' ||
                   1897: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1898: 		) {
                   1899: 		foreach my $item (keys(%javafiles)) {
                   1900: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1901: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1902: 			&add_filetype($allfiles,$file,$item);
                   1903: 		    }
                   1904: 		}
                   1905: 	    } 
                   1906: 	    pop @state;
                   1907: 	}
                   1908:     }
1.637     raeburn  1909:     return 'ok';
                   1910: }
                   1911: 
1.639     albertel 1912: sub add_filetype {
                   1913:     my ($allfiles,$file,$type)=@_;
                   1914:     if (exists($allfiles->{$file})) {
                   1915: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1916: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1917: 	}
                   1918:     } else {
                   1919: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1920:     }
                   1921: }
                   1922: 
1.493     albertel 1923: sub removeuploadedurl {
                   1924:     my ($url)=@_;
                   1925:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1926:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1927: }
                   1928: 
                   1929: sub removeuserfile {
                   1930:     my ($docuname,$docudom,$fname)=@_;
                   1931:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1932:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1933:     if ($result eq 'ok') {
                   1934:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1935:             my $metafile = $fname.'.meta';
                   1936:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1937: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1938:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1939:             my $sqlresult = 
1.823     albertel 1940:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1941:                                         'portfolio_metadata',$group,
                   1942:                                         'delete');
1.798     raeburn  1943:         }
                   1944:     }
                   1945:     return $result;
1.257     www      1946: }
1.15      www      1947: 
1.530     albertel 1948: sub mkdiruserfile {
                   1949:     my ($docuname,$docudom,$dir)=@_;
                   1950:     my $home=&homeserver($docuname,$docudom);
                   1951:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1952: }
                   1953: 
1.531     albertel 1954: sub renameuserfile {
                   1955:     my ($docuname,$docudom,$old,$new)=@_;
                   1956:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1957:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1958:                         &escape("$old").':'.&escape("$new"),$home);
                   1959:     if ($result eq 'ok') {
                   1960:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1961:             my $oldmeta = $old.'.meta';
                   1962:             my $newmeta = $new.'.meta';
                   1963:             my $metaresult = 
                   1964:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1965: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1966:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1967:             my $sqlresult = 
1.823     albertel 1968:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1969:                                         'portfolio_metadata',$group,
                   1970:                                         'delete');
1.798     raeburn  1971:         }
                   1972:     }
                   1973:     return $result;
1.531     albertel 1974: }
                   1975: 
1.14      www      1976: # ------------------------------------------------------------------------- Log
                   1977: 
                   1978: sub log {
                   1979:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1980:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1981: }
                   1982: 
                   1983: # ------------------------------------------------------------------ Course Log
1.352     www      1984: #
                   1985: # This routine flushes several buffers of non-mission-critical nature
                   1986: #
1.157     www      1987: 
                   1988: sub flushcourselogs {
1.352     www      1989:     &logthis('Flushing log buffers');
                   1990: #
                   1991: # course logs
                   1992: # This is a log of all transactions in a course, which can be used
                   1993: # for data mining purposes
                   1994: #
                   1995: # It also collects the courseid database, which lists last transaction
                   1996: # times and course titles for all courseids
                   1997: #
                   1998:     my %courseidbuffer=();
1.800     albertel 1999:     foreach my $crsid (keys %courselogs) {
1.352     www      2000:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2001: 		          &escape($courselogs{$crsid}),
                   2002: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2003: 	    delete $courselogs{$crsid};
                   2004:         } else {
                   2005:             &logthis('Failed to flush log buffer for '.$crsid);
                   2006:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2007:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2008:                         " exceeded maximum size, deleting.</font>");
                   2009:                delete $courselogs{$crsid};
                   2010:             }
1.352     www      2011:         }
                   2012:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2013:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2014: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2015:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2016:         } else {
                   2017:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2018: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2019:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2020:         }
1.191     harris41 2021:     }
1.352     www      2022: #
                   2023: # Write course id database (reverse lookup) to homeserver of courses 
                   2024: # Is used in pickcourse
                   2025: #
1.840     albertel 2026:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2027:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2028: 		     $crs_home);
1.352     www      2029:     }
                   2030: #
                   2031: # File accesses
                   2032: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2033: #
1.449     matthew  2034:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2035:         if ($entry =~ /___count$/) {
                   2036:             my ($dom,$name);
1.807     albertel 2037:             ($dom,$name,undef)=
1.811     albertel 2038: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2039:             if (! defined($dom) || $dom eq '' || 
                   2040:                 ! defined($name) || $name eq '') {
1.620     albertel 2041:                 my $cid = $env{'request.course.id'};
                   2042:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2043:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2044:             }
1.450     matthew  2045:             my $value = $accesshash{$entry};
                   2046:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2047:             my %temphash=($url => $value);
1.449     matthew  2048:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2049:             if ($result eq 'ok') {
                   2050:                 delete $accesshash{$entry};
                   2051:             } elsif ($result eq 'unknown_cmd') {
                   2052:                 # Target server has old code running on it.
1.450     matthew  2053:                 my %temphash=($entry => $value);
1.449     matthew  2054:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2055:                     delete $accesshash{$entry};
                   2056:                 }
                   2057:             }
                   2058:         } else {
1.811     albertel 2059:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2060:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2061:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2062:                 delete $accesshash{$entry};
                   2063:             }
1.185     www      2064:         }
1.191     harris41 2065:     }
1.352     www      2066: #
                   2067: # Roles
                   2068: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2069: #
1.800     albertel 2070:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2071:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2072: 	    split(/\:/,$entry);
                   2073:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2074:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2075:                 $rudom,$runame) eq 'ok') {
                   2076: 	    delete $userrolehash{$entry};
                   2077:         }
                   2078:     }
1.662     raeburn  2079: #
                   2080: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2081: #
                   2082:     my %domrolebuffer = ();
                   2083:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2084:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2085:         if ($domrolebuffer{$rudom}) {
                   2086:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2087:                       '='.&escape($domainrolehash{$entry});
                   2088:         } else {
                   2089:             $domrolebuffer{$rudom}.=&escape($entry).
                   2090:                       '='.&escape($domainrolehash{$entry});
                   2091:         }
                   2092:         delete $domainrolehash{$entry};
                   2093:     }
                   2094:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2095: 	my %servers = &get_servers($dom,'library');
                   2096: 	foreach my $tryserver (keys(%servers)) {
                   2097: 	    unless (&reply('domroleput:'.$dom.':'.
                   2098: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2099: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2100: 	    }
1.662     raeburn  2101:         }
                   2102:     }
1.186     www      2103:     $dumpcount++;
1.157     www      2104: }
                   2105: 
                   2106: sub courselog {
                   2107:     my $what=shift;
1.158     www      2108:     $what=time.':'.$what;
1.620     albertel 2109:     unless ($env{'request.course.id'}) { return ''; }
                   2110:     $coursedombuf{$env{'request.course.id'}}=
                   2111:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2112:     $coursenumbuf{$env{'request.course.id'}}=
                   2113:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2114:     $coursehombuf{$env{'request.course.id'}}=
                   2115:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2116:     $coursedescrbuf{$env{'request.course.id'}}=
                   2117:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2118:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2119:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2120:     $courseownerbuf{$env{'request.course.id'}}=
                   2121:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2122:     $coursetypebuf{$env{'request.course.id'}}=
                   2123:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2124:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2125: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2126:     } else {
1.620     albertel 2127: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2128:     }
1.620     albertel 2129:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2130: 	&flushcourselogs();
                   2131:     }
1.158     www      2132: }
                   2133: 
                   2134: sub courseacclog {
                   2135:     my $fnsymb=shift;
1.620     albertel 2136:     unless ($env{'request.course.id'}) { return ''; }
                   2137:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2138:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2139:         $what.=':POST';
1.583     matthew  2140:         # FIXME: Probably ought to escape things....
1.800     albertel 2141: 	foreach my $key (keys(%env)) {
                   2142:             if ($key=~/^form\.(.*)/) {
                   2143: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2144:             }
1.191     harris41 2145:         }
1.583     matthew  2146:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2147:         # FIXME: We should not be depending on a form parameter that someone
                   2148:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2149:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2150:             $what.= ':POST';
                   2151:             # FIXME: Probably ought to escape things....
                   2152:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2153:                                  'crsdiscuss') {
1.620     albertel 2154:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2155:             }
                   2156:         }
1.158     www      2157:     }
                   2158:     &courselog($what);
1.149     www      2159: }
                   2160: 
1.185     www      2161: sub countacc {
                   2162:     my $url=&declutter(shift);
1.458     matthew  2163:     return if (! defined($url) || $url eq '');
1.620     albertel 2164:     unless ($env{'request.course.id'}) { return ''; }
                   2165:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2166:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2167:     $accesshash{$key}++;
1.185     www      2168: }
1.349     www      2169: 
1.361     www      2170: sub linklog {
                   2171:     my ($from,$to)=@_;
                   2172:     $from=&declutter($from);
                   2173:     $to=&declutter($to);
                   2174:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2175:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2176: }
                   2177:   
1.349     www      2178: sub userrolelog {
                   2179:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2180:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2181:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2182:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2183:         ($trole=~/^ta/)) {
1.350     www      2184:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2185:        $userrolehash
                   2186:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2187:                     =$tend.':'.$tstart;
1.662     raeburn  2188:     }
1.898     albertel 2189:     if (($env{'request.role'} =~ /dc\./) &&
                   2190: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2191: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2192: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2193:        $userrolehash
                   2194:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2195:                     =$tend.':'.$tstart;
                   2196:     }
1.662     raeburn  2197:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2198:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2199:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2200:         ($trole=~/^sc/)) {
                   2201:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2202:        $domainrolehash
                   2203:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2204:                     = $tend.':'.$tstart;
                   2205:     }
1.351     www      2206: }
                   2207: 
                   2208: sub get_course_adv_roles {
                   2209:     my $cid=shift;
1.620     albertel 2210:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2211:     my %coursehash=&coursedescription($cid);
1.470     www      2212:     my %nothide=();
1.800     albertel 2213:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2214: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2215:     }
1.351     www      2216:     my %returnhash=();
                   2217:     my %dumphash=
                   2218:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2219:     my $now=time;
1.800     albertel 2220:     foreach my $entry (keys %dumphash) {
                   2221: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2222:         if (($tstart) && ($tstart<0)) { next; }
                   2223:         if (($tend) && ($tend<$now)) { next; }
                   2224:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2225:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2226: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2227: 	if ((&privileged($username,$domain)) && 
                   2228: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2229: 	if ($role eq 'cr') { next; }
1.351     www      2230:         my $key=&plaintext($role);
                   2231:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2232:         if ($returnhash{$key}) {
                   2233: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2234:         } else {
                   2235:             $returnhash{$key}=$username.':'.$domain;
                   2236:         }
1.400     www      2237:      }
                   2238:     return %returnhash;
                   2239: }
                   2240: 
                   2241: sub get_my_roles {
1.858     raeburn  2242:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2243:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2244:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2245:     my %dumphash;
                   2246:     if ($context eq 'userroles') { 
                   2247:         %dumphash = &dump('roles',$udom,$uname);
                   2248:     } else {
                   2249:         %dumphash=
1.400     www      2250:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2251:     }
1.400     www      2252:     my %returnhash=();
                   2253:     my $now=time;
1.800     albertel 2254:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2255:         my ($role,$tend,$tstart);
                   2256:         if ($context eq 'userroles') {
                   2257: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2258:         } else {
                   2259:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2260:         }
1.400     www      2261:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2262:         my $status = 'active';
                   2263:         if (($tend) && ($tend<$now)) {
                   2264:             $status = 'previous';
                   2265:         } 
                   2266:         if (($tstart) && ($now<$tstart)) {
                   2267:             $status = 'future';
                   2268:         }
                   2269:         if (ref($types) eq 'ARRAY') {
                   2270:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2271:                 next;
                   2272:             } 
                   2273:         } else {
                   2274:             if ($status ne 'active') {
                   2275:                 next;
                   2276:             }
                   2277:         }
1.867     raeburn  2278:         my ($rolecode,$username,$domain,$section,$area);
                   2279:         if ($context eq 'userroles') {
                   2280:             ($area,$rolecode) = split(/_/,$entry);
                   2281:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2282:         } else {
                   2283:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2284:         }
1.832     raeburn  2285:         if (ref($roledoms) eq 'ARRAY') {
                   2286:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2287:                 next;
                   2288:             }
                   2289:         }
                   2290:         if (ref($roles) eq 'ARRAY') {
                   2291:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2292:                 next;
                   2293:             }
1.867     raeburn  2294:         }
1.400     www      2295: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2296:     }
1.373     www      2297:     return %returnhash;
1.399     www      2298: }
                   2299: 
                   2300: # ----------------------------------------------------- Frontpage Announcements
                   2301: #
                   2302: #
                   2303: 
                   2304: sub postannounce {
                   2305:     my ($server,$text)=@_;
1.844     albertel 2306:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2307:     unless ($text=~/\w/) { $text=''; }
                   2308:     return &reply('setannounce:'.&escape($text),$server);
                   2309: }
                   2310: 
                   2311: sub getannounce {
1.448     albertel 2312: 
                   2313:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2314: 	my $announcement='';
1.800     albertel 2315: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2316: 	close($fh);
1.399     www      2317: 	if ($announcement=~/\w/) { 
                   2318: 	    return 
                   2319:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2320:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2321: 	} else {
                   2322: 	    return '';
                   2323: 	}
                   2324:     } else {
                   2325: 	return '';
                   2326:     }
1.351     www      2327: }
1.353     www      2328: 
                   2329: # ---------------------------------------------------------- Course ID routines
                   2330: # Deal with domain's nohist_courseid.db files
                   2331: #
                   2332: 
                   2333: sub courseidput {
                   2334:     my ($domain,$what,$coursehome)=@_;
                   2335:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2336: }
                   2337: 
                   2338: sub courseiddump {
1.791     raeburn  2339:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2340:     my %returnhash=();
1.355     www      2341:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2342:     my %libserv = &all_library();
                   2343:     foreach my $tryserver (keys(%libserv)) {
                   2344:         if ( (  $hostidflag == 1 
                   2345: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2346: 	     || (!defined($hostidflag)) ) {
                   2347: 
                   2348: 	    if ($domfilter eq ''
                   2349: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2350: 	        foreach my $line (
1.844     albertel 2351:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2352: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2353:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2354:                                $tryserver))) {
1.800     albertel 2355: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2356:                     if (($key) && ($value)) {
1.516     raeburn  2357: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2358:                     }
1.353     www      2359:                 }
                   2360:             }
                   2361:         }
                   2362:     }
                   2363:     return %returnhash;
                   2364: }
                   2365: 
1.658     raeburn  2366: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2367: 
                   2368: sub dcmailput {
1.685     raeburn  2369:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2370:     my $status = &Apache::lonnet::critical(
1.740     www      2371:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2372:        &escape($message),$server);
1.662     raeburn  2373:     return $status;
                   2374: }
                   2375: 
1.658     raeburn  2376: sub dcmaildump {
                   2377:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2378:     my %returnhash=();
1.846     albertel 2379: 
                   2380:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2381:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2382:                                                          &escape($enddate).':';
                   2383: 	my @esc_senders=map { &escape($_)} @$senders;
                   2384: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2385: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2386:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2387:             if (($key) && ($value)) {
                   2388:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2389:             }
                   2390:         }
                   2391:     }
                   2392:     return %returnhash;
                   2393: }
1.662     raeburn  2394: # ---------------------------------------------------------- Domain roles
                   2395: 
                   2396: sub get_domain_roles {
                   2397:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2398:     if (undef($startdate) || $startdate eq '') {
                   2399:         $startdate = '.';
                   2400:     }
                   2401:     if (undef($enddate) || $enddate eq '') {
                   2402:         $enddate = '.';
                   2403:     }
                   2404:     my $rolelist = join(':',@{$roles});
                   2405:     my %personnel = ();
1.841     albertel 2406: 
                   2407:     my %servers = &get_servers($dom,'library');
                   2408:     foreach my $tryserver (keys(%servers)) {
                   2409: 	%{$personnel{$tryserver}}=();
                   2410: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2411: 					    &escape($startdate).':'.
                   2412: 					    &escape($enddate).':'.
                   2413: 					    &escape($rolelist), $tryserver))) {
                   2414: 	    my ($key,$value) = split(/\=/,$line,2);
                   2415: 	    if (($key) && ($value)) {
                   2416: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2417: 	    }
                   2418: 	}
1.662     raeburn  2419:     }
                   2420:     return %personnel;
                   2421: }
1.658     raeburn  2422: 
1.149     www      2423: # ----------------------------------------------------------- Check out an item
                   2424: 
1.504     albertel 2425: sub get_first_access {
                   2426:     my ($type,$argsymb)=@_;
1.790     albertel 2427:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2428:     if ($argsymb) { $symb=$argsymb; }
                   2429:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2430:     if ($type eq 'map') {
                   2431: 	$res=&symbread($map);
                   2432:     } else {
                   2433: 	$res=$symb;
                   2434:     }
                   2435:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2436:     return $times{"$courseid\0$res"};
1.504     albertel 2437: }
                   2438: 
                   2439: sub set_first_access {
                   2440:     my ($type)=@_;
1.790     albertel 2441:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2442:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2443:     if ($type eq 'map') {
                   2444: 	$res=&symbread($map);
                   2445:     } else {
                   2446: 	$res=$symb;
                   2447:     }
                   2448:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2449:     if (!$firstaccess) {
1.588     albertel 2450: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2451:     }
                   2452:     return 'already_set';
1.504     albertel 2453: }
                   2454: 
1.149     www      2455: sub checkout {
                   2456:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2457:     my $now=time;
                   2458:     my $lonhost=$perlvar{'lonHostID'};
                   2459:     my $infostr=&escape(
1.234     www      2460:                  'CHECKOUTTOKEN&'.
1.149     www      2461:                  $tuname.'&'.
                   2462:                  $tudom.'&'.
                   2463:                  $tcrsid.'&'.
                   2464:                  $symb.'&'.
                   2465: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2466:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2467:     if ($token=~/^error\:/) { 
1.672     albertel 2468:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2469:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2470:                  "</font>");
                   2471:         return ''; 
                   2472:     }
                   2473: 
1.149     www      2474:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2475:     $token=~tr/a-z/A-Z/;
                   2476: 
1.153     www      2477:     my %infohash=('resource.0.outtoken' => $token,
                   2478:                   'resource.0.checkouttime' => $now,
                   2479:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2480: 
                   2481:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2482:        return '';
1.151     www      2483:     } else {
1.672     albertel 2484:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2485:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2486:                  "</font>");
1.149     www      2487:     }    
                   2488: 
                   2489:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2490:                          &escape('Checkout '.$infostr.' - '.
                   2491:                                                  $token)) ne 'ok') {
                   2492: 	return '';
1.151     www      2493:     } else {
1.672     albertel 2494:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2495:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2496:                  "</font>");
1.149     www      2497:     }
1.151     www      2498:     return $token;
1.149     www      2499: }
                   2500: 
                   2501: # ------------------------------------------------------------ Check in an item
                   2502: 
                   2503: sub checkin {
                   2504:     my $token=shift;
1.150     www      2505:     my $now=time;
                   2506:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2507:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2508:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2509:     $dtoken=~s/\W/\_/g;
1.234     www      2510:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2511:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2512: 
1.154     www      2513:     unless (($tuname) && ($tudom)) {
                   2514:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2515:         return '';
                   2516:     }
                   2517:     
                   2518:     unless (&allowed('mgr',$tcrsid)) {
                   2519:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2520:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2521:         return '';
                   2522:     }
                   2523: 
1.153     www      2524:     my %infohash=('resource.0.intoken' => $token,
                   2525:                   'resource.0.checkintime' => $now,
                   2526:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2527: 
                   2528:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2529:        return '';
                   2530:     }    
                   2531: 
                   2532:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2533:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2534: 	return '';
                   2535:     }
                   2536: 
                   2537:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2538: }
                   2539: 
                   2540: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2541: 
                   2542: sub expirespread {
                   2543:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2544:     my $cid=$env{'request.course.id'}; 
1.110     www      2545:     if ($cid) {
                   2546:        my $now=time;
                   2547:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2548:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2549:                             $env{'course.'.$cid.'.num'}.
1.110     www      2550: 	        	    ':nohist_expirationdates:'.
                   2551:                             &escape($key).'='.$now,
1.620     albertel 2552:                             $env{'course.'.$cid.'.home'})
1.110     www      2553:     }
                   2554:     return 'ok';
1.14      www      2555: }
                   2556: 
1.109     www      2557: # ----------------------------------------------------- Devalidate Spreadsheets
                   2558: 
                   2559: sub devalidate {
1.325     www      2560:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2561:     my $cid=$env{'request.course.id'}; 
1.109     www      2562:     if ($cid) {
1.391     matthew  2563:         # delete the stored spreadsheets for
                   2564:         # - the student level sheet of this user in course's homespace
                   2565:         # - the assessment level sheet for this resource 
                   2566:         #   for this user in user's homespace
1.553     albertel 2567: 	# - current conditional state info
1.325     www      2568: 	my $key=$uname.':'.$udom.':';
1.109     www      2569:         my $status=
1.299     matthew  2570: 	    &del('nohist_calculatedsheets',
1.391     matthew  2571: 		 [$key.'studentcalc:'],
1.620     albertel 2572: 		 $env{'course.'.$cid.'.domain'},
                   2573: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2574: 		.' '.
                   2575: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2576: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2577:         unless ($status eq 'ok ok') {
                   2578:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2579:                     $uname.' at '.$udom.' for '.
1.109     www      2580: 		    $symb.': '.$status);
1.133     albertel 2581:         }
1.553     albertel 2582: 	&delenv('user.state.'.$cid);
1.109     www      2583:     }
                   2584: }
                   2585: 
1.265     albertel 2586: sub get_scalar {
                   2587:     my ($string,$end) = @_;
                   2588:     my $value;
                   2589:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2590: 	$value = $1;
                   2591:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2592: 	$value = $1;
                   2593:     }
                   2594:     return &unescape($value);
                   2595: }
                   2596: 
                   2597: sub array2str {
                   2598:   my (@array) = @_;
                   2599:   my $result=&arrayref2str(\@array);
                   2600:   $result=~s/^__ARRAY_REF__//;
                   2601:   $result=~s/__END_ARRAY_REF__$//;
                   2602:   return $result;
                   2603: }
                   2604: 
1.204     albertel 2605: sub arrayref2str {
                   2606:   my ($arrayref) = @_;
1.265     albertel 2607:   my $result='__ARRAY_REF__';
1.204     albertel 2608:   foreach my $elem (@$arrayref) {
1.265     albertel 2609:     if(ref($elem) eq 'ARRAY') {
                   2610:       $result.=&arrayref2str($elem).'&';
                   2611:     } elsif(ref($elem) eq 'HASH') {
                   2612:       $result.=&hashref2str($elem).'&';
                   2613:     } elsif(ref($elem)) {
                   2614:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2615:     } else {
                   2616:       $result.=&escape($elem).'&';
                   2617:     }
                   2618:   }
                   2619:   $result=~s/\&$//;
1.265     albertel 2620:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2621:   return $result;
                   2622: }
                   2623: 
1.168     albertel 2624: sub hash2str {
1.204     albertel 2625:   my (%hash) = @_;
                   2626:   my $result=&hashref2str(\%hash);
1.265     albertel 2627:   $result=~s/^__HASH_REF__//;
                   2628:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2629:   return $result;
                   2630: }
                   2631: 
                   2632: sub hashref2str {
                   2633:   my ($hashref)=@_;
1.265     albertel 2634:   my $result='__HASH_REF__';
1.800     albertel 2635:   foreach my $key (sort(keys(%$hashref))) {
                   2636:     if (ref($key) eq 'ARRAY') {
                   2637:       $result.=&arrayref2str($key).'=';
                   2638:     } elsif (ref($key) eq 'HASH') {
                   2639:       $result.=&hashref2str($key).'=';
                   2640:     } elsif (ref($key)) {
1.265     albertel 2641:       $result.='=';
1.800     albertel 2642:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2643:     } else {
1.800     albertel 2644: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2645:     }
                   2646: 
1.800     albertel 2647:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2648:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2649:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2650:       $result.=&hashref2str($hashref->{$key}).'&';
                   2651:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2652:        $result.='&';
1.800     albertel 2653:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2654:     } else {
1.800     albertel 2655:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2656:     }
                   2657:   }
1.168     albertel 2658:   $result=~s/\&$//;
1.265     albertel 2659:   $result .= '__END_HASH_REF__';
1.168     albertel 2660:   return $result;
                   2661: }
                   2662: 
                   2663: sub str2hash {
1.265     albertel 2664:     my ($string)=@_;
                   2665:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2666:     return %$hash;
                   2667: }
                   2668: 
                   2669: sub str2hashref {
1.168     albertel 2670:   my ($string) = @_;
1.265     albertel 2671: 
                   2672:   my %hash;
                   2673: 
                   2674:   if($string !~ /^__HASH_REF__/) {
                   2675:       if (! ($string eq '' || !defined($string))) {
                   2676: 	  $hash{'error'}='Not hash reference';
                   2677:       }
                   2678:       return (\%hash, $string);
                   2679:   }
                   2680: 
                   2681:   $string =~ s/^__HASH_REF__//;
                   2682: 
                   2683:   while($string !~ /^__END_HASH_REF__/) {
                   2684:       #key
                   2685:       my $key='';
                   2686:       if($string =~ /^__HASH_REF__/) {
                   2687:           ($key, $string)=&str2hashref($string);
                   2688:           if(defined($key->{'error'})) {
                   2689:               $hash{'error'}='Bad data';
                   2690:               return (\%hash, $string);
                   2691:           }
                   2692:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2693:           ($key, $string)=&str2arrayref($string);
                   2694:           if($key->[0] eq 'Array reference error') {
                   2695:               $hash{'error'}='Bad data';
                   2696:               return (\%hash, $string);
                   2697:           }
                   2698:       } else {
                   2699:           $string =~ s/^(.*?)=//;
1.267     albertel 2700: 	  $key=&unescape($1);
1.265     albertel 2701:       }
                   2702:       $string =~ s/^=//;
                   2703: 
                   2704:       #value
                   2705:       my $value='';
                   2706:       if($string =~ /^__HASH_REF__/) {
                   2707:           ($value, $string)=&str2hashref($string);
                   2708:           if(defined($value->{'error'})) {
                   2709:               $hash{'error'}='Bad data';
                   2710:               return (\%hash, $string);
                   2711:           }
                   2712:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2713:           ($value, $string)=&str2arrayref($string);
                   2714:           if($value->[0] eq 'Array reference error') {
                   2715:               $hash{'error'}='Bad data';
                   2716:               return (\%hash, $string);
                   2717:           }
                   2718:       } else {
                   2719: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2720:       }
                   2721:       $string =~ s/^&//;
                   2722: 
                   2723:       $hash{$key}=$value;
1.204     albertel 2724:   }
1.265     albertel 2725: 
                   2726:   $string =~ s/^__END_HASH_REF__//;
                   2727: 
                   2728:   return (\%hash, $string);
1.204     albertel 2729: }
                   2730: 
                   2731: sub str2array {
1.265     albertel 2732:     my ($string)=@_;
                   2733:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2734:     return @$array;
                   2735: }
                   2736: 
                   2737: sub str2arrayref {
1.204     albertel 2738:   my ($string) = @_;
1.265     albertel 2739:   my @array;
                   2740: 
                   2741:   if($string !~ /^__ARRAY_REF__/) {
                   2742:       if (! ($string eq '' || !defined($string))) {
                   2743: 	  $array[0]='Array reference error';
                   2744:       }
                   2745:       return (\@array, $string);
                   2746:   }
                   2747: 
                   2748:   $string =~ s/^__ARRAY_REF__//;
                   2749: 
                   2750:   while($string !~ /^__END_ARRAY_REF__/) {
                   2751:       my $value='';
                   2752:       if($string =~ /^__HASH_REF__/) {
                   2753:           ($value, $string)=&str2hashref($string);
                   2754:           if(defined($value->{'error'})) {
                   2755:               $array[0] ='Array reference error';
                   2756:               return (\@array, $string);
                   2757:           }
                   2758:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2759:           ($value, $string)=&str2arrayref($string);
                   2760:           if($value->[0] eq 'Array reference error') {
                   2761:               $array[0] ='Array reference error';
                   2762:               return (\@array, $string);
                   2763:           }
                   2764:       } else {
                   2765: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2766:       }
                   2767:       $string =~ s/^&//;
                   2768: 
                   2769:       push(@array, $value);
1.191     harris41 2770:   }
1.265     albertel 2771: 
                   2772:   $string =~ s/^__END_ARRAY_REF__//;
                   2773: 
                   2774:   return (\@array, $string);
1.168     albertel 2775: }
                   2776: 
1.167     albertel 2777: # -------------------------------------------------------------------Temp Store
                   2778: 
1.168     albertel 2779: sub tmpreset {
                   2780:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2781:   if (!$symb) {
                   2782:     $symb=&symbread();
1.620     albertel 2783:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2784:   }
                   2785:   $symb=escape($symb);
                   2786: 
1.620     albertel 2787:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2788:   $namespace=~s/\//\_/g;
                   2789:   $namespace=~s/\W//g;
                   2790: 
1.620     albertel 2791:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2792:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2793:   if ($domain eq 'public' && $stuname eq 'public') {
                   2794:       $stuname=$ENV{'REMOTE_ADDR'};
                   2795:   }
1.168     albertel 2796:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2797:   my %hash;
                   2798:   if (tie(%hash,'GDBM_File',
                   2799: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2800: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2801:     foreach my $key (keys %hash) {
1.180     albertel 2802:       if ($key=~ /:$symb/) {
1.168     albertel 2803: 	delete($hash{$key});
                   2804:       }
                   2805:     }
                   2806:   }
                   2807: }
                   2808: 
1.167     albertel 2809: sub tmpstore {
1.168     albertel 2810:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2811: 
                   2812:   if (!$symb) {
                   2813:     $symb=&symbread();
1.620     albertel 2814:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2815:   }
                   2816:   $symb=escape($symb);
                   2817: 
                   2818:   if (!$namespace) {
                   2819:     # I don't think we would ever want to store this for a course.
                   2820:     # it seems this will only be used if we don't have a course.
1.620     albertel 2821:     #$namespace=$env{'request.course.id'};
1.168     albertel 2822:     #if (!$namespace) {
1.620     albertel 2823:       $namespace=$env{'request.state'};
1.168     albertel 2824:     #}
                   2825:   }
                   2826:   $namespace=~s/\//\_/g;
                   2827:   $namespace=~s/\W//g;
1.620     albertel 2828:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2829:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2830:   if ($domain eq 'public' && $stuname eq 'public') {
                   2831:       $stuname=$ENV{'REMOTE_ADDR'};
                   2832:   }
1.168     albertel 2833:   my $now=time;
                   2834:   my %hash;
                   2835:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2836:   if (tie(%hash,'GDBM_File',
                   2837: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2838: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2839:     $hash{"version:$symb"}++;
                   2840:     my $version=$hash{"version:$symb"};
                   2841:     my $allkeys=''; 
                   2842:     foreach my $key (keys(%$storehash)) {
                   2843:       $allkeys.=$key.':';
1.591     albertel 2844:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2845:     }
                   2846:     $hash{"$version:$symb:timestamp"}=$now;
                   2847:     $allkeys.='timestamp';
                   2848:     $hash{"$version:keys:$symb"}=$allkeys;
                   2849:     if (untie(%hash)) {
                   2850:       return 'ok';
                   2851:     } else {
                   2852:       return "error:$!";
                   2853:     }
                   2854:   } else {
                   2855:     return "error:$!";
                   2856:   }
                   2857: }
1.167     albertel 2858: 
1.168     albertel 2859: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2860: 
1.168     albertel 2861: sub tmprestore {
                   2862:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2863: 
1.168     albertel 2864:   if (!$symb) {
                   2865:     $symb=&symbread();
1.620     albertel 2866:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2867:   }
                   2868:   $symb=escape($symb);
                   2869: 
1.620     albertel 2870:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2871: 
1.620     albertel 2872:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2873:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2874:   if ($domain eq 'public' && $stuname eq 'public') {
                   2875:       $stuname=$ENV{'REMOTE_ADDR'};
                   2876:   }
1.168     albertel 2877:   my %returnhash;
                   2878:   $namespace=~s/\//\_/g;
                   2879:   $namespace=~s/\W//g;
                   2880:   my %hash;
                   2881:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2882:   if (tie(%hash,'GDBM_File',
                   2883: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2884: 	  &GDBM_READER(),0640)) {
1.168     albertel 2885:     my $version=$hash{"version:$symb"};
                   2886:     $returnhash{'version'}=$version;
                   2887:     my $scope;
                   2888:     for ($scope=1;$scope<=$version;$scope++) {
                   2889:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2890:       my @keys=split(/:/,$vkeys);
                   2891:       my $key;
                   2892:       $returnhash{"$scope:keys"}=$vkeys;
                   2893:       foreach $key (@keys) {
1.591     albertel 2894: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2895: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2896:       }
                   2897:     }
1.168     albertel 2898:     if (!(untie(%hash))) {
                   2899:       return "error:$!";
                   2900:     }
                   2901:   } else {
                   2902:     return "error:$!";
                   2903:   }
                   2904:   return %returnhash;
1.167     albertel 2905: }
                   2906: 
1.9       www      2907: # ----------------------------------------------------------------------- Store
                   2908: 
                   2909: sub store {
1.124     www      2910:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2911:     my $home='';
                   2912: 
1.168     albertel 2913:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2914: 
1.213     www      2915:     $symb=&symbclean($symb);
1.122     albertel 2916:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2917: 
1.620     albertel 2918:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2919:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2920: 
                   2921:     &devalidate($symb,$stuname,$domain);
1.109     www      2922: 
                   2923:     $symb=escape($symb);
1.187     www      2924:     if (!$namespace) { 
1.620     albertel 2925:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2926:           return ''; 
                   2927:        } 
                   2928:     }
1.620     albertel 2929:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2930: 
                   2931:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2932:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2933: 
1.12      www      2934:     my $namevalue='';
1.800     albertel 2935:     foreach my $key (keys(%$storehash)) {
                   2936:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2937:     }
1.12      www      2938:     $namevalue=~s/\&$//;
1.187     www      2939:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2940:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2941: }
                   2942: 
1.47      www      2943: # -------------------------------------------------------------- Critical Store
                   2944: 
                   2945: sub cstore {
1.124     www      2946:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2947:     my $home='';
                   2948: 
1.168     albertel 2949:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2950: 
1.213     www      2951:     $symb=&symbclean($symb);
1.122     albertel 2952:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2953: 
1.620     albertel 2954:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2955:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2956: 
                   2957:     &devalidate($symb,$stuname,$domain);
1.109     www      2958: 
                   2959:     $symb=escape($symb);
1.187     www      2960:     if (!$namespace) { 
1.620     albertel 2961:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2962:           return ''; 
                   2963:        } 
                   2964:     }
1.620     albertel 2965:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2966: 
                   2967:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2968:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2969: 
1.47      www      2970:     my $namevalue='';
1.800     albertel 2971:     foreach my $key (keys(%$storehash)) {
                   2972:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2973:     }
1.47      www      2974:     $namevalue=~s/\&$//;
1.187     www      2975:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2976:     return critical
                   2977:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2978: }
                   2979: 
1.9       www      2980: # --------------------------------------------------------------------- Restore
                   2981: 
                   2982: sub restore {
1.124     www      2983:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2984:     my $home='';
                   2985: 
1.168     albertel 2986:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2987: 
1.122     albertel 2988:     if (!$symb) {
                   2989:       unless ($symb=escape(&symbread())) { return ''; }
                   2990:     } else {
1.213     www      2991:       $symb=&escape(&symbclean($symb));
1.122     albertel 2992:     }
1.188     www      2993:     if (!$namespace) { 
1.620     albertel 2994:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2995:           return ''; 
                   2996:        } 
                   2997:     }
1.620     albertel 2998:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2999:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3000:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3001:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3002: 
1.12      www      3003:     my %returnhash=();
1.800     albertel 3004:     foreach my $line (split(/\&/,$answer)) {
                   3005: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3006:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3007:     }
1.75      www      3008:     my $version;
                   3009:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3010:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3011:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3012:        }
1.75      www      3013:     }
1.13      www      3014:     return %returnhash;
1.34      www      3015: }
                   3016: 
                   3017: # ---------------------------------------------------------- Course Description
                   3018: 
                   3019: sub coursedescription {
1.731     albertel 3020:     my ($courseid,$args)=@_;
1.34      www      3021:     $courseid=~s/^\///;
1.49      www      3022:     $courseid=~s/\_/\//g;
1.34      www      3023:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3024:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3025:     my $normalid=$cdomain.'_'.$cnum;
                   3026:     # need to always cache even if we get errors otherwise we keep 
                   3027:     # trying and trying and trying to get the course description.
                   3028:     my %envhash=();
                   3029:     my %returnhash=();
1.731     albertel 3030:     
                   3031:     my $expiretime=600;
                   3032:     if ($env{'request.course.id'} eq $normalid) {
                   3033: 	$expiretime=120;
                   3034:     }
                   3035: 
                   3036:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3037:     if (!$args->{'freshen_cache'}
                   3038: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3039: 	foreach my $key (keys(%env)) {
                   3040: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3041: 	    my ($setting) = $1;
                   3042: 	    $returnhash{$setting} = $env{$key};
                   3043: 	}
                   3044: 	return %returnhash;
                   3045:     }
                   3046: 
                   3047:     # get the data agin
                   3048:     if (!$args->{'one_time'}) {
                   3049: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3050:     }
1.811     albertel 3051: 
1.34      www      3052:     if ($chome ne 'no_host') {
1.302     albertel 3053:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3054:        if (!exists($returnhash{'con_lost'})) {
                   3055:            $returnhash{'home'}= $chome;
                   3056: 	   $returnhash{'domain'} = $cdomain;
                   3057: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3058:            if (!defined($returnhash{'type'})) {
                   3059:                $returnhash{'type'} = 'Course';
                   3060:            }
1.130     albertel 3061:            while (my ($name,$value) = each %returnhash) {
1.53      www      3062:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3063:            }
1.270     www      3064:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3065:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3066: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3067:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3068:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3069:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3070:        }
                   3071:     }
1.731     albertel 3072:     if (!$args->{'one_time'}) {
                   3073: 	&appenv(%envhash);
                   3074:     }
1.302     albertel 3075:     return %returnhash;
1.461     www      3076: }
                   3077: 
                   3078: # -------------------------------------------------See if a user is privileged
                   3079: 
                   3080: sub privileged {
                   3081:     my ($username,$domain)=@_;
                   3082:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3083: 			&homeserver($username,$domain));
                   3084:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3085:     my $now=time;
                   3086:     if ($rolesdump ne '') {
1.800     albertel 3087:         foreach my $entry (split(/&/,$rolesdump)) {
                   3088: 	    if ($entry!~/^rolesdef_/) {
                   3089: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3090: 		$area=~s/\_\w\w$//;
                   3091: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3092: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3093: 		    my $active=1;
                   3094: 		    if ($tend) {
                   3095: 			if ($tend<$now) { $active=0; }
                   3096: 		    }
                   3097: 		    if ($tstart) {
                   3098: 			if ($tstart>$now) { $active=0; }
                   3099: 		    }
                   3100: 		    if ($active) { return 1; }
                   3101: 		}
                   3102: 	    }
                   3103: 	}
                   3104:     }
                   3105:     return 0;
1.9       www      3106: }
1.1       albertel 3107: 
1.103     harris41 3108: # -------------------------------------------------------- Get user privileges
1.11      www      3109: 
                   3110: sub rolesinit {
                   3111:     my ($domain,$username,$authhost)=@_;
                   3112:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3113:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3114:     my %allroles=();
1.678     raeburn  3115:     my %allgroups=();   
1.11      www      3116:     my $now=time;
1.743     albertel 3117:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3118:     my $group_privs;
1.11      www      3119: 
                   3120:     if ($rolesdump ne '') {
1.800     albertel 3121:         foreach my $entry (split(/&/,$rolesdump)) {
                   3122: 	  if ($entry!~/^rolesdef_/) {
                   3123:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3124: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3125:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3126: 	    if ($role=~/^cr/) { 
1.807     albertel 3127: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3128: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3129: 		    ($tend,$tstart)=split('_',$trest);
                   3130: 		} else {
                   3131: 		    $trole=$role;
                   3132: 		}
1.678     raeburn  3133:             } elsif ($role =~ m|^gr/|) {
                   3134:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3135:                 ($trole,$group_privs) = split(/\//,$trole);
                   3136:                 $group_privs = &unescape($group_privs);
1.587     albertel 3137: 	    } else {
                   3138: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3139: 	    }
1.743     albertel 3140: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3141: 					 $username);
                   3142: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3143:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3144:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3145:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3146: 		my $spec=$trole.'.'.$area;
                   3147: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3148: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3149:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3150:                 } elsif ($trole eq 'gr') {
                   3151:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3152: 		} else {
1.567     raeburn  3153:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3154: 		}
1.12      www      3155:             }
1.662     raeburn  3156:           }
1.191     harris41 3157:         }
1.743     albertel 3158:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3159:         $userroles{'user.adv'}    = $adv;
                   3160: 	$userroles{'user.author'} = $author;
1.620     albertel 3161:         $env{'user.adv'}=$adv;
1.11      www      3162:     }
1.743     albertel 3163:     return \%userroles;  
1.11      www      3164: }
                   3165: 
1.567     raeburn  3166: sub set_arearole {
                   3167:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3168: # log the associated role with the area
                   3169:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3170:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3171: }
                   3172: 
                   3173: sub custom_roleprivs {
                   3174:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3175:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3176:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3177:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3178:         my ($rdummy,$roledef)=
                   3179:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3180:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3181:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3182:             if (defined($syspriv)) {
                   3183:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3184:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3185:             }
                   3186:             if ($tdomain ne '') {
                   3187:                 if (defined($dompriv)) {
                   3188:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3189:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3190:                 }
                   3191:                 if (($trest ne '') && (defined($coursepriv))) {
                   3192:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3193:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3194:                 }
                   3195:             }
                   3196:         }
                   3197:     }
                   3198: }
                   3199: 
1.678     raeburn  3200: sub group_roleprivs {
                   3201:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3202:     my $access = 1;
                   3203:     my $now = time;
                   3204:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3205:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3206:     if ($access) {
1.811     albertel 3207:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3208:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3209:     }
                   3210: }
1.567     raeburn  3211: 
                   3212: sub standard_roleprivs {
                   3213:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3214:     if (defined($pr{$trole.':s'})) {
                   3215:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3216:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3217:     }
                   3218:     if ($tdomain ne '') {
                   3219:         if (defined($pr{$trole.':d'})) {
                   3220:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3221:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3222:         }
                   3223:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3224:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3225:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3226:         }
                   3227:     }
                   3228: }
                   3229: 
                   3230: sub set_userprivs {
1.678     raeburn  3231:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3232:     my $author=0;
                   3233:     my $adv=0;
1.678     raeburn  3234:     my %grouproles = ();
                   3235:     if (keys(%{$allgroups}) > 0) {
                   3236:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3237:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3238:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3239:                 $trole = $1;
                   3240:                 $area = $2;
1.681     raeburn  3241:                 $sec = $3;
                   3242:                 $extendedarea = $area.$sec;
                   3243:                 if (exists($$allgroups{$area})) {
                   3244:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3245:                         my $spec = $trole.'.'.$extendedarea;
                   3246:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3247:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3248:                     }
                   3249:                 }
                   3250:             }
                   3251:         }
                   3252:     }
1.800     albertel 3253:     foreach my $group (keys(%grouproles)) {
                   3254:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3255:     }
1.800     albertel 3256:     foreach my $role (keys(%{$allroles})) {
                   3257:         my %thesepriv;
                   3258:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3259:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3260:             if ($item ne '') {
                   3261:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3262:                 if ($restrictions eq '') {
                   3263:                     $thesepriv{$privilege}='F';
                   3264:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3265:                     $thesepriv{$privilege}.=$restrictions;
                   3266:                 }
                   3267:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3268:             }
                   3269:         }
                   3270:         my $thesestr='';
1.800     albertel 3271:         foreach my $priv (keys(%thesepriv)) {
                   3272: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3273: 	}
                   3274:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3275:     }
                   3276:     return ($author,$adv);
                   3277: }
                   3278: 
1.12      www      3279: # --------------------------------------------------------------- get interface
                   3280: 
                   3281: sub get {
1.131     albertel 3282:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3283:    my $items='';
1.800     albertel 3284:    foreach my $item (@$storearr) {
                   3285:        $items.=&escape($item).'&';
1.191     harris41 3286:    }
1.12      www      3287:    $items=~s/\&$//;
1.620     albertel 3288:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3289:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3290:    my $uhome=&homeserver($uname,$udomain);
                   3291: 
1.133     albertel 3292:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3293:    my @pairs=split(/\&/,$rep);
1.273     albertel 3294:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3295:      return @pairs;
                   3296:    }
1.15      www      3297:    my %returnhash=();
1.42      www      3298:    my $i=0;
1.800     albertel 3299:    foreach my $item (@$storearr) {
                   3300:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3301:       $i++;
1.191     harris41 3302:    }
1.15      www      3303:    return %returnhash;
1.27      www      3304: }
                   3305: 
                   3306: # --------------------------------------------------------------- del interface
                   3307: 
                   3308: sub del {
1.133     albertel 3309:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3310:    my $items='';
1.800     albertel 3311:    foreach my $item (@$storearr) {
                   3312:        $items.=&escape($item).'&';
1.191     harris41 3313:    }
1.27      www      3314:    $items=~s/\&$//;
1.620     albertel 3315:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3316:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3317:    my $uhome=&homeserver($uname,$udomain);
                   3318: 
                   3319:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3320: }
                   3321: 
                   3322: # -------------------------------------------------------------- dump interface
                   3323: 
                   3324: sub dump {
1.755     albertel 3325:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3326:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3327:     if (!$uname) { $uname=$env{'user.name'}; }
                   3328:     my $uhome=&homeserver($uname,$udomain);
                   3329:     if ($regexp) {
                   3330: 	$regexp=&escape($regexp);
                   3331:     } else {
                   3332: 	$regexp='.';
                   3333:     }
                   3334:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3335:     my @pairs=split(/\&/,$rep);
                   3336:     my %returnhash=();
                   3337:     foreach my $item (@pairs) {
                   3338: 	my ($key,$value)=split(/=/,$item,2);
                   3339: 	$key = &unescape($key);
                   3340: 	next if ($key =~ /^error: 2 /);
                   3341: 	$returnhash{$key}=&thaw_unescape($value);
                   3342:     }
                   3343:     return %returnhash;
1.407     www      3344: }
                   3345: 
1.717     albertel 3346: # --------------------------------------------------------- dumpstore interface
                   3347: 
                   3348: sub dumpstore {
                   3349:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3350:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3351:    if (!$uname) { $uname=$env{'user.name'}; }
                   3352:    my $uhome=&homeserver($uname,$udomain);
                   3353:    if ($regexp) {
                   3354:        $regexp=&escape($regexp);
                   3355:    } else {
                   3356:        $regexp='.';
                   3357:    }
                   3358:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3359:    my @pairs=split(/\&/,$rep);
                   3360:    my %returnhash=();
                   3361:    foreach my $item (@pairs) {
                   3362:        my ($key,$value)=split(/=/,$item,2);
                   3363:        next if ($key =~ /^error: 2 /);
                   3364:        $returnhash{$key}=&thaw_unescape($value);
                   3365:    }
                   3366:    return %returnhash;
1.717     albertel 3367: }
                   3368: 
1.407     www      3369: # -------------------------------------------------------------- keys interface
                   3370: 
                   3371: sub getkeys {
                   3372:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3373:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3374:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3375:    my $uhome=&homeserver($uname,$udomain);
                   3376:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3377:    my @keyarray=();
1.800     albertel 3378:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3379:       next if ($key =~ /^error: 2 /);
1.800     albertel 3380:       push(@keyarray,&unescape($key));
1.407     www      3381:    }
                   3382:    return @keyarray;
1.318     matthew  3383: }
                   3384: 
1.319     matthew  3385: # --------------------------------------------------------------- currentdump
                   3386: sub currentdump {
1.328     matthew  3387:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3388:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3389:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3390:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3391:    my $uhome = &homeserver($sname,$sdom);
                   3392:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3393:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3394:    #
1.318     matthew  3395:    my %returnhash=();
1.319     matthew  3396:    #
                   3397:    if ($rep eq "unknown_cmd") { 
                   3398:        # an old lond will not know currentdump
                   3399:        # Do a dump and make it look like a currentdump
1.822     albertel 3400:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3401:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3402:        my %hash = @tmp;
                   3403:        @tmp=();
1.424     matthew  3404:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3405:    } else {
                   3406:        my @pairs=split(/\&/,$rep);
1.800     albertel 3407:        foreach my $pair (@pairs) {
                   3408:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3409:            my ($symb,$param) = split(/:/,$key);
                   3410:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3411:                                                         &thaw_unescape($value);
1.319     matthew  3412:        }
1.191     harris41 3413:    }
1.12      www      3414:    return %returnhash;
1.424     matthew  3415: }
                   3416: 
                   3417: sub convert_dump_to_currentdump{
                   3418:     my %hash = %{shift()};
                   3419:     my %returnhash;
                   3420:     # Code ripped from lond, essentially.  The only difference
                   3421:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3422:     # we might run in to problems with parameter names =~ /^v\./
                   3423:     while (my ($key,$value) = each(%hash)) {
                   3424:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3425: 	$symb  = &unescape($symb);
                   3426: 	$param = &unescape($param);
1.424     matthew  3427:         next if ($v eq 'version' || $symb eq 'keys');
                   3428:         next if (exists($returnhash{$symb}) &&
                   3429:                  exists($returnhash{$symb}->{$param}) &&
                   3430:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3431:         $returnhash{$symb}->{$param}=$value;
                   3432:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3433:     }
                   3434:     #
                   3435:     # Remove all of the keys in the hashes which keep track of
                   3436:     # the version of the parameter.
                   3437:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3438:         # use a foreach because we are going to delete from the hash.
                   3439:         foreach my $key (keys(%$param_hash)) {
                   3440:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3441:         }
                   3442:     }
                   3443:     return \%returnhash;
1.12      www      3444: }
                   3445: 
1.627     albertel 3446: # ------------------------------------------------------ critical inc interface
                   3447: 
                   3448: sub cinc {
                   3449:     return &inc(@_,'critical');
                   3450: }
                   3451: 
1.449     matthew  3452: # --------------------------------------------------------------- inc interface
                   3453: 
                   3454: sub inc {
1.627     albertel 3455:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3456:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3457:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3458:     my $uhome=&homeserver($uname,$udomain);
                   3459:     my $items='';
                   3460:     if (! ref($store)) {
                   3461:         # got a single value, so use that instead
                   3462:         $items = &escape($store).'=&';
                   3463:     } elsif (ref($store) eq 'SCALAR') {
                   3464:         $items = &escape($$store).'=&';        
                   3465:     } elsif (ref($store) eq 'ARRAY') {
                   3466:         $items = join('=&',map {&escape($_);} @{$store});
                   3467:     } elsif (ref($store) eq 'HASH') {
                   3468:         while (my($key,$value) = each(%{$store})) {
                   3469:             $items.= &escape($key).'='.&escape($value).'&';
                   3470:         }
                   3471:     }
                   3472:     $items=~s/\&$//;
1.627     albertel 3473:     if ($critical) {
                   3474: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3475:     } else {
                   3476: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3477:     }
1.449     matthew  3478: }
                   3479: 
1.12      www      3480: # --------------------------------------------------------------- put interface
                   3481: 
                   3482: sub put {
1.134     albertel 3483:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3484:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3485:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3486:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3487:    my $items='';
1.800     albertel 3488:    foreach my $item (keys(%$storehash)) {
                   3489:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3490:    }
1.12      www      3491:    $items=~s/\&$//;
1.134     albertel 3492:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3493: }
                   3494: 
1.631     albertel 3495: # ------------------------------------------------------------ newput interface
                   3496: 
                   3497: sub newput {
                   3498:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3499:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3500:    if (!$uname) { $uname=$env{'user.name'}; }
                   3501:    my $uhome=&homeserver($uname,$udomain);
                   3502:    my $items='';
                   3503:    foreach my $key (keys(%$storehash)) {
                   3504:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3505:    }
                   3506:    $items=~s/\&$//;
                   3507:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3508: }
                   3509: 
                   3510: # ---------------------------------------------------------  putstore interface
                   3511: 
1.524     raeburn  3512: sub putstore {
1.715     albertel 3513:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3514:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3515:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3516:    my $uhome=&homeserver($uname,$udomain);
                   3517:    my $items='';
1.715     albertel 3518:    foreach my $key (keys(%$storehash)) {
                   3519:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3520:    }
1.715     albertel 3521:    $items=~s/\&$//;
1.716     albertel 3522:    my $esc_symb=&escape($symb);
                   3523:    my $esc_v=&escape($version);
1.715     albertel 3524:    my $reply =
1.716     albertel 3525:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3526: 	      $uhome);
                   3527:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3528:        # gfall back to way things use to be done
1.715     albertel 3529:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3530: 			    $uname);
1.524     raeburn  3531:    }
1.715     albertel 3532:    return $reply;
                   3533: }
                   3534: 
                   3535: sub old_putstore {
1.716     albertel 3536:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3537:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3538:     if (!$uname) { $uname=$env{'user.name'}; }
                   3539:     my $uhome=&homeserver($uname,$udomain);
                   3540:     my %newstorehash;
1.800     albertel 3541:     foreach my $item (keys(%$storehash)) {
                   3542: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3543: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3544:     }
                   3545:     my $items='';
                   3546:     my %allitems = ();
1.800     albertel 3547:     foreach my $item (keys(%newstorehash)) {
                   3548: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3549: 	    my $key = $1.':keys:'.$2;
                   3550: 	    $allitems{$key} .= $3.':';
                   3551: 	}
1.800     albertel 3552: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3553:     }
1.800     albertel 3554:     foreach my $item (keys(%allitems)) {
                   3555: 	$allitems{$item} =~ s/\:$//;
                   3556: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3557:     }
                   3558:     $items=~s/\&$//;
                   3559:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3560: }
                   3561: 
1.47      www      3562: # ------------------------------------------------------ critical put interface
                   3563: 
                   3564: sub cput {
1.134     albertel 3565:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3566:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3567:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3568:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3569:    my $items='';
1.800     albertel 3570:    foreach my $item (keys(%$storehash)) {
                   3571:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3572:    }
1.47      www      3573:    $items=~s/\&$//;
1.134     albertel 3574:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3575: }
                   3576: 
                   3577: # -------------------------------------------------------------- eget interface
                   3578: 
                   3579: sub eget {
1.133     albertel 3580:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3581:    my $items='';
1.800     albertel 3582:    foreach my $item (@$storearr) {
                   3583:        $items.=&escape($item).'&';
1.191     harris41 3584:    }
1.12      www      3585:    $items=~s/\&$//;
1.620     albertel 3586:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3587:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3588:    my $uhome=&homeserver($uname,$udomain);
                   3589:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3590:    my @pairs=split(/\&/,$rep);
                   3591:    my %returnhash=();
1.42      www      3592:    my $i=0;
1.800     albertel 3593:    foreach my $item (@$storearr) {
                   3594:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3595:       $i++;
1.191     harris41 3596:    }
1.12      www      3597:    return %returnhash;
                   3598: }
                   3599: 
1.667     albertel 3600: # ------------------------------------------------------------ tmpput interface
                   3601: sub tmpput {
1.802     raeburn  3602:     my ($storehash,$server,$context)=@_;
1.667     albertel 3603:     my $items='';
1.800     albertel 3604:     foreach my $item (keys(%$storehash)) {
                   3605: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3606:     }
                   3607:     $items=~s/\&$//;
1.802     raeburn  3608:     if (defined($context)) {
                   3609:         $items .= ':'.&escape($context);
                   3610:     }
1.667     albertel 3611:     return &reply("tmpput:$items",$server);
                   3612: }
                   3613: 
                   3614: # ------------------------------------------------------------ tmpget interface
                   3615: sub tmpget {
1.688     albertel 3616:     my ($token,$server)=@_;
                   3617:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3618:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3619:     my %returnhash;
                   3620:     foreach my $item (split(/\&/,$rep)) {
                   3621: 	my ($key,$value)=split(/=/,$item);
                   3622: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3623:     }
                   3624:     return %returnhash;
                   3625: }
                   3626: 
1.688     albertel 3627: # ------------------------------------------------------------ tmpget interface
                   3628: sub tmpdel {
                   3629:     my ($token,$server)=@_;
                   3630:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3631:     return &reply("tmpdel:$token",$server);
                   3632: }
                   3633: 
1.765     albertel 3634: # -------------------------------------------------- portfolio access checking
                   3635: 
                   3636: sub portfolio_access {
1.766     albertel 3637:     my ($requrl) = @_;
1.765     albertel 3638:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3639:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3640:     if ($result) {
                   3641:         my %setters;
                   3642:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3643:             my ($startblock,$endblock) =
                   3644:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3645:             if ($startblock && $endblock) {
                   3646:                 return 'B';
                   3647:             }
                   3648:         } else {
                   3649:             my ($startblock,$endblock) =
                   3650:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3651:             if ($startblock && $endblock) {
                   3652:                 return 'B';
                   3653:             }
                   3654:         }
                   3655:     }
1.765     albertel 3656:     if ($result eq 'ok') {
1.766     albertel 3657:        return 'F';
1.765     albertel 3658:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3659:        return 'A';
1.765     albertel 3660:     }
1.766     albertel 3661:     return '';
1.765     albertel 3662: }
                   3663: 
                   3664: sub get_portfolio_access {
1.767     albertel 3665:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3666: 
                   3667:     if (!ref($access_hash)) {
                   3668: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3669: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3670: 						   $file_name);
                   3671: 	$access_hash = $access_controls{$file_name};
                   3672:     }
                   3673: 
1.765     albertel 3674:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3675:     my $now = time;
                   3676:     if (ref($access_hash) eq 'HASH') {
                   3677:         foreach my $key (keys(%{$access_hash})) {
                   3678:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3679:             if ($start > $now) {
                   3680:                 next;
                   3681:             }
                   3682:             if ($end && $end<$now) {
                   3683:                 next;
                   3684:             }
                   3685:             if ($scope eq 'public') {
                   3686:                 $public = $key;
                   3687:                 last;
                   3688:             } elsif ($scope eq 'guest') {
                   3689:                 $guest = $key;
                   3690:             } elsif ($scope eq 'domains') {
                   3691:                 push(@domains,$key);
                   3692:             } elsif ($scope eq 'users') {
                   3693:                 push(@users,$key);
                   3694:             } elsif ($scope eq 'course') {
                   3695:                 push(@courses,$key);
                   3696:             } elsif ($scope eq 'group') {
                   3697:                 push(@groups,$key);
                   3698:             }
                   3699:         }
                   3700:         if ($public) {
                   3701:             return 'ok';
                   3702:         }
                   3703:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3704:             if ($guest) {
                   3705:                 return $guest;
                   3706:             }
                   3707:         } else {
                   3708:             if (@domains > 0) {
                   3709:                 foreach my $domkey (@domains) {
                   3710:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3711:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3712:                             return 'ok';
                   3713:                         }
                   3714:                     }
                   3715:                 }
                   3716:             }
                   3717:             if (@users > 0) {
                   3718:                 foreach my $userkey (@users) {
1.865     raeburn  3719:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3720:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3721:                             if (ref($item) eq 'HASH') {
                   3722:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3723:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3724:                                     return 'ok';
                   3725:                                 }
                   3726:                             }
                   3727:                         }
                   3728:                     } 
1.765     albertel 3729:                 }
                   3730:             }
                   3731:             my %roleshash;
                   3732:             my @courses_and_groups = @courses;
                   3733:             push(@courses_and_groups,@groups); 
                   3734:             if (@courses_and_groups > 0) {
                   3735:                 my (%allgroups,%allroles); 
                   3736:                 my ($start,$end,$role,$sec,$group);
                   3737:                 foreach my $envkey (%env) {
1.811     albertel 3738:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3739:                         my $cid = $2.'_'.$3; 
                   3740:                         if ($1 eq 'gr') {
                   3741:                             $group = $4;
                   3742:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3743:                         } else {
                   3744:                             if ($4 eq '') {
                   3745:                                 $sec = 'none';
                   3746:                             } else {
                   3747:                                 $sec = $4;
                   3748:                             }
                   3749:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3750:                         }
1.811     albertel 3751:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3752:                         my $cid = $2.'_'.$3;
                   3753:                         if ($4 eq '') {
                   3754:                             $sec = 'none';
                   3755:                         } else {
                   3756:                             $sec = $4;
                   3757:                         }
                   3758:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3759:                     }
                   3760:                 }
                   3761:                 if (keys(%allroles) == 0) {
                   3762:                     return;
                   3763:                 }
                   3764:                 foreach my $key (@courses_and_groups) {
                   3765:                     my %content = %{$$access_hash{$key}};
                   3766:                     my $cnum = $content{'number'};
                   3767:                     my $cdom = $content{'domain'};
                   3768:                     my $cid = $cdom.'_'.$cnum;
                   3769:                     if (!exists($allroles{$cid})) {
                   3770:                         next;
                   3771:                     }    
                   3772:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3773:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3774:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3775:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3776:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3777:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3778:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3779:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3780:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3781:                                         if (grep/^all$/,@sections) {
                   3782:                                             return 'ok';
                   3783:                                         } else {
                   3784:                                             if (grep/^$sec$/,@sections) {
                   3785:                                                 return 'ok';
                   3786:                                             }
                   3787:                                         }
                   3788:                                     }
                   3789:                                 }
                   3790:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3791:                                     if (grep/^none$/,@groups) {
                   3792:                                         return 'ok';
                   3793:                                     }
                   3794:                                 } else {
                   3795:                                     if (grep/^all$/,@groups) {
                   3796:                                         return 'ok';
                   3797:                                     } 
                   3798:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3799:                                         if (grep/^$group$/,@groups) {
                   3800:                                             return 'ok';
                   3801:                                         }
                   3802:                                     }
                   3803:                                 } 
                   3804:                             }
                   3805:                         }
                   3806:                     }
                   3807:                 }
                   3808:             }
                   3809:             if ($guest) {
                   3810:                 return $guest;
                   3811:             }
                   3812:         }
                   3813:     }
                   3814:     return;
                   3815: }
                   3816: 
                   3817: sub course_group_datechecker {
                   3818:     my ($dates,$now,$status) = @_;
                   3819:     my ($start,$end) = split(/\./,$dates);
                   3820:     if (!$start && !$end) {
                   3821:         return 'ok';
                   3822:     }
                   3823:     if (grep/^active$/,@{$status}) {
                   3824:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3825:             return 'ok';
                   3826:         }
                   3827:     }
                   3828:     if (grep/^previous$/,@{$status}) {
                   3829:         if ($end > $now ) {
                   3830:             return 'ok';
                   3831:         }
                   3832:     }
                   3833:     if (grep/^future$/,@{$status}) {
                   3834:         if ($start > $now) {
                   3835:             return 'ok';
                   3836:         }
                   3837:     }
                   3838:     return; 
                   3839: }
                   3840: 
                   3841: sub parse_portfolio_url {
                   3842:     my ($url) = @_;
                   3843: 
                   3844:     my ($type,$udom,$unum,$group,$file_name);
                   3845:     
1.823     albertel 3846:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3847: 	$type = 1;
                   3848:         $udom = $1;
                   3849:         $unum = $2;
                   3850:         $file_name = $3;
1.823     albertel 3851:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3852: 	$type = 2;
                   3853:         $udom = $1;
                   3854:         $unum = $2;
                   3855:         $group = $3;
                   3856:         $file_name = $3.'/'.$4;
                   3857:     }
                   3858:     if (wantarray) {
                   3859: 	return ($type,$udom,$unum,$file_name,$group);
                   3860:     }
                   3861:     return $type;
                   3862: }
                   3863: 
                   3864: sub is_portfolio_url {
                   3865:     my ($url) = @_;
                   3866:     return scalar(&parse_portfolio_url($url));
                   3867: }
                   3868: 
1.798     raeburn  3869: sub is_portfolio_file {
                   3870:     my ($file) = @_;
1.820     raeburn  3871:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3872:         return 1;
                   3873:     }
                   3874:     return;
                   3875: }
                   3876: 
                   3877: 
1.341     www      3878: # ---------------------------------------------- Custom access rule evaluation
                   3879: 
                   3880: sub customaccess {
                   3881:     my ($priv,$uri)=@_;
1.807     albertel 3882:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3883:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3884:     $udom = &LONCAPA::clean_domain($udom);
                   3885:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3886:     my $access=0;
1.800     albertel 3887:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 3888: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   3889: 	if ($type eq 'user') {
                   3890: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 3891: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 3892: 		if ($tdom) {
                   3893: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   3894: 		}
1.896     albertel 3895: 		if ($tuname) {
                   3896: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 3897: 		}
                   3898: 		$access=($effect eq 'allow');
                   3899: 		last;
                   3900: 	    }
                   3901: 	} else {
                   3902: 	    if ($role) {
                   3903: 		if ($role ne $urole) { next; }
                   3904: 	    }
                   3905: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3906: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   3907: 		if ($tdom) {
                   3908: 		    if ($tdom ne $udom) { next; }
                   3909: 		}
                   3910: 		if ($tcrs) {
                   3911: 		    if ($tcrs ne $ucrs) { next; }
                   3912: 		}
                   3913: 		if ($tsec) {
                   3914: 		    if ($tsec ne $usec) { next; }
                   3915: 		}
                   3916: 		$access=($effect eq 'allow');
                   3917: 		last;
                   3918: 	    }
                   3919: 	    if ($realm eq '' && $role eq '') {
                   3920: 		$access=($effect eq 'allow');
                   3921: 	    }
1.402     bowersj2 3922: 	}
1.341     www      3923:     }
                   3924:     return $access;
                   3925: }
                   3926: 
1.103     harris41 3927: # ------------------------------------------------- Check for a user privilege
1.12      www      3928: 
                   3929: sub allowed {
1.810     raeburn  3930:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3931:     my $ver_orguri=$uri;
1.439     www      3932:     $uri=&deversion($uri);
1.152     www      3933:     my $orguri=$uri;
1.52      www      3934:     $uri=&declutter($uri);
1.809     raeburn  3935: 
1.810     raeburn  3936:     if ($priv eq 'evb') {
                   3937: # Evade communication block restrictions for specified role in a course
                   3938:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3939:             return $1;
                   3940:         } else {
                   3941:             return;
                   3942:         }
                   3943:     }
                   3944: 
1.620     albertel 3945:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3946: # Free bre access to adm and meta resources
1.775     albertel 3947:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3948: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3949: 	&& ($priv eq 'bre')) {
1.14      www      3950: 	return 'F';
1.159     www      3951:     }
                   3952: 
1.545     banghart 3953: # Free bre access to user's own portfolio contents
1.714     raeburn  3954:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3955:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3956: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3957:         my %setters;
                   3958:         my ($startblock,$endblock) = 
                   3959:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3960:         if ($startblock && $endblock) {
                   3961:             return 'B';
                   3962:         } else {
                   3963:             return 'F';
                   3964:         }
1.545     banghart 3965:     }
                   3966: 
1.762     raeburn  3967: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3968:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3969:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3970:         if (exists($env{'request.course.id'})) {
                   3971:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3972:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3973:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3974:                 my $courseprivid=$env{'request.course.id'};
                   3975:                 $courseprivid=~s/\_/\//;
                   3976:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3977:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3978:                     return $1; 
1.762     raeburn  3979:                 } else {
                   3980:                     if ($env{'request.course.sec'}) {
                   3981:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3982:                     }
                   3983:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3984:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3985:                         return $2;
                   3986:                     }
1.714     raeburn  3987:                 }
                   3988:             }
                   3989:         }
                   3990:     }
                   3991: 
1.159     www      3992: # Free bre to public access
                   3993: 
                   3994:     if ($priv eq 'bre') {
1.238     www      3995:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3996: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3997:            return 'F'; 
                   3998:         }
1.238     www      3999:         if ($copyright eq 'priv') {
                   4000:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4001: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4002: 		return '';
                   4003:             }
                   4004:         }
                   4005:         if ($copyright eq 'domain') {
                   4006:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4007: 	    unless (($env{'user.domain'} eq $1) ||
                   4008:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4009: 		return '';
                   4010:             }
1.262     matthew  4011:         }
1.620     albertel 4012:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4013:             # Library role, so allow browsing of resources in this domain.
                   4014:             return 'F';
1.238     www      4015:         }
1.341     www      4016:         if ($copyright eq 'custom') {
                   4017: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4018:         }
1.14      www      4019:     }
1.264     matthew  4020:     # Domain coordinator is trying to create a course
1.620     albertel 4021:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4022:         # uri is the requested domain in this case.
                   4023:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4024:         # a role of dc for the domain in question.
1.620     albertel 4025:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4026:     }
1.29      www      4027: 
1.52      www      4028:     my $thisallowed='';
                   4029:     my $statecond=0;
                   4030:     my $courseprivid='';
                   4031: 
                   4032: # Course
                   4033: 
1.620     albertel 4034:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4035:        $thisallowed.=$1;
                   4036:     }
1.29      www      4037: 
1.52      www      4038: # Domain
                   4039: 
1.620     albertel 4040:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4041:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4042:        $thisallowed.=$1;
                   4043:     }
1.52      www      4044: 
                   4045: # Course: uri itself is a course
1.66      www      4046:     my $courseuri=$uri;
                   4047:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4048:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4049: 
1.620     albertel 4050:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4051:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4052:        $thisallowed.=$1;
                   4053:     }
1.29      www      4054: 
1.665     albertel 4055: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4056: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4057:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4058: 	$thisallowed='';
1.671     raeburn  4059:         my ($match)=&is_on_map($uri);
                   4060:         if ($match) {
                   4061:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4062:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4063:                 $thisallowed.=$1;
                   4064:             }
                   4065:         } else {
1.705     albertel 4066:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4067:             if ($refuri) {
                   4068:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4069:                     $thisallowed='F';
1.671     raeburn  4070:                 } else {
                   4071:                     $refuri=&declutter($refuri);
                   4072:                     my ($match) = &is_on_map($refuri);
                   4073:                     if ($match) {
                   4074:                         $thisallowed='F';
                   4075:                     }
1.669     raeburn  4076:                 }
1.671     raeburn  4077:             }
                   4078:         }
1.314     www      4079:     }
1.492     albertel 4080: 
1.766     albertel 4081:     if ($priv eq 'bre'
                   4082: 	&& $thisallowed ne 'F' 
                   4083: 	&& $thisallowed ne '2'
                   4084: 	&& &is_portfolio_url($uri)) {
                   4085: 	$thisallowed = &portfolio_access($uri);
                   4086:     }
                   4087:     
1.52      www      4088: # Full access at system, domain or course-wide level? Exit.
1.29      www      4089: 
                   4090:     if ($thisallowed=~/F/) {
                   4091: 	return 'F';
                   4092:     }
                   4093: 
1.52      www      4094: # If this is generating or modifying users, exit with special codes
1.29      www      4095: 
1.643     www      4096:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4097: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4098: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4099: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4100: 	    unless ($auname) { return $thisallowed; }
                   4101: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4102: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4103: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4104: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4105: 	}
1.52      www      4106: 	return $thisallowed;
                   4107:     }
                   4108: #
1.103     harris41 4109: # Gathered so far: system, domain and course wide privileges
1.52      www      4110: #
                   4111: # Course: See if uri or referer is an individual resource that is part of 
                   4112: # the course
                   4113: 
1.620     albertel 4114:     if ($env{'request.course.id'}) {
1.232     www      4115: 
1.620     albertel 4116:        $courseprivid=$env{'request.course.id'};
                   4117:        if ($env{'request.course.sec'}) {
                   4118:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4119:        }
                   4120:        $courseprivid=~s/\_/\//;
                   4121:        my $checkreferer=1;
1.232     www      4122:        my ($match,$cond)=&is_on_map($uri);
                   4123:        if ($match) {
                   4124:            $statecond=$cond;
1.620     albertel 4125:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4126:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4127:                $thisallowed.=$1;
                   4128:                $checkreferer=0;
                   4129:            }
1.29      www      4130:        }
1.83      www      4131:        
1.148     www      4132:        if ($checkreferer) {
1.620     albertel 4133: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4134:             unless ($refuri) {
1.800     albertel 4135:                 foreach my $key (keys(%env)) {
                   4136: 		    if ($key=~/^httpref\..*\*/) {
                   4137: 			my $pattern=$key;
1.156     www      4138:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4139:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4140:                         $pattern=~s/\//\\\//g;
1.152     www      4141:                         if ($orguri=~/$pattern/) {
1.800     albertel 4142: 			    $refuri=$env{$key};
1.148     www      4143:                         }
                   4144:                     }
1.191     harris41 4145:                 }
1.148     www      4146:             }
1.232     www      4147: 
1.148     www      4148:          if ($refuri) { 
1.152     www      4149: 	  $refuri=&declutter($refuri);
1.232     www      4150:           my ($match,$cond)=&is_on_map($refuri);
                   4151:             if ($match) {
                   4152:               my $refstatecond=$cond;
1.620     albertel 4153:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4154:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4155:                   $thisallowed.=$1;
1.53      www      4156:                   $uri=$refuri;
                   4157:                   $statecond=$refstatecond;
1.52      www      4158:               }
                   4159:           }
1.148     www      4160:         }
1.29      www      4161:        }
1.52      www      4162:    }
1.29      www      4163: 
1.52      www      4164: #
1.103     harris41 4165: # Gathered now: all privileges that could apply, and condition number
1.52      www      4166: # 
                   4167: #
                   4168: # Full or no access?
                   4169: #
1.29      www      4170: 
1.52      www      4171:     if ($thisallowed=~/F/) {
                   4172: 	return 'F';
                   4173:     }
1.29      www      4174: 
1.52      www      4175:     unless ($thisallowed) {
                   4176:         return '';
                   4177:     }
1.29      www      4178: 
1.52      www      4179: # Restrictions exist, deal with them
                   4180: #
                   4181: #   C:according to course preferences
                   4182: #   R:according to resource settings
                   4183: #   L:unless locked
                   4184: #   X:according to user session state
                   4185: #
                   4186: 
                   4187: # Possibly locked functionality, check all courses
1.54      www      4188: # Locks might take effect only after 10 minutes cache expiration for other
                   4189: # courses, and 2 minutes for current course
1.52      www      4190: 
                   4191:     my $envkey;
                   4192:     if ($thisallowed=~/L/) {
1.620     albertel 4193:         foreach $envkey (keys %env) {
1.54      www      4194:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4195:                my $courseid=$2;
                   4196:                my $roleid=$1.'.'.$2;
1.92      www      4197:                $courseid=~s/^\///;
1.54      www      4198:                my $expiretime=600;
1.620     albertel 4199:                if ($env{'request.role'} eq $roleid) {
1.54      www      4200: 		  $expiretime=120;
                   4201:                }
                   4202: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4203:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4204:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4205: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4206:                }
1.620     albertel 4207:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4208:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4209: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4210:                        &log($env{'user.domain'},$env{'user.name'},
                   4211:                             $env{'user.home'},
1.57      www      4212:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4213:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4214:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4215: 		       return '';
                   4216:                    }
                   4217:                }
1.620     albertel 4218:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4219:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4220: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4221:                        &log($env{'user.domain'},$env{'user.name'},
                   4222:                             $env{'user.home'},
1.57      www      4223:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4224:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4225:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4226: 		       return '';
                   4227:                    }
                   4228:                }
                   4229: 	   }
1.29      www      4230:        }
1.52      www      4231:     }
                   4232:    
                   4233: #
                   4234: # Rest of the restrictions depend on selected course
                   4235: #
                   4236: 
1.620     albertel 4237:     unless ($env{'request.course.id'}) {
1.766     albertel 4238: 	if ($thisallowed eq 'A') {
                   4239: 	    return 'A';
1.814     raeburn  4240:         } elsif ($thisallowed eq 'B') {
                   4241:             return 'B';
1.766     albertel 4242: 	} else {
                   4243: 	    return '1';
                   4244: 	}
1.52      www      4245:     }
1.29      www      4246: 
1.52      www      4247: #
                   4248: # Now user is definitely in a course
                   4249: #
1.53      www      4250: 
                   4251: 
                   4252: # Course preferences
                   4253: 
                   4254:    if ($thisallowed=~/C/) {
1.620     albertel 4255:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4256:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4257:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4258: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4259: 	   if ($priv ne 'pch') { 
                   4260: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4261: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4262: 			$env{'request.course.id'});
                   4263: 	   }
1.237     www      4264:            return '';
                   4265:        }
                   4266: 
1.620     albertel 4267:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4268: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4269: 	   if ($priv ne 'pch') { 
                   4270: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4271: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4272: 			$env{'request.course.id'});
                   4273: 	   }
1.54      www      4274:            return '';
                   4275:        }
1.53      www      4276:    }
                   4277: 
                   4278: # Resource preferences
                   4279: 
                   4280:    if ($thisallowed=~/R/) {
1.620     albertel 4281:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4282:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4283: 	   if ($priv ne 'pch') { 
                   4284: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4285: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4286: 	   }
                   4287: 	   return '';
1.54      www      4288:        }
1.53      www      4289:    }
1.30      www      4290: 
1.246     www      4291: # Restricted by state or randomout?
1.30      www      4292: 
1.52      www      4293:    if ($thisallowed=~/X/) {
1.620     albertel 4294:       if ($env{'acc.randomout'}) {
1.579     albertel 4295: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4296:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4297:             return ''; 
                   4298:          }
1.247     www      4299:       }
                   4300:       if (&condval($statecond)) {
1.52      www      4301: 	 return '2';
                   4302:       } else {
                   4303:          return '';
                   4304:       }
                   4305:    }
1.30      www      4306: 
1.766     albertel 4307:     if ($thisallowed eq 'A') {
                   4308: 	return 'A';
1.814     raeburn  4309:     } elsif ($thisallowed eq 'B') {
                   4310:         return 'B';
1.766     albertel 4311:     }
1.52      www      4312:    return 'F';
1.232     www      4313: }
                   4314: 
1.710     albertel 4315: sub split_uri_for_cond {
                   4316:     my $uri=&deversion(&declutter(shift));
                   4317:     my @uriparts=split(/\//,$uri);
                   4318:     my $filename=pop(@uriparts);
                   4319:     my $pathname=join('/',@uriparts);
                   4320:     return ($pathname,$filename);
                   4321: }
1.232     www      4322: # --------------------------------------------------- Is a resource on the map?
                   4323: 
                   4324: sub is_on_map {
1.710     albertel 4325:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4326:     #Trying to find the conditional for the file
1.620     albertel 4327:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4328: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4329:     if ($match) {
1.289     bowersj2 4330: 	return (1,$1);
                   4331:     } else {
1.434     www      4332: 	return (0,0);
1.289     bowersj2 4333:     }
1.12      www      4334: }
                   4335: 
1.427     www      4336: # --------------------------------------------------------- Get symb from alias
                   4337: 
                   4338: sub get_symb_from_alias {
                   4339:     my $symb=shift;
                   4340:     my ($map,$resid,$url)=&decode_symb($symb);
                   4341: # Already is a symb
                   4342:     if ($url) { return $symb; }
                   4343: # Must be an alias
                   4344:     my $aliassymb='';
                   4345:     my %bighash;
1.620     albertel 4346:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4347:                             &GDBM_READER(),0640)) {
                   4348:         my $rid=$bighash{'mapalias_'.$symb};
                   4349: 	if ($rid) {
                   4350: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4351: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4352: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4353: 	}
                   4354:         untie %bighash;
                   4355:     }
                   4356:     return $aliassymb;
                   4357: }
                   4358: 
1.12      www      4359: # ----------------------------------------------------------------- Define Role
                   4360: 
                   4361: sub definerole {
                   4362:   if (allowed('mcr','/')) {
                   4363:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4364:     foreach my $role (split(':',$sysrole)) {
                   4365: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4366:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4367:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4368: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4369:                return "refused:s:$crole&$cqual"; 
                   4370:             }
                   4371:         }
1.191     harris41 4372:     }
1.800     albertel 4373:     foreach my $role (split(':',$domrole)) {
                   4374: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4375:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4376:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4377: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4378:                return "refused:d:$crole&$cqual"; 
                   4379:             }
                   4380:         }
1.191     harris41 4381:     }
1.800     albertel 4382:     foreach my $role (split(':',$courole)) {
                   4383: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4384:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4385:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4386: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4387:                return "refused:c:$crole&$cqual"; 
                   4388:             }
                   4389:         }
1.191     harris41 4390:     }
1.620     albertel 4391:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4392:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4393: 	        "rolesdef_$rolename=".
                   4394:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4395:     return reply($command,$env{'user.home'});
1.12      www      4396:   } else {
                   4397:     return 'refused';
                   4398:   }
1.105     harris41 4399: }
                   4400: 
                   4401: # ---------------- Make a metadata query against the network of library servers
                   4402: 
                   4403: sub metadata_query {
1.244     matthew  4404:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4405:     my %rhash;
1.845     albertel 4406:     my %libserv = &all_library();
1.244     matthew  4407:     my @server_list = (defined($server_array) ? @$server_array
                   4408:                                               : keys(%libserv) );
                   4409:     for my $server (@server_list) {
1.118     harris41 4410: 	unless ($custom or $customshow) {
                   4411: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4412: 	    $rhash{$server}=$reply;
                   4413: 	}
                   4414: 	else {
                   4415: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4416: 			     &escape($custom).':'.&escape($customshow),
                   4417: 			     $server);
                   4418: 	    $rhash{$server}=$reply;
                   4419: 	}
1.112     harris41 4420:     }
1.118     harris41 4421:     return \%rhash;
1.240     www      4422: }
                   4423: 
                   4424: # ----------------------------------------- Send log queries and wait for reply
                   4425: 
                   4426: sub log_query {
                   4427:     my ($uname,$udom,$query,%filters)=@_;
                   4428:     my $uhome=&homeserver($uname,$udom);
                   4429:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4430:     my $uhost=&hostname($uhome);
1.800     albertel 4431:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4432:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4433:                        $uhome);
1.479     albertel 4434:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4435:     return get_query_reply($queryid);
                   4436: }
                   4437: 
1.818     raeburn  4438: # -------------------------- Update MySQL table for portfolio file
                   4439: 
                   4440: sub update_portfolio_table {
1.821     raeburn  4441:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4442:     my $homeserver = &homeserver($uname,$udom);
                   4443:     my $queryid=
1.821     raeburn  4444:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4445:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4446:     my $reply = &get_query_reply($queryid);
                   4447:     return $reply;
                   4448: }
                   4449: 
1.899     raeburn  4450: # -------------------------- Update MySQL allusers table
                   4451: 
                   4452: sub update_allusers_table {
                   4453:     my ($uname,$udom,$names) = @_;
                   4454:     my $homeserver = &homeserver($uname,$udom);
                   4455:     my $queryid=
                   4456:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4457:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4458:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4459:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4460:                'generation='.&escape($names->{'generation'}).'%%'.
                   4461:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4462:                'id='.&escape($names->{'id'}),$homeserver);
                   4463:     my $reply = &get_query_reply($queryid);
                   4464:     return $reply;
                   4465: }
                   4466: 
1.508     raeburn  4467: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4468: 
                   4469: sub fetch_enrollment_query {
1.511     raeburn  4470:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4471:     my $homeserver;
1.547     raeburn  4472:     my $maxtries = 1;
1.508     raeburn  4473:     if ($context eq 'automated') {
                   4474:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4475:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4476:     } else {
                   4477:         $homeserver = &homeserver($cnum,$dom);
                   4478:     }
1.838     albertel 4479:     my $host=&hostname($homeserver);
1.506     raeburn  4480:     my $cmd = '';
1.800     albertel 4481:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4482:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4483:     }
                   4484:     $cmd =~ s/%%$//;
                   4485:     $cmd = &escape($cmd);
                   4486:     my $query = 'fetchenrollment';
1.620     albertel 4487:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4488:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4489:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4490:         return 'error: '.$queryid;
                   4491:     }
1.506     raeburn  4492:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4493:     my $tries = 1;
                   4494:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4495:         $reply = &get_query_reply($queryid);
                   4496:         $tries ++;
                   4497:     }
1.526     raeburn  4498:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4499:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4500:     } else {
1.901     albertel 4501:         my @responses = split(/:/,$reply);
1.515     raeburn  4502:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4503:             foreach my $line (@responses) {
                   4504:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4505:                 $$replyref{$key} = $value;
                   4506:             }
                   4507:         } else {
1.506     raeburn  4508:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4509:             foreach my $line (@responses) {
                   4510:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4511:                 $$replyref{$key} = $value;
                   4512:                 if ($value > 0) {
1.800     albertel 4513:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4514:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4515:                         my $destname = $pathname.'/'.$filename;
                   4516:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4517:                         if ($xml_classlist =~ /^error/) {
                   4518:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4519:                         } else {
1.506     raeburn  4520:                             if ( open(FILE,">$destname") ) {
                   4521:                                 print FILE &unescape($xml_classlist);
                   4522:                                 close(FILE);
1.526     raeburn  4523:                             } else {
                   4524:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4525:                             }
                   4526:                         }
                   4527:                     }
                   4528:                 }
                   4529:             }
                   4530:         }
                   4531:         return 'ok';
                   4532:     }
                   4533:     return 'error';
                   4534: }
                   4535: 
1.242     www      4536: sub get_query_reply {
                   4537:     my $queryid=shift;
1.240     www      4538:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4539:     my $reply='';
                   4540:     for (1..100) {
                   4541: 	sleep 2;
                   4542:         if (-e $replyfile.'.end') {
1.448     albertel 4543: 	    if (open(my $fh,$replyfile)) {
1.240     www      4544:                $reply.=<$fh>;
1.448     albertel 4545:                close($fh);
1.240     www      4546: 	   } else { return 'error: reply_file_error'; }
1.242     www      4547:            return &unescape($reply);
                   4548: 	}
1.240     www      4549:     }
1.242     www      4550:     return 'timeout:'.$queryid;
1.240     www      4551: }
                   4552: 
                   4553: sub courselog_query {
1.241     www      4554: #
                   4555: # possible filters:
                   4556: # url: url or symb
                   4557: # username
                   4558: # domain
                   4559: # action: view, submit, grade
                   4560: # start: timestamp
                   4561: # end: timestamp
                   4562: #
1.240     www      4563:     my (%filters)=@_;
1.620     albertel 4564:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4565:     if ($filters{'url'}) {
                   4566: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4567:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4568:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4569:     }
1.620     albertel 4570:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4571:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4572:     return &log_query($cname,$cdom,'courselog',%filters);
                   4573: }
                   4574: 
                   4575: sub userlog_query {
1.858     raeburn  4576: #
                   4577: # possible filters:
                   4578: # action: log check role
                   4579: # start: timestamp
                   4580: # end: timestamp
                   4581: #
1.240     www      4582:     my ($uname,$udom,%filters)=@_;
                   4583:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4584: }
                   4585: 
1.506     raeburn  4586: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4587: 
                   4588: sub auto_run {
1.508     raeburn  4589:     my ($cnum,$cdom) = @_;
1.876     raeburn  4590:     my $response = 0;
                   4591:     my $settings;
                   4592:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4593:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4594:         $settings = $domconfig{'autoenroll'};
                   4595:         if ($settings->{'run'} eq '1') {
                   4596:             $response = 1;
                   4597:         }
                   4598:     } else {
                   4599:         my $homeserver = &homeserver($cnum,$cdom);
                   4600:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4601:     }
1.506     raeburn  4602:     return $response;
                   4603: }
1.776     albertel 4604: 
1.506     raeburn  4605: sub auto_get_sections {
1.508     raeburn  4606:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4607:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4608:     my @secs = ();
1.511     raeburn  4609:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4610:     unless ($response eq 'refused') {
1.901     albertel 4611:         @secs = split(/:/,$response);
1.506     raeburn  4612:     }
                   4613:     return @secs;
                   4614: }
1.776     albertel 4615: 
1.506     raeburn  4616: sub auto_new_course {
1.508     raeburn  4617:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4618:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4619:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4620:     return $response;
                   4621: }
1.776     albertel 4622: 
1.506     raeburn  4623: sub auto_validate_courseID {
1.508     raeburn  4624:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4625:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4626:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4627:     return $response;
                   4628: }
1.776     albertel 4629: 
1.506     raeburn  4630: sub auto_create_password {
1.873     raeburn  4631:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4632:     my ($homeserver,$response);
1.506     raeburn  4633:     my $create_passwd = 0;
                   4634:     my $authchk = '';
1.873     raeburn  4635:     if ($udom =~ /^$match_domain$/) {
                   4636:         $homeserver = &domain($udom,'primary');
                   4637:     }
                   4638:     if ($homeserver eq '') {
                   4639:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4640:             $homeserver = &homeserver($cnum,$cdom);
                   4641:         }
                   4642:     }
                   4643:     if ($homeserver eq '') {
                   4644:         $authchk = 'nodomain';
1.506     raeburn  4645:     } else {
1.873     raeburn  4646:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4647:         if ($response eq 'refused') {
                   4648:             $authchk = 'refused';
                   4649:         } else {
1.901     albertel 4650:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4651:         }
1.506     raeburn  4652:     }
                   4653:     return ($authparam,$create_passwd,$authchk);
                   4654: }
                   4655: 
1.706     raeburn  4656: sub auto_photo_permission {
                   4657:     my ($cnum,$cdom,$students) = @_;
                   4658:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4659:     my ($outcome,$perm_reqd,$conditions) = 
                   4660: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4661:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4662: 	return (undef,undef);
                   4663:     }
1.706     raeburn  4664:     return ($outcome,$perm_reqd,$conditions);
                   4665: }
                   4666: 
                   4667: sub auto_checkphotos {
                   4668:     my ($uname,$udom,$pid) = @_;
                   4669:     my $homeserver = &homeserver($uname,$udom);
                   4670:     my ($result,$resulttype);
                   4671:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4672: 				   &escape($uname).':'.&escape($pid),
                   4673: 				   $homeserver));
1.709     albertel 4674:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4675: 	return (undef,undef);
                   4676:     }
1.706     raeburn  4677:     if ($outcome) {
                   4678:         ($result,$resulttype) = split(/:/,$outcome);
                   4679:     } 
                   4680:     return ($result,$resulttype);
                   4681: }
                   4682: 
                   4683: sub auto_photochoice {
                   4684:     my ($cnum,$cdom) = @_;
                   4685:     my $homeserver = &homeserver($cnum,$cdom);
                   4686:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4687: 						       &escape($cdom),
                   4688: 						       $homeserver)));
1.709     albertel 4689:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4690: 	return (undef,undef);
                   4691:     }
1.706     raeburn  4692:     return ($update,$comment);
                   4693: }
                   4694: 
                   4695: sub auto_photoupdate {
                   4696:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4697:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4698:     my $host=&hostname($homeserver);
1.706     raeburn  4699:     my $cmd = '';
                   4700:     my $maxtries = 1;
1.800     albertel 4701:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4702:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4703:     }
                   4704:     $cmd =~ s/%%$//;
                   4705:     $cmd = &escape($cmd);
                   4706:     my $query = 'institutionalphotos';
                   4707:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4708:     unless ($queryid=~/^\Q$host\E\_/) {
                   4709:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4710:         return 'error: '.$queryid;
                   4711:     }
                   4712:     my $reply = &get_query_reply($queryid);
                   4713:     my $tries = 1;
                   4714:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4715:         $reply = &get_query_reply($queryid);
                   4716:         $tries ++;
                   4717:     }
                   4718:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4719:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4720:     } else {
                   4721:         my @responses = split(/:/,$reply);
                   4722:         my $outcome = shift(@responses); 
                   4723:         foreach my $item (@responses) {
                   4724:             my ($key,$value) = split(/=/,$item);
                   4725:             $$photo{$key} = $value;
                   4726:         }
                   4727:         return $outcome;
                   4728:     }
                   4729:     return 'error';
                   4730: }
                   4731: 
1.521     raeburn  4732: sub auto_instcode_format {
1.793     albertel 4733:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4734: 	$cat_order) = @_;
1.521     raeburn  4735:     my $courses = '';
1.772     raeburn  4736:     my @homeservers;
1.521     raeburn  4737:     if ($caller eq 'global') {
1.841     albertel 4738: 	my %servers = &get_servers($codedom,'library');
                   4739: 	foreach my $tryserver (keys(%servers)) {
                   4740: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4741: 		push(@homeservers,$tryserver);
                   4742: 	    }
1.584     raeburn  4743:         }
1.521     raeburn  4744:     } else {
1.772     raeburn  4745:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4746:     }
1.793     albertel 4747:     foreach my $code (keys(%{$instcodes})) {
                   4748:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4749:     }
                   4750:     chop($courses);
1.772     raeburn  4751:     my $ok_response = 0;
                   4752:     my $response;
                   4753:     while (@homeservers > 0 && $ok_response == 0) {
                   4754:         my $server = shift(@homeservers); 
                   4755:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4756:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4757:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4758: 		split(/:/,$response);
1.772     raeburn  4759:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4760:             push(@{$codetitles},&str2array($codetitles_str));
                   4761:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4762:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4763:             $ok_response = 1;
                   4764:         }
                   4765:     }
                   4766:     if ($ok_response) {
1.521     raeburn  4767:         return 'ok';
1.772     raeburn  4768:     } else {
                   4769:         return $response;
1.521     raeburn  4770:     }
                   4771: }
                   4772: 
1.792     raeburn  4773: sub auto_instcode_defaults {
                   4774:     my ($domain,$returnhash,$code_order) = @_;
                   4775:     my @homeservers;
1.841     albertel 4776: 
                   4777:     my %servers = &get_servers($domain,'library');
                   4778:     foreach my $tryserver (keys(%servers)) {
                   4779: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4780: 	    push(@homeservers,$tryserver);
                   4781: 	}
1.792     raeburn  4782:     }
1.841     albertel 4783: 
1.792     raeburn  4784:     my $response;
1.841     albertel 4785:     foreach my $server (@homeservers) {
1.792     raeburn  4786:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4787:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4788: 	
                   4789: 	foreach my $pair (split(/\&/,$response)) {
                   4790: 	    my ($name,$value)=split(/\=/,$pair);
                   4791: 	    if ($name eq 'code_order') {
                   4792: 		@{$code_order} = split(/\&/,&unescape($value));
                   4793: 	    } else {
                   4794: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4795: 	    }
                   4796: 	}
                   4797: 	return 'ok';
1.792     raeburn  4798:     }
1.841     albertel 4799: 
                   4800:     return $response;
1.792     raeburn  4801: } 
                   4802: 
1.777     albertel 4803: sub auto_validate_class_sec {
1.773     raeburn  4804:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4805:     my $homeserver = &homeserver($cnum,$cdom);
                   4806:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4807:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4808:     return $response;
                   4809: }
                   4810: 
1.679     raeburn  4811: # ------------------------------------------------------- Course Group routines
                   4812: 
                   4813: sub get_coursegroups {
1.809     raeburn  4814:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4815:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4816: }
                   4817: 
1.679     raeburn  4818: sub modify_coursegroup {
                   4819:     my ($cdom,$cnum,$groupsettings) = @_;
                   4820:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4821: }
                   4822: 
1.809     raeburn  4823: sub toggle_coursegroup_status {
                   4824:     my ($cdom,$cnum,$group,$action) = @_;
                   4825:     my ($from_namespace,$to_namespace);
                   4826:     if ($action eq 'delete') {
                   4827:         $from_namespace = 'coursegroups';
                   4828:         $to_namespace = 'deleted_groups';
                   4829:     } else {
                   4830:         $from_namespace = 'deleted_groups';
                   4831:         $to_namespace = 'coursegroups';
                   4832:     }
                   4833:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4834:     if (my $tmp = &error(%curr_group)) {
                   4835:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4836:         return ('read error',$tmp);
                   4837:     } else {
                   4838:         my %savedsettings = %curr_group; 
1.809     raeburn  4839:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4840:         my $deloutcome;
                   4841:         if ($result eq 'ok') {
1.809     raeburn  4842:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4843:         } else {
                   4844:             return ('write error',$result);
                   4845:         }
                   4846:         if ($deloutcome eq 'ok') {
                   4847:             return 'ok';
                   4848:         } else {
                   4849:             return ('delete error',$deloutcome);
                   4850:         }
                   4851:     }
                   4852: }
                   4853: 
1.679     raeburn  4854: sub modify_group_roles {
                   4855:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4856:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4857:     my $role = 'gr/'.&escape($userprivs);
                   4858:     my ($uname,$udom) = split(/:/,$user);
                   4859:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4860:     if ($result eq 'ok') {
                   4861:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4862:     }
1.679     raeburn  4863:     return $result;
                   4864: }
                   4865: 
                   4866: sub modify_coursegroup_membership {
                   4867:     my ($cdom,$cnum,$membership) = @_;
                   4868:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4869:     return $result;
                   4870: }
                   4871: 
1.682     raeburn  4872: sub get_active_groups {
                   4873:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4874:     my $now = time;
                   4875:     my %groups = ();
                   4876:     foreach my $key (keys(%env)) {
1.811     albertel 4877:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4878:             my ($start,$end) = split(/\./,$env{$key});
                   4879:             if (($end!=0) && ($end<$now)) { next; }
                   4880:             if (($start!=0) && ($start>$now)) { next; }
                   4881:             if ($1 eq $cdom && $2 eq $cnum) {
                   4882:                 $groups{$3} = $env{$key} ;
                   4883:             }
                   4884:         }
                   4885:     }
                   4886:     return %groups;
                   4887: }
                   4888: 
1.683     raeburn  4889: sub get_group_membership {
                   4890:     my ($cdom,$cnum,$group) = @_;
                   4891:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4892: }
                   4893: 
                   4894: sub get_users_groups {
                   4895:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4896:     my @usersgroups;
1.683     raeburn  4897:     my $cachetime=1800;
                   4898: 
                   4899:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4900:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4901:     if (defined($cached)) {
1.734     albertel 4902:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4903:     } else {  
                   4904:         $grouplist = '';
1.816     raeburn  4905:         my $courseurl = &courseid_to_courseurl($courseid);
                   4906:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4907:         my $access_end = $env{'course.'.$courseid.
                   4908:                               '.default_enrollment_end_date'};
                   4909:         my $now = time;
                   4910:         foreach my $key (keys(%roleshash)) {
                   4911:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4912:                 my $group = $1;
                   4913:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4914:                     my $start = $2;
                   4915:                     my $end = $1;
                   4916:                     if ($start == -1) { next; } # deleted from group
                   4917:                     if (($start!=0) && ($start>$now)) { next; }
                   4918:                     if (($end!=0) && ($end<$now)) {
                   4919:                         if ($access_end && $access_end < $now) {
                   4920:                             if ($access_end - $end < 86400) {
                   4921:                                 push(@usersgroups,$group);
1.733     raeburn  4922:                             }
                   4923:                         }
1.817     raeburn  4924:                         next;
1.733     raeburn  4925:                     }
1.817     raeburn  4926:                     push(@usersgroups,$group);
1.683     raeburn  4927:                 }
                   4928:             }
                   4929:         }
1.817     raeburn  4930:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4931:         $grouplist = join(':',@usersgroups);
                   4932:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4933:     }
1.733     raeburn  4934:     return @usersgroups;
1.683     raeburn  4935: }
                   4936: 
                   4937: sub devalidate_getgroups_cache {
                   4938:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4939:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4940: 
1.683     raeburn  4941:     my $hashid="$udom:$uname:$courseid";
                   4942:     &devalidate_cache_new('getgroups',$hashid);
                   4943: }
                   4944: 
1.12      www      4945: # ------------------------------------------------------------------ Plain Text
                   4946: 
                   4947: sub plaintext {
1.742     raeburn  4948:     my ($short,$type,$cid) = @_;
1.758     albertel 4949:     if ($short =~ /^cr/) {
                   4950: 	return (split('/',$short))[-1];
                   4951:     }
1.742     raeburn  4952:     if (!defined($cid)) {
                   4953:         $cid = $env{'request.course.id'};
                   4954:     }
                   4955:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4956:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4957:                                           '.plaintext'});
                   4958:     }
                   4959:     my %rolenames = (
                   4960:                       Course => 'std',
                   4961:                       Group => 'alt1',
                   4962:                     );
                   4963:     if (defined($type) && 
                   4964:          defined($rolenames{$type}) && 
                   4965:          defined($prp{$short}{$rolenames{$type}})) {
                   4966:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4967:     } else {
                   4968:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4969:     }
1.12      www      4970: }
                   4971: 
                   4972: # ----------------------------------------------------------------- Assign Role
                   4973: 
                   4974: sub assignrole {
1.357     www      4975:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4976:     my $mrole;
                   4977:     if ($role =~ /^cr\//) {
1.393     www      4978:         my $cwosec=$url;
1.811     albertel 4979:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4980: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4981:            &logthis('Refused custom assignrole: '.
                   4982:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4983: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4984:            return 'refused'; 
                   4985:         }
1.21      www      4986:         $mrole='cr';
1.678     raeburn  4987:     } elsif ($role =~ /^gr\//) {
                   4988:         my $cwogrp=$url;
1.811     albertel 4989:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4990:         unless (&allowed('mdg',$cwogrp)) {
                   4991:             &logthis('Refused group assignrole: '.
                   4992:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4993:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4994:             return 'refused';
                   4995:         }
                   4996:         $mrole='gr';
1.21      www      4997:     } else {
1.82      www      4998:         my $cwosec=$url;
1.811     albertel 4999:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5000:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5001:            &logthis('Refused assignrole: '.
                   5002:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5003: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5004:            return 'refused'; 
                   5005:         }
1.21      www      5006:         $mrole=$role;
                   5007:     }
1.620     albertel 5008:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5009:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5010:     if ($end) { $command.='_'.$end; }
1.21      www      5011:     if ($start) {
                   5012: 	if ($end) { 
1.81      www      5013:            $command.='_'.$start; 
1.21      www      5014:         } else {
1.81      www      5015:            $command.='_0_'.$start;
1.21      www      5016:         }
                   5017:     }
1.739     raeburn  5018:     my $origstart = $start;
                   5019:     my $origend = $end;
1.357     www      5020: # actually delete
                   5021:     if ($deleteflag) {
1.373     www      5022: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5023: # modify command to delete the role
1.620     albertel 5024:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5025:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5026: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5027: # set start and finish to negative values for userrolelog
                   5028:            $start=-1;
                   5029:            $end=-1;
                   5030:         }
                   5031:     }
                   5032: # send command
1.349     www      5033:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5034: # log new user role if status is ok
1.349     www      5035:     if ($answer eq 'ok') {
1.663     raeburn  5036: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5037: # for course roles, perform group memberships changes triggered by role change.
                   5038:         unless ($role =~ /^gr/) {
                   5039:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5040:                                              $origstart);
                   5041:         }
1.349     www      5042:     }
                   5043:     return $answer;
1.169     harris41 5044: }
                   5045: 
                   5046: # -------------------------------------------------- Modify user authentication
1.197     www      5047: # Overrides without validation
                   5048: 
1.169     harris41 5049: sub modifyuserauth {
                   5050:     my ($udom,$uname,$umode,$upass)=@_;
                   5051:     my $uhome=&homeserver($uname,$udom);
1.197     www      5052:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5053:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5054:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5055:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5056:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5057: 		     &escape($upass),$uhome);
1.620     albertel 5058:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5059:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5060:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5061:     &log($udom,,$uname,$uhome,
1.620     albertel 5062:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5063:                                      $env{'user.name'}.', '.$umode.
1.197     www      5064:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5065:     unless ($reply eq 'ok') {
1.197     www      5066:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5067: 	return 'error: '.$reply;
                   5068:     }   
1.170     harris41 5069:     return 'ok';
1.80      www      5070: }
                   5071: 
1.81      www      5072: # --------------------------------------------------------------- Modify a user
1.80      www      5073: 
1.81      www      5074: sub modifyuser {
1.206     matthew  5075:     my ($udom,    $uname, $uid,
                   5076:         $umode,   $upass, $first,
                   5077:         $middle,  $last,  $gene,
1.387     www      5078:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5079:     $udom= &LONCAPA::clean_domain($udom);
                   5080:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5081:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5082:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5083: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5084:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5085:                                      ' desiredhome not specified'). 
1.620     albertel 5086:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5087:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5088:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5089: # ----------------------------------------------------------------- Create User
1.406     albertel 5090:     if (($uhome eq 'no_host') && 
                   5091: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5092:         my $unhome='';
1.844     albertel 5093:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5094:             $unhome = $desiredhome;
1.620     albertel 5095: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5096: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5097:         } else { # load balancing routine for determining $unhome
1.81      www      5098:             my $loadm=10000000;
1.841     albertel 5099: 	    my %servers = &get_servers($udom,'library');
                   5100: 	    foreach my $tryserver (keys(%servers)) {
                   5101: 		my $answer=reply('load',$tryserver);
                   5102: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5103: 		    $loadm=$answer;
                   5104: 		    $unhome=$tryserver;
                   5105: 		}
1.80      www      5106: 	    }
                   5107:         }
                   5108:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5109: 	    return 'error: unable to find a home server for '.$uname.
                   5110:                    ' in domain '.$udom;
1.80      www      5111:         }
                   5112:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5113:                          &escape($upass),$unhome);
                   5114: 	unless ($reply eq 'ok') {
                   5115:             return 'error: '.$reply;
                   5116:         }   
1.230     stredwic 5117:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5118:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5119: 	    return 'error: unable verify users home machine.';
1.80      www      5120:         }
1.209     matthew  5121:     }   # End of creation of new user
1.80      www      5122: # ---------------------------------------------------------------------- Add ID
                   5123:     if ($uid) {
                   5124:        $uid=~tr/A-Z/a-z/;
                   5125:        my %uidhash=&idrget($udom,$uname);
1.196     www      5126:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5127:          && (!$forceid)) {
1.80      www      5128: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5129: 	      return 'error: user id "'.$uid.'" does not match '.
                   5130:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5131:           }
                   5132:        } else {
                   5133: 	  &idput($udom,($uname => $uid));
                   5134:        }
                   5135:     }
                   5136: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5137:     my @tmp=&get('environment',
1.899     raeburn  5138: 		   ['firstname','middlename','lastname','generation','id',
                   5139:                     'permanentemail'],
1.134     albertel 5140: 		   $udom,$uname);
1.313     matthew  5141:     my %names;
                   5142:     if ($tmp[0] =~ m/^error:.*/) { 
                   5143:         %names=(); 
                   5144:     } else {
                   5145:         %names = @tmp;
                   5146:     }
1.388     www      5147: #
                   5148: # Make sure to not trash student environment if instructor does not bother
                   5149: # to supply name and email information
                   5150: #
                   5151:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5152:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5153:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5154:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5155:     if ($email) {
                   5156:        $email=~s/[^\w\@\.\-\,]//gs;
                   5157:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5158: 			   $names{'critnotification'} = $email;
                   5159: 			   $names{'permanentemail'} = $email; }
                   5160:     }
1.899     raeburn  5161:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5162:     my $reply = &put('environment', \%names, $udom,$uname);
                   5163:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5164:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5165:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5166:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5167:              $umode.', '.$first.', '.$middle.', '.
                   5168: 	     $last.', '.$gene.' by '.
1.620     albertel 5169:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5170:     return 'ok';
1.80      www      5171: }
                   5172: 
1.81      www      5173: # -------------------------------------------------------------- Modify student
1.80      www      5174: 
1.81      www      5175: sub modifystudent {
                   5176:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5177:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5178:     if (!$cid) {
1.620     albertel 5179: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5180: 	    return 'not_in_class';
                   5181: 	}
1.80      www      5182:     }
                   5183: # --------------------------------------------------------------- Make the user
1.81      www      5184:     my $reply=&modifyuser
1.209     matthew  5185: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5186:          $desiredhome,$email);
1.80      www      5187:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5188:     # This will cause &modify_student_enrollment to get the uid from the
                   5189:     # students environment
                   5190:     $uid = undef if (!$forceid);
1.455     albertel 5191:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5192: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5193:     return $reply;
                   5194: }
                   5195: 
                   5196: sub modify_student_enrollment {
1.515     raeburn  5197:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5198:     my ($cdom,$cnum,$chome);
                   5199:     if (!$cid) {
1.620     albertel 5200: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5201: 	    return 'not_in_class';
                   5202: 	}
1.620     albertel 5203: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5204: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5205:     } else {
                   5206: 	($cdom,$cnum)=split(/_/,$cid);
                   5207:     }
1.620     albertel 5208:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5209:     if (!$chome) {
1.457     raeburn  5210: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5211:     }
1.455     albertel 5212:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5213:     # Make sure the user exists
1.81      www      5214:     my $uhome=&homeserver($uname,$udom);
                   5215:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5216: 	return 'error: no such user';
                   5217:     }
1.297     matthew  5218:     # Get student data if we were not given enough information
                   5219:     if (!defined($first)  || $first  eq '' || 
                   5220:         !defined($last)   || $last   eq '' || 
                   5221:         !defined($uid)    || $uid    eq '' || 
                   5222:         !defined($middle) || $middle eq '' || 
                   5223:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5224:         # They did not supply us with enough data to enroll the student, so
                   5225:         # we need to pick up more information.
1.297     matthew  5226:         my %tmp = &get('environment',
1.294     matthew  5227:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5228:                        ,$udom,$uname);
                   5229: 
1.800     albertel 5230:         #foreach my $key (keys(%tmp)) {
                   5231:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5232:         #}
1.294     matthew  5233:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5234:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5235:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5236:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5237:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5238:     }
1.556     albertel 5239:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5240:     my $reply=cput('classlist',
                   5241: 		   {"$uname:$udom" => 
1.515     raeburn  5242: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5243: 		   $cdom,$cnum);
1.81      www      5244:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5245: 	return 'error: '.$reply;
1.652     albertel 5246:     } else {
                   5247: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5248:     }
1.297     matthew  5249:     # Add student role to user
1.83      www      5250:     my $uurl='/'.$cid;
1.81      www      5251:     $uurl=~s/\_/\//g;
                   5252:     if ($usec) {
                   5253: 	$uurl.='/'.$usec;
                   5254:     }
                   5255:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5256: }
                   5257: 
1.556     albertel 5258: sub format_name {
                   5259:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5260:     my $name;
                   5261:     if ($first ne 'lastname') {
                   5262: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5263:     } else {
                   5264: 	if ($lastname=~/\S/) {
                   5265: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5266: 	    $name=~s/\s+,/,/;
                   5267: 	} else {
                   5268: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5269: 	}
                   5270:     }
                   5271:     $name=~s/^\s+//;
                   5272:     $name=~s/\s+$//;
                   5273:     $name=~s/\s+/ /g;
                   5274:     return $name;
                   5275: }
                   5276: 
1.84      www      5277: # ------------------------------------------------- Write to course preferences
                   5278: 
                   5279: sub writecoursepref {
                   5280:     my ($courseid,%prefs)=@_;
                   5281:     $courseid=~s/^\///;
                   5282:     $courseid=~s/\_/\//g;
                   5283:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5284:     my $chome=homeserver($cnum,$cdomain);
                   5285:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5286: 	return 'error: no such course';
                   5287:     }
                   5288:     my $cstring='';
1.800     albertel 5289:     foreach my $pref (keys(%prefs)) {
                   5290: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5291:     }
1.84      www      5292:     $cstring=~s/\&$//;
                   5293:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5294: }
                   5295: 
                   5296: # ---------------------------------------------------------- Make/modify course
                   5297: 
                   5298: sub createcourse {
1.741     raeburn  5299:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5300:         $course_owner,$crstype)=@_;
1.84      www      5301:     $url=&declutter($url);
                   5302:     my $cid='';
1.264     matthew  5303:     unless (&allowed('ccc',$udom)) {
1.84      www      5304:         return 'refused';
                   5305:     }
                   5306: # ------------------------------------------------------------------- Create ID
1.674     www      5307:    my $uname=int(1+rand(9)).
                   5308:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5309:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5310:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5311: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5312:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5313:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5314:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5315:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5316:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5317:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5318:            return 'error: unable to generate unique course-ID';
                   5319:        } 
                   5320:    }
1.264     matthew  5321: # ------------------------------------------------ Check supplied server name
1.620     albertel 5322:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5323:     if (! &is_library($course_server)) {
1.264     matthew  5324:         return 'error:bad server name '.$course_server;
                   5325:     }
1.84      www      5326: # ------------------------------------------------------------- Make the course
                   5327:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5328:                       $course_server);
1.84      www      5329:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5330:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5331:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5332: 	return 'error: no such course';
                   5333:     }
1.271     www      5334: # ----------------------------------------------------------------- Course made
1.516     raeburn  5335: # log existence
                   5336:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5337:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5338:                   &escape($crstype),$uhome);
1.358     www      5339:     &flushcourselogs();
                   5340: # set toplevel url
1.271     www      5341:     my $topurl=$url;
                   5342:     unless ($nonstandard) {
                   5343: # ------------------------------------------ For standard courses, make top url
                   5344:         my $mapurl=&clutter($url);
1.278     www      5345:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5346:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5347: <map>
                   5348: <resource id="1" type="start"></resource>
                   5349: <resource id="2" src="$mapurl"></resource>
                   5350: <resource id="3" type="finish"></resource>
                   5351: <link index="1" from="1" to="2"></link>
                   5352: <link index="2" from="2" to="3"></link>
                   5353: </map>
                   5354: ENDINITMAP
                   5355:         $topurl=&declutter(
1.638     albertel 5356:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5357:                           );
                   5358:     }
                   5359: # ----------------------------------------------------------- Write preferences
1.84      www      5360:     &writecoursepref($udom.'_'.$uname,
                   5361:                      ('description' => $description,
1.271     www      5362:                       'url'         => $topurl));
1.84      www      5363:     return '/'.$udom.'/'.$uname;
                   5364: }
                   5365: 
1.813     albertel 5366: sub is_course {
                   5367:     my ($cdom,$cnum) = @_;
                   5368:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5369: 				undef,'.');
                   5370:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5371:         return 1;
                   5372:     }
                   5373:     return 0;
                   5374: }
                   5375: 
1.21      www      5376: # ---------------------------------------------------------- Assign Custom Role
                   5377: 
                   5378: sub assigncustomrole {
1.357     www      5379:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5380:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5381:                        $end,$start,$deleteflag);
1.21      www      5382: }
                   5383: 
                   5384: # ----------------------------------------------------------------- Revoke Role
                   5385: 
                   5386: sub revokerole {
1.357     www      5387:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5388:     my $now=time;
1.357     www      5389:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5390: }
                   5391: 
                   5392: # ---------------------------------------------------------- Revoke Custom Role
                   5393: 
                   5394: sub revokecustomrole {
1.357     www      5395:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5396:     my $now=time;
1.357     www      5397:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5398:            $deleteflag);
1.17      www      5399: }
                   5400: 
1.533     banghart 5401: # ------------------------------------------------------------ Disk usage
1.535     albertel 5402: sub diskusage {
1.533     banghart 5403:     my ($udom,$uname,$directoryRoot)=@_;
                   5404:     $directoryRoot =~ s/\/$//;
1.535     albertel 5405:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5406:     return $listing;
1.512     banghart 5407: }
                   5408: 
1.566     banghart 5409: sub is_locked {
                   5410:     my ($file_name, $domain, $user) = @_;
                   5411:     my @check;
                   5412:     my $is_locked;
                   5413:     push @check, $file_name;
1.613     albertel 5414:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5415: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5416:     my ($tmp)=keys(%locked);
                   5417:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5418:     
1.566     banghart 5419:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5420:         $is_locked = 'false';
                   5421:         foreach my $entry (@{$locked{$file_name}}) {
                   5422:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5423:                $is_locked = 'true';
                   5424:                last;
1.745     raeburn  5425:            }
                   5426:        }
1.566     banghart 5427:     } else {
                   5428:         $is_locked = 'false';
                   5429:     }
                   5430: }
                   5431: 
1.759     albertel 5432: sub declutter_portfile {
                   5433:     my ($file) = @_;
1.833     albertel 5434:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5435:     return $file;
                   5436: }
                   5437: 
1.559     banghart 5438: # ------------------------------------------------------------- Mark as Read Only
                   5439: 
                   5440: sub mark_as_readonly {
                   5441:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5442:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5443:     my ($tmp)=keys(%current_permissions);
                   5444:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5445:     foreach my $file (@{$files}) {
1.759     albertel 5446: 	$file = &declutter_portfile($file);
1.561     banghart 5447:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5448:     }
1.613     albertel 5449:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5450:     return;
                   5451: }
                   5452: 
1.572     banghart 5453: # ------------------------------------------------------------Save Selected Files
                   5454: 
                   5455: sub save_selected_files {
                   5456:     my ($user, $path, @files) = @_;
                   5457:     my $filename = $user."savedfiles";
1.573     banghart 5458:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5459:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5460:     foreach my $file (@files) {
1.620     albertel 5461:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5462:     }
                   5463:     foreach my $file (@other_files) {
1.574     banghart 5464:         print (OUT $file."\n");
1.572     banghart 5465:     }
1.574     banghart 5466:     close (OUT);
1.572     banghart 5467:     return 'ok';
                   5468: }
                   5469: 
1.574     banghart 5470: sub clear_selected_files {
                   5471:     my ($user) = @_;
                   5472:     my $filename = $user."savedfiles";
                   5473:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5474:     print (OUT undef);
                   5475:     close (OUT);
                   5476:     return ("ok");    
                   5477: }
                   5478: 
1.572     banghart 5479: sub files_in_path {
                   5480:     my ($user, $path) = @_;
                   5481:     my $filename = $user."savedfiles";
                   5482:     my %return_files;
1.574     banghart 5483:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5484:     while (my $line_in = <IN>) {
1.574     banghart 5485:         chomp ($line_in);
                   5486:         my @paths_and_file = split (m!/!, $line_in);
                   5487:         my $file_part = pop (@paths_and_file);
                   5488:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5489:         $path_part.='/';
                   5490:         my $path_and_file = $path_part.$file_part;
                   5491:         if ($path_part eq $path) {
                   5492:             $return_files{$file_part}= 'selected';
                   5493:         }
                   5494:     }
1.574     banghart 5495:     close (IN);
                   5496:     return (\%return_files);
1.572     banghart 5497: }
                   5498: 
                   5499: # called in portfolio select mode, to show files selected NOT in current directory
                   5500: sub files_not_in_path {
                   5501:     my ($user, $path) = @_;
                   5502:     my $filename = $user."savedfiles";
                   5503:     my @return_files;
                   5504:     my $path_part;
1.800     albertel 5505:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5506:     while (my $line = <IN>) {
1.572     banghart 5507:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5508:         my @paths_and_file = split(m|/|, $line);
                   5509:         my $file_part = pop(@paths_and_file);
                   5510:         chomp($file_part);
                   5511:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5512:         $path_part .= '/';
                   5513:         my $path_and_file = $path_part.$file_part;
                   5514:         if ($path_part ne $path) {
1.800     albertel 5515:             push(@return_files, ($path_and_file));
1.572     banghart 5516:         }
                   5517:     }
1.800     albertel 5518:     close(OUT);
1.574     banghart 5519:     return (@return_files);
1.572     banghart 5520: }
                   5521: 
1.745     raeburn  5522: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5523: 
1.745     raeburn  5524: sub get_portfile_permissions {
                   5525:     my ($domain,$user) = @_;
1.613     albertel 5526:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5527:     my ($tmp)=keys(%current_permissions);
                   5528:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5529:     return \%current_permissions;
                   5530: }
                   5531: 
                   5532: #---------------------------------------------Get portfolio file access controls
                   5533: 
1.749     raeburn  5534: sub get_access_controls {
1.745     raeburn  5535:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5536:     my %access;
                   5537:     my $real_file = $file;
                   5538:     $file =~ s/\.meta$//;
1.745     raeburn  5539:     if (defined($file)) {
1.749     raeburn  5540:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5541:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5542:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5543:             }
                   5544:         }
1.745     raeburn  5545:     } else {
1.749     raeburn  5546:         foreach my $key (keys(%{$current_permissions})) {
                   5547:             if ($key =~ /\0accesscontrol$/) {
                   5548:                 if (defined($group)) {
                   5549:                     if ($key !~ m-^\Q$group\E/-) {
                   5550:                         next;
                   5551:                     }
                   5552:                 }
                   5553:                 my ($fullpath) = split(/\0/,$key);
                   5554:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5555:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5556:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5557:                     }
                   5558:                 }
                   5559:             }
                   5560:         }
                   5561:     }
                   5562:     return %access;
                   5563: }
                   5564: 
                   5565: sub modify_access_controls {
                   5566:     my ($file_name,$changes,$domain,$user)=@_;
                   5567:     my ($outcome,$deloutcome);
                   5568:     my %store_permissions;
                   5569:     my %new_values;
                   5570:     my %new_control;
                   5571:     my %translation;
                   5572:     my @deletions = ();
                   5573:     my $now = time;
                   5574:     if (exists($$changes{'activate'})) {
                   5575:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5576:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5577:             my $numnew = scalar(@newitems);
                   5578:             for (my $i=0; $i<$numnew; $i++) {
                   5579:                 my $newkey = $newitems[$i];
                   5580:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5581:                 if ($newkey =~ /^\d+:/) { 
                   5582:                     $newkey =~ s/^(\d+)/$newid/;
                   5583:                     $translation{$1} = $newid;
                   5584:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5585:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5586:                     $translation{$1} = $newid;
                   5587:                 }
1.749     raeburn  5588:                 $new_values{$file_name."\0".$newkey} = 
                   5589:                                           $$changes{'activate'}{$newitems[$i]};
                   5590:                 $new_control{$newkey} = $now;
                   5591:             }
                   5592:         }
                   5593:     }
                   5594:     my %todelete;
                   5595:     my %changed_items;
                   5596:     foreach my $action ('delete','update') {
                   5597:         if (exists($$changes{$action})) {
                   5598:             if (ref($$changes{$action}) eq 'HASH') {
                   5599:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5600:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5601:                     if ($action eq 'delete') { 
                   5602:                         $todelete{$itemnum} = 1;
                   5603:                     } else {
                   5604:                         $changed_items{$itemnum} = $key;
                   5605:                     }
                   5606:                 }
1.745     raeburn  5607:             }
                   5608:         }
1.749     raeburn  5609:     }
                   5610:     # get lock on access controls for file.
                   5611:     my $lockhash = {
                   5612:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5613:                                                        ':'.$env{'user.domain'},
                   5614:                    }; 
                   5615:     my $tries = 0;
                   5616:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5617:    
                   5618:     while (($gotlock ne 'ok') && $tries <3) {
                   5619:         $tries ++;
                   5620:         sleep 1;
                   5621:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5622:     }
                   5623:     if ($gotlock eq 'ok') {
                   5624:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5625:         my ($tmp)=keys(%curr_permissions);
                   5626:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5627:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5628:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5629:             if (ref($curr_controls) eq 'HASH') {
                   5630:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5631:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5632:                     if (defined($todelete{$itemnum})) {
                   5633:                         push(@deletions,$file_name."\0".$control_item);
                   5634:                     } else {
                   5635:                         if (defined($changed_items{$itemnum})) {
                   5636:                             $new_control{$changed_items{$itemnum}} = $now;
                   5637:                             push(@deletions,$file_name."\0".$control_item);
                   5638:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5639:                         } else {
                   5640:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5641:                         }
                   5642:                     }
1.745     raeburn  5643:                 }
                   5644:             }
                   5645:         }
1.749     raeburn  5646:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5647:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5648:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5649:         #  remove lock
                   5650:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5651:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5652:         my ($file,$group);
                   5653:         if (&is_course($domain,$user)) {
                   5654:             ($group,$file) = split(/\//,$file_name,2);
                   5655:         } else {
                   5656:             $file = $file_name;
                   5657:         }
                   5658:         my $sqlresult =
                   5659:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5660:                                     $group);
1.749     raeburn  5661:     } else {
                   5662:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5663:     }
1.749     raeburn  5664:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5665: }
                   5666: 
1.827     raeburn  5667: sub make_public_indefinitely {
                   5668:     my ($requrl) = @_;
                   5669:     my $now = time;
                   5670:     my $action = 'activate';
                   5671:     my $aclnum = 0;
                   5672:     if (&is_portfolio_url($requrl)) {
                   5673:         my (undef,$udom,$unum,$file_name,$group) =
                   5674:             &parse_portfolio_url($requrl);
                   5675:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5676:         my %access_controls = &get_access_controls($current_perms,
                   5677:                                                    $group,$file_name);
                   5678:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5679:             my ($num,$scope,$end,$start) = 
                   5680:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5681:             if ($scope eq 'public') {
                   5682:                 if ($start <= $now && $end == 0) {
                   5683:                     $action = 'none';
                   5684:                 } else {
                   5685:                     $action = 'update';
                   5686:                     $aclnum = $num;
                   5687:                 }
                   5688:                 last;
                   5689:             }
                   5690:         }
                   5691:         if ($action eq 'none') {
                   5692:              return 'ok';
                   5693:         } else {
                   5694:             my %changes;
                   5695:             my $newend = 0;
                   5696:             my $newstart = $now;
                   5697:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5698:             $changes{$action}{$newkey} = {
                   5699:                 type => 'public',
                   5700:                 time => {
                   5701:                     start => $newstart,
                   5702:                     end   => $newend,
                   5703:                 },
                   5704:             };
                   5705:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5706:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5707:             return $outcome;
                   5708:         }
                   5709:     } else {
                   5710:         return 'invalid';
                   5711:     }
                   5712: }
                   5713: 
1.745     raeburn  5714: #------------------------------------------------------Get Marked as Read Only
                   5715: 
                   5716: sub get_marked_as_readonly {
                   5717:     my ($domain,$user,$what,$group) = @_;
                   5718:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5719:     my @readonly_files;
1.629     banghart 5720:     my $cmp1=$what;
                   5721:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5722:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5723:         if (defined($group)) {
                   5724:             if ($file_name !~ m-^\Q$group\E/-) {
                   5725:                 next;
                   5726:             }
                   5727:         }
1.561     banghart 5728:         if (ref($value) eq "ARRAY"){
                   5729:             foreach my $stored_what (@{$value}) {
1.629     banghart 5730:                 my $cmp2=$stored_what;
1.759     albertel 5731:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5732:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5733:                 }
1.629     banghart 5734:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5735:                     push(@readonly_files, $file_name);
1.745     raeburn  5736:                     last;
1.563     banghart 5737:                 } elsif (!defined($what)) {
                   5738:                     push(@readonly_files, $file_name);
1.745     raeburn  5739:                     last;
1.561     banghart 5740:                 }
                   5741:             }
1.745     raeburn  5742:         }
1.561     banghart 5743:     }
                   5744:     return @readonly_files;
                   5745: }
1.577     banghart 5746: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5747: 
1.577     banghart 5748: sub get_marked_as_readonly_hash {
1.745     raeburn  5749:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5750:     my %readonly_files;
1.745     raeburn  5751:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5752:         if (defined($group)) {
                   5753:             if ($file_name !~ m-^\Q$group\E/-) {
                   5754:                 next;
                   5755:             }
                   5756:         }
1.577     banghart 5757:         if (ref($value) eq "ARRAY"){
                   5758:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5759:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5760:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5761:                         if ($lock_descriptor eq 'graded') {
                   5762:                             $readonly_files{$file_name} = 'graded';
                   5763:                         } elsif ($lock_descriptor eq 'handback') {
                   5764:                             $readonly_files{$file_name} = 'handback';
                   5765:                         } else {
                   5766:                             if (!exists($readonly_files{$file_name})) {
                   5767:                                 $readonly_files{$file_name} = 'locked';
                   5768:                             }
                   5769:                         }
1.745     raeburn  5770:                     }
1.750     banghart 5771:                 } 
1.577     banghart 5772:             }
                   5773:         } 
                   5774:     }
                   5775:     return %readonly_files;
                   5776: }
1.559     banghart 5777: # ------------------------------------------------------------ Unmark as Read Only
                   5778: 
                   5779: sub unmark_as_readonly {
1.629     banghart 5780:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5781:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5782:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5783:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5784:     my $symb_crs = $what;
                   5785:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5786:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5787:     my ($tmp)=keys(%current_permissions);
                   5788:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5789:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5790:     foreach my $file (@readonly_files) {
1.759     albertel 5791: 	my $clean_file = &declutter_portfile($file);
                   5792: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5793: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5794:         my @new_locks;
                   5795:         my @del_keys;
                   5796:         if (ref($current_locks) eq "ARRAY"){
                   5797:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5798:                 my $compare=$locker;
1.749     raeburn  5799:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5800:                     $compare=join('',@{$locker});
1.746     raeburn  5801:                     if ($compare ne $symb_crs) {
                   5802:                         push(@new_locks, $locker);
                   5803:                     }
1.563     banghart 5804:                 }
                   5805:             }
1.650     albertel 5806:             if (scalar(@new_locks) > 0) {
1.563     banghart 5807:                 $current_permissions{$file} = \@new_locks;
                   5808:             } else {
                   5809:                 push(@del_keys, $file);
1.613     albertel 5810:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5811:                 delete($current_permissions{$file});
1.563     banghart 5812:             }
                   5813:         }
1.561     banghart 5814:     }
1.613     albertel 5815:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5816:     return;
                   5817: }
1.512     banghart 5818: 
1.17      www      5819: # ------------------------------------------------------------ Directory lister
                   5820: 
                   5821: sub dirlist {
1.253     stredwic 5822:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5823: 
1.18      www      5824:     $uri=~s/^\///;
                   5825:     $uri=~s/\/$//;
1.253     stredwic 5826:     my ($udom, $uname);
                   5827:     (undef,$udom,$uname)=split(/\//,$uri);
                   5828:     if(defined($userdomain)) {
                   5829:         $udom = $userdomain;
                   5830:     }
                   5831:     if(defined($username)) {
                   5832:         $uname = $username;
                   5833:     }
                   5834: 
                   5835:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5836:     if(defined($alternateDirectoryRoot)) {
                   5837:         $dirRoot = $alternateDirectoryRoot;
                   5838:         $dirRoot =~ s/\/$//;
1.751     banghart 5839:     }
1.253     stredwic 5840: 
                   5841:     if($udom) {
                   5842:         if($uname) {
1.800     albertel 5843:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5844: 				 &homeserver($uname,$udom));
1.605     matthew  5845:             my @listing_results;
                   5846:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5847:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5848: 				  &homeserver($uname,$udom));
1.605     matthew  5849:                 @listing_results = split(/:/,$listing);
                   5850:             } else {
                   5851:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5852:             }
                   5853:             return @listing_results;
1.253     stredwic 5854:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5855:             my %allusers;
1.841     albertel 5856: 	    my %servers = &get_servers($udom,'library');
                   5857: 	    foreach my $tryserver (keys(%servers)) {
                   5858: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5859: 				     $udom, $tryserver);
                   5860: 		my @listing_results;
                   5861: 		if ($listing eq 'unknown_cmd') {
                   5862: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5863: 				      $udom, $tryserver);
                   5864: 		    @listing_results = split(/:/,$listing);
                   5865: 		} else {
                   5866: 		    @listing_results =
                   5867: 			map { &unescape($_); } split(/:/,$listing);
                   5868: 		}
                   5869: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5870: 		    $listing_results[0] ne 'empty'       &&
                   5871: 		    $listing_results[0] ne 'con_lost') {
                   5872: 		    foreach my $line (@listing_results) {
                   5873: 			my ($entry) = split(/&/,$line,2);
                   5874: 			$allusers{$entry} = 1;
                   5875: 		    }
                   5876: 		}
1.253     stredwic 5877:             }
                   5878:             my $alluserstr='';
1.800     albertel 5879:             foreach my $user (sort(keys(%allusers))) {
                   5880:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5881:             }
                   5882:             $alluserstr=~s/:$//;
                   5883:             return split(/:/,$alluserstr);
                   5884:         } else {
1.800     albertel 5885:             return ('missing user name');
1.253     stredwic 5886:         }
                   5887:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5888:         my @all_domains = sort(&all_domains());
                   5889:          foreach my $domain (@all_domains) {
                   5890:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5891:          }
                   5892:          return @all_domains;
                   5893:      } else {
1.800     albertel 5894:         return ('missing domain');
1.275     stredwic 5895:     }
                   5896: }
                   5897: 
                   5898: # --------------------------------------------- GetFileTimestamp
                   5899: # This function utilizes dirlist and returns the date stamp for
                   5900: # when it was last modified.  It will also return an error of -1
                   5901: # if an error occurs
                   5902: 
1.410     matthew  5903: ##
                   5904: ## FIXME: This subroutine assumes its caller knows something about the
                   5905: ## directory structure of the home server for the student ($root).
                   5906: ## Not a good assumption to make.  Since this is for looking up files
                   5907: ## in user directories, the full path should be constructed by lond, not
                   5908: ## whatever machine we request data from.
                   5909: ##
1.275     stredwic 5910: sub GetFileTimestamp {
                   5911:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5912:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5913:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5914:     my $subdir=$studentName.'__';
                   5915:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5916:     my $proname="$studentDomain/$subdir/$studentName";
                   5917:     $proname .= '/'.$filename;
1.375     matthew  5918:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5919:                                               $studentName, $root);
1.275     stredwic 5920:     my @stats = split('&', $fileStat);
                   5921:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5922:         # @stats contains first the filename, then the stat output
                   5923:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5924:     } else {
                   5925:         return -1;
1.253     stredwic 5926:     }
1.26      www      5927: }
                   5928: 
1.712     albertel 5929: sub stat_file {
                   5930:     my ($uri) = @_;
1.787     albertel 5931:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5932: 
1.712     albertel 5933:     my ($udom,$uname,$file,$dir);
                   5934:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5935: 	($udom,$uname,$file) =
1.811     albertel 5936: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5937: 	$file = 'userfiles/'.$file;
1.740     www      5938: 	$dir = &propath($udom,$uname);
1.712     albertel 5939:     }
                   5940:     if ($uri =~ m-^/res/-) {
                   5941: 	($udom,$uname) = 
1.807     albertel 5942: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5943: 	$file = $uri;
                   5944:     }
                   5945: 
                   5946:     if (!$udom || !$uname || !$file) {
                   5947: 	# unable to handle the uri
                   5948: 	return ();
                   5949:     }
                   5950: 
                   5951:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5952:     my @stats = split('&', $result);
1.721     banghart 5953:     
1.712     albertel 5954:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5955: 	shift(@stats); #filename is first
                   5956: 	return @stats;
                   5957:     }
                   5958:     return ();
                   5959: }
                   5960: 
1.26      www      5961: # -------------------------------------------------------- Value of a Condition
                   5962: 
1.713     albertel 5963: # gets the value of a specific preevaluated condition
                   5964: #    stored in the string  $env{user.state.<cid>}
                   5965: # or looks up a condition reference in the bighash and if if hasn't
                   5966: # already been evaluated recurses into docondval to get the value of
                   5967: # the condition, then memoizing it to 
                   5968: #   $env{user.state.<cid>.<condition>}
1.40      www      5969: sub directcondval {
                   5970:     my $number=shift;
1.620     albertel 5971:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5972: 	&Apache::lonuserstate::evalstate();
                   5973:     }
1.713     albertel 5974:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5975: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5976:     } elsif ($number =~ /^_/) {
                   5977: 	my $sub_condition;
                   5978: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5979: 		&GDBM_READER(),0640)) {
                   5980: 	    $sub_condition=$bighash{'conditions'.$number};
                   5981: 	    untie(%bighash);
                   5982: 	}
                   5983: 	my $value = &docondval($sub_condition);
                   5984: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5985: 	return $value;
                   5986:     }
1.620     albertel 5987:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5988:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5989:     } else {
                   5990:        return 2;
                   5991:     }
                   5992: }
                   5993: 
1.713     albertel 5994: # get the collection of conditions for this resource
1.26      www      5995: sub condval {
                   5996:     my $condidx=shift;
1.54      www      5997:     my $allpathcond='';
1.713     albertel 5998:     foreach my $cond (split(/\|/,$condidx)) {
                   5999: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6000: 	    $allpathcond.=
                   6001: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6002: 	}
1.191     harris41 6003:     }
1.54      www      6004:     $allpathcond=~s/\|$//;
1.713     albertel 6005:     return &docondval($allpathcond);
                   6006: }
                   6007: 
                   6008: #evaluates an expression of conditions
                   6009: sub docondval {
                   6010:     my ($allpathcond) = @_;
                   6011:     my $result=0;
                   6012:     if ($env{'request.course.id'}
                   6013: 	&& defined($allpathcond)) {
                   6014: 	my $operand='|';
                   6015: 	my @stack;
                   6016: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6017: 	    if ($chunk eq '(') {
                   6018: 		push @stack,($operand,$result);
                   6019: 	    } elsif ($chunk eq ')') {
                   6020: 		my $before=pop @stack;
                   6021: 		if (pop @stack eq '&') {
                   6022: 		    $result=$result>$before?$before:$result;
                   6023: 		} else {
                   6024: 		    $result=$result>$before?$result:$before;
                   6025: 		}
                   6026: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6027: 		$operand=$chunk;
                   6028: 	    } else {
                   6029: 		my $new=directcondval($chunk);
                   6030: 		if ($operand eq '&') {
                   6031: 		    $result=$result>$new?$new:$result;
                   6032: 		} else {
                   6033: 		    $result=$result>$new?$result:$new;
                   6034: 		}
                   6035: 	    }
                   6036: 	}
1.26      www      6037:     }
                   6038:     return $result;
1.421     albertel 6039: }
                   6040: 
                   6041: # ---------------------------------------------------- Devalidate courseresdata
                   6042: 
                   6043: sub devalidatecourseresdata {
                   6044:     my ($coursenum,$coursedomain)=@_;
                   6045:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6046:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6047: }
                   6048: 
1.763     www      6049: 
1.200     www      6050: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6051: #
                   6052: #  Parameters:
                   6053: #      $coursenum    - Number of the course.
                   6054: #      $coursedomain - Domain at which the course was created.
                   6055: #  Returns:
                   6056: #     A hash of the course parameters along (I think) with timestamps
                   6057: #     and version info.
1.877     foxr     6058: 
1.624     albertel 6059: sub get_courseresdata {
                   6060:     my ($coursenum,$coursedomain)=@_;
1.200     www      6061:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6062:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6063:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6064:     my %dumpreply;
1.417     albertel 6065:     unless (defined($cached)) {
1.624     albertel 6066: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6067: 	$result=\%dumpreply;
1.251     albertel 6068: 	my ($tmp) = keys(%dumpreply);
                   6069: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6070: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6071: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6072: 	    return $tmp;
1.416     albertel 6073: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6074: 	    $result=undef;
1.599     albertel 6075: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6076: 	}
                   6077:     }
1.624     albertel 6078:     return $result;
                   6079: }
                   6080: 
1.633     albertel 6081: sub devalidateuserresdata {
                   6082:     my ($uname,$udom)=@_;
                   6083:     my $hashid="$udom:$uname";
                   6084:     &devalidate_cache_new('userres',$hashid);
                   6085: }
                   6086: 
1.624     albertel 6087: sub get_userresdata {
                   6088:     my ($uname,$udom)=@_;
                   6089:     #most student don\'t have any data set, check if there is some data
                   6090:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6091: 
                   6092:     my $hashid="$udom:$uname";
                   6093:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6094:     if (!defined($cached)) {
                   6095: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6096: 	$result=\%resourcedata;
                   6097: 	&do_cache_new('userres',$hashid,$result,600);
                   6098:     }
                   6099:     my ($tmp)=keys(%$result);
                   6100:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6101: 	return $result;
                   6102:     }
                   6103:     #error 2 occurs when the .db doesn't exist
                   6104:     if ($tmp!~/error: 2 /) {
1.672     albertel 6105: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6106: 		 " Trying to get resource data for ".
                   6107: 		 $uname." at ".$udom.": ".
                   6108: 		 $tmp."</font>");
                   6109:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6110: 	#&EXT_cache_set($udom,$uname);
                   6111: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6112: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6113:     }
                   6114:     return $tmp;
                   6115: }
1.879     foxr     6116: #----------------------------------------------- resdata - return resource data
                   6117: #  Purpose:
                   6118: #    Return resource data for either users or for a course.
                   6119: #  Parameters:
                   6120: #     $name      - Course/user name.
                   6121: #     $domain    - Name of the domain the user/course is registered on.
                   6122: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6123: #     @which     - Array of names of resources desired.
                   6124: #  Returns:
                   6125: #     The value of the first reasource in @which that is found in the
                   6126: #     resource hash.
                   6127: #  Exceptional Conditions:
                   6128: #     If the $type passed in is not valid (not the string 'course' or 
                   6129: #     'user', an undefined  reference is returned.
                   6130: #     If none of the resources are found, an undef is returned
1.624     albertel 6131: sub resdata {
                   6132:     my ($name,$domain,$type,@which)=@_;
                   6133:     my $result;
                   6134:     if ($type eq 'course') {
                   6135: 	$result=&get_courseresdata($name,$domain);
                   6136:     } elsif ($type eq 'user') {
                   6137: 	$result=&get_userresdata($name,$domain);
                   6138:     }
                   6139:     if (!ref($result)) { return $result; }    
1.251     albertel 6140:     foreach my $item (@which) {
1.417     albertel 6141: 	if (defined($result->{$item})) {
                   6142: 	    return $result->{$item};
1.251     albertel 6143: 	}
1.250     albertel 6144:     }
1.291     albertel 6145:     return undef;
1.200     www      6146: }
                   6147: 
1.379     matthew  6148: #
                   6149: # EXT resource caching routines
                   6150: #
                   6151: 
                   6152: sub clear_EXT_cache_status {
1.383     albertel 6153:     &delenv('cache.EXT.');
1.379     matthew  6154: }
                   6155: 
                   6156: sub EXT_cache_status {
                   6157:     my ($target_domain,$target_user) = @_;
1.383     albertel 6158:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6159:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6160:         # We know already the user has no data
                   6161:         return 1;
                   6162:     } else {
                   6163:         return 0;
                   6164:     }
                   6165: }
                   6166: 
                   6167: sub EXT_cache_set {
                   6168:     my ($target_domain,$target_user) = @_;
1.383     albertel 6169:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6170:     #&appenv($cachename => time);
1.379     matthew  6171: }
                   6172: 
1.28      www      6173: # --------------------------------------------------------- Value of a Variable
1.58      www      6174: sub EXT {
1.715     albertel 6175: 
1.395     albertel 6176:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6177:     unless ($varname) { return ''; }
1.218     albertel 6178:     #get real user name/domain, courseid and symb
                   6179:     my $courseid;
1.359     albertel 6180:     my $publicuser;
1.427     www      6181:     if ($symbparm) {
                   6182: 	$symbparm=&get_symb_from_alias($symbparm);
                   6183:     }
1.218     albertel 6184:     if (!($uname && $udom)) {
1.790     albertel 6185:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6186:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6187:     } else {
1.620     albertel 6188: 	$courseid=$env{'request.course.id'};
1.218     albertel 6189:     }
1.48      www      6190:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6191:     my $rest;
1.320     albertel 6192:     if (defined($therest[0])) {
1.48      www      6193:        $rest=join('.',@therest);
                   6194:     } else {
                   6195:        $rest='';
                   6196:     }
1.320     albertel 6197: 
1.57      www      6198:     my $qualifierrest=$qualifier;
                   6199:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6200:     my $spacequalifierrest=$space;
                   6201:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6202:     if ($realm eq 'user') {
1.48      www      6203: # --------------------------------------------------------------- user.resource
                   6204: 	if ($space eq 'resource') {
1.651     albertel 6205: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6206: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6207: 		 &&
1.744     albertel 6208: 		 ($symbparm eq &symbread()) ) {	
                   6209: 		# if we are in the middle of processing the resource the
                   6210: 		# get the value we are planning on committing
                   6211:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6212:                     return $Apache::lonhomework::results{$qualifierrest};
                   6213:                 } else {
                   6214:                     return $Apache::lonhomework::history{$qualifierrest};
                   6215:                 }
1.335     albertel 6216: 	    } else {
1.359     albertel 6217: 		my %restored;
1.620     albertel 6218: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6219: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6220: 		} else {
                   6221: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6222: 		}
1.335     albertel 6223: 		return $restored{$qualifierrest};
                   6224: 	    }
1.48      www      6225: # ----------------------------------------------------------------- user.access
                   6226:         } elsif ($space eq 'access') {
1.218     albertel 6227: 	    # FIXME - not supporting calls for a specific user
1.48      www      6228:             return &allowed($qualifier,$rest);
                   6229: # ------------------------------------------ user.preferences, user.environment
                   6230:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6231: 	    if (($uname eq $env{'user.name'}) &&
                   6232: 		($udom eq $env{'user.domain'})) {
                   6233: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6234: 	    } else {
1.359     albertel 6235: 		my %returnhash;
                   6236: 		if (!$publicuser) {
                   6237: 		    %returnhash=&userenvironment($udom,$uname,
                   6238: 						 $qualifierrest);
                   6239: 		}
1.218     albertel 6240: 		return $returnhash{$qualifierrest};
                   6241: 	    }
1.48      www      6242: # ----------------------------------------------------------------- user.course
                   6243:         } elsif ($space eq 'course') {
1.218     albertel 6244: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6245:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6246: # ------------------------------------------------------------------- user.role
                   6247:         } elsif ($space eq 'role') {
1.218     albertel 6248: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6249:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6250:             if ($qualifier eq 'value') {
                   6251: 		return $role;
                   6252:             } elsif ($qualifier eq 'extent') {
                   6253:                 return $where;
                   6254:             }
                   6255: # ----------------------------------------------------------------- user.domain
                   6256:         } elsif ($space eq 'domain') {
1.218     albertel 6257:             return $udom;
1.48      www      6258: # ------------------------------------------------------------------- user.name
                   6259:         } elsif ($space eq 'name') {
1.218     albertel 6260:             return $uname;
1.48      www      6261: # ---------------------------------------------------- Any other user namespace
1.29      www      6262:         } else {
1.359     albertel 6263: 	    my %reply;
                   6264: 	    if (!$publicuser) {
                   6265: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6266: 	    }
                   6267: 	    return $reply{$qualifierrest};
1.48      www      6268:         }
1.236     www      6269:     } elsif ($realm eq 'query') {
                   6270: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6271:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6272: 						[$spacequalifierrest]);
1.620     albertel 6273: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6274:    } elsif ($realm eq 'request') {
1.48      www      6275: # ------------------------------------------------------------- request.browser
                   6276:         if ($space eq 'browser') {
1.430     www      6277: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6278: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6279: 		    return 1;
                   6280: 		} else {
                   6281: 		    return 0;
                   6282: 		}
                   6283: 	    } else {
1.620     albertel 6284: 		return $env{'browser.'.$qualifier};
1.430     www      6285: 	    }
1.57      www      6286: # ------------------------------------------------------------ request.filename
                   6287:         } else {
1.620     albertel 6288:             return $env{'request.'.$spacequalifierrest};
1.29      www      6289:         }
1.28      www      6290:     } elsif ($realm eq 'course') {
1.48      www      6291: # ---------------------------------------------------------- course.description
1.620     albertel 6292:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6293:     } elsif ($realm eq 'resource') {
1.165     www      6294: 
1.620     albertel 6295: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6296: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6297: 	}
1.693     albertel 6298: 
                   6299: 	if ($space eq 'title') {
                   6300: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6301: 	    return &gettitle($symbparm);
                   6302: 	}
                   6303: 	
                   6304: 	if ($space eq 'map') {
                   6305: 	    my ($map) = &decode_symb($symbparm);
                   6306: 	    return &symbread($map);
                   6307: 	}
                   6308: 
                   6309: 	my ($section, $group, @groups);
1.593     albertel 6310: 	my ($courselevelm,$courselevel);
1.539     albertel 6311: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6312: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6313: 
1.218     albertel 6314: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6315: 
1.60      www      6316: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6317: 	    my $symbp=$symbparm;
1.735     albertel 6318: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6319: 
                   6320: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6321: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6322: 
1.620     albertel 6323: 	    if (($env{'user.name'} eq $uname) &&
                   6324: 		($env{'user.domain'} eq $udom)) {
                   6325: 		$section=$env{'request.course.sec'};
1.733     raeburn  6326:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6327:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6328: 	    } else {
1.539     albertel 6329: 		if (! defined($usection)) {
1.551     albertel 6330: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6331: 		} else {
                   6332: 		    $section = $usection;
                   6333: 		}
1.733     raeburn  6334:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6335: 	    }
                   6336: 
                   6337: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6338: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6339: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6340: 
1.593     albertel 6341: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6342: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6343: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6344: 
1.60      www      6345: # ----------------------------------------------------------- first, check user
1.624     albertel 6346: 
                   6347: 	    my $userreply=&resdata($uname,$udom,'user',
                   6348: 				       ($courselevelr,$courselevelm,
                   6349: 					$courselevel));
                   6350: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6351: 
1.594     albertel 6352: # ------------------------------------------------ second, check some of course
1.684     raeburn  6353:             my $coursereply;
1.691     raeburn  6354:             if (@groups > 0) {
                   6355:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6356:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6357:                 if (defined($coursereply)) { return $coursereply; }
                   6358:             }
1.96      www      6359: 
1.684     raeburn  6360: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6361: 				     $env{'course.'.$courseid.'.domain'},
                   6362: 				     'course',
                   6363: 				     ($seclevelr,$seclevelm,$seclevel,
                   6364: 				      $courselevelr));
1.287     albertel 6365: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6366: 
1.60      www      6367: # ------------------------------------------------------ third, check map parms
1.218     albertel 6368: 	    my %parmhash=();
                   6369: 	    my $thisparm='';
                   6370: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6371: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6372: 		    &GDBM_READER(),0640)) {
1.218     albertel 6373: 		$thisparm=$parmhash{$symbparm};
                   6374: 		untie(%parmhash);
                   6375: 	    }
                   6376: 	    if ($thisparm) { return $thisparm; }
                   6377: 	}
1.594     albertel 6378: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6379: 
1.218     albertel 6380: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6381: 	my $filename;
                   6382: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6383: 	if ($symbparm) {
1.409     www      6384: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6385: 	} else {
1.620     albertel 6386: 	    $filename=$env{'request.filename'};
1.282     albertel 6387: 	}
                   6388: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6389: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6390: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6391: 	if (defined($metadata)) { return $metadata; }
1.142     www      6392: 
1.594     albertel 6393: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6394: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6395: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6396: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6397: 				     $env{'course.'.$courseid.'.domain'},
                   6398: 				     'course',
                   6399: 				     ($courselevelm,$courselevel));
1.593     albertel 6400: 	    if (defined($coursereply)) { return $coursereply; }
                   6401: 	}
1.145     www      6402: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6403: 	unless ($space eq '0') {
1.336     albertel 6404: 	    my @parts=split(/_/,$space);
                   6405: 	    my $id=pop(@parts);
                   6406: 	    my $part=join('_',@parts);
                   6407: 	    if ($part eq '') { $part='0'; }
                   6408: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6409: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6410: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6411: 	}
1.395     albertel 6412: 	if ($recurse) { return undef; }
                   6413: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6414: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6415: 
1.48      www      6416: # ---------------------------------------------------- Any other user namespace
                   6417:     } elsif ($realm eq 'environment') {
                   6418: # ----------------------------------------------------------------- environment
1.620     albertel 6419: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6420: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6421: 	} else {
1.770     albertel 6422: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6423: 		return '';
                   6424: 	    }
1.219     albertel 6425: 	    my %returnhash=&userenvironment($udom,$uname,
                   6426: 					    $spacequalifierrest);
                   6427: 	    return $returnhash{$spacequalifierrest};
                   6428: 	}
1.28      www      6429:     } elsif ($realm eq 'system') {
1.48      www      6430: # ----------------------------------------------------------------- system.time
                   6431: 	if ($space eq 'time') {
                   6432: 	    return time;
                   6433:         }
1.696     albertel 6434:     } elsif ($realm eq 'server') {
                   6435: # ----------------------------------------------------------------- system.time
                   6436: 	if ($space eq 'name') {
                   6437: 	    return $ENV{'SERVER_NAME'};
                   6438:         }
1.28      www      6439:     }
1.48      www      6440:     return '';
1.61      www      6441: }
                   6442: 
1.691     raeburn  6443: sub check_group_parms {
                   6444:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6445:     my @groupitems = ();
                   6446:     my $resultitem;
                   6447:     my @levels = ($symbparm,$mapparm,$what);
                   6448:     foreach my $group (@{$groups}) {
                   6449:         foreach my $level (@levels) {
                   6450:              my $item = $courseid.'.['.$group.'].'.$level;
                   6451:              push(@groupitems,$item);
                   6452:         }
                   6453:     }
                   6454:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6455:                             $env{'course.'.$courseid.'.domain'},
                   6456:                                      'course',@groupitems);
                   6457:     return $coursereply;
                   6458: }
                   6459: 
                   6460: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6461:     my ($courseid,@groups) = @_;
                   6462:     @groups = sort(@groups);
1.691     raeburn  6463:     return @groups;
                   6464: }
                   6465: 
1.395     albertel 6466: sub packages_tab_default {
                   6467:     my ($uri,$varname)=@_;
                   6468:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6469: 
                   6470:     my (@extension,@specifics,$do_default);
                   6471:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6472: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6473: 	if ($pack_type eq 'default') {
                   6474: 	    $do_default=1;
                   6475: 	} elsif ($pack_type eq 'extension') {
                   6476: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6477: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6478: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6479: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6480: 	}
                   6481:     }
                   6482:     # first look for a package that matches the requested part id
                   6483:     foreach my $package (@specifics) {
                   6484: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6485: 	next if ($pack_part ne $part);
                   6486: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6487: 	    return $packagetab{"$pack_type&$name&default"};
                   6488: 	}
                   6489:     }
                   6490:     # look for any possible matching non extension_ package
                   6491:     foreach my $package (@specifics) {
                   6492: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6493: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6494: 	    return $packagetab{"$pack_type&$name&default"};
                   6495: 	}
1.585     albertel 6496: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6497: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6498: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6499: 	}
                   6500:     }
1.738     albertel 6501:     # look for any posible extension_ match
                   6502:     foreach my $package (@extension) {
                   6503: 	my ($package,$pack_type)=@{$package};
                   6504: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6505: 	    return $packagetab{"$pack_type&$name&default"};
                   6506: 	}
                   6507: 	if (defined($packagetab{$package."&$name&default"})) {
                   6508: 	    return $packagetab{$package."&$name&default"};
                   6509: 	}
                   6510:     }
                   6511:     # look for a global default setting
                   6512:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6513: 	return $packagetab{"default&$name&default"};
                   6514:     }
1.395     albertel 6515:     return undef;
                   6516: }
                   6517: 
1.334     albertel 6518: sub add_prefix_and_part {
                   6519:     my ($prefix,$part)=@_;
                   6520:     my $keyroot;
                   6521:     if (defined($prefix) && $prefix !~ /^__/) {
                   6522: 	# prefix that has a part already
                   6523: 	$keyroot=$prefix;
                   6524:     } elsif (defined($prefix)) {
                   6525: 	# prefix that is missing a part
                   6526: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6527:     } else {
                   6528: 	# no prefix at all
                   6529: 	if (defined($part)) { $keyroot='_'.$part; }
                   6530:     }
                   6531:     return $keyroot;
                   6532: }
                   6533: 
1.71      www      6534: # ---------------------------------------------------------------- Get metadata
                   6535: 
1.599     albertel 6536: my %metaentry;
1.71      www      6537: sub metadata {
1.176     www      6538:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6539:     $uri=&declutter($uri);
1.288     albertel 6540:     # if it is a non metadata possible uri return quickly
1.529     albertel 6541:     if (($uri eq '') || 
                   6542: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6543: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6544:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6545: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6546: 	return undef;
1.288     albertel 6547:     }
1.73      www      6548:     my $filename=$uri;
                   6549:     $uri=~s/\.meta$//;
1.172     www      6550: #
                   6551: # Is the metadata already cached?
1.177     www      6552: # Look at timestamp of caching
1.172     www      6553: # Everything is cached by the main uri, libraries are never directly cached
                   6554: #
1.428     albertel 6555:     if (!defined($liburi)) {
1.599     albertel 6556: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6557: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6558:     }
                   6559:     {
1.172     www      6560: #
                   6561: # Is this a recursive call for a library?
                   6562: #
1.599     albertel 6563: #	if (! exists($metacache{$uri})) {
                   6564: #	    $metacache{$uri}={};
                   6565: #	}
1.171     www      6566:         if ($liburi) {
                   6567: 	    $liburi=&declutter($liburi);
                   6568:             $filename=$liburi;
1.401     bowersj2 6569:         } else {
1.599     albertel 6570: 	    &devalidate_cache_new('meta',$uri);
                   6571: 	    undef(%metaentry);
1.401     bowersj2 6572: 	}
1.140     www      6573:         my %metathesekeys=();
1.73      www      6574:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6575: 	my $metastring;
1.768     albertel 6576: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6577: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6578: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6579: 	    $metastring=&getfile($file);
1.489     albertel 6580: 	}
1.208     albertel 6581:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6582:         my $token;
1.140     www      6583:         undef %metathesekeys;
1.71      www      6584:         while ($token=$parser->get_token) {
1.339     albertel 6585: 	    if ($token->[0] eq 'S') {
                   6586: 		if (defined($token->[2]->{'package'})) {
1.172     www      6587: #
                   6588: # This is a package - get package info
                   6589: #
1.339     albertel 6590: 		    my $package=$token->[2]->{'package'};
                   6591: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6592: 		    if (defined($token->[2]->{'id'})) { 
                   6593: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6594: 		    }
1.599     albertel 6595: 		    if ($metaentry{':packages'}) {
                   6596: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6597: 		    } else {
1.599     albertel 6598: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6599: 		    }
1.736     albertel 6600: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6601: 			my $part=$keyroot;
                   6602: 			$part=~s/^\_//;
1.736     albertel 6603: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6604: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6605: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6606: 			    # ignore package.tab specified default values
                   6607:                             # here &package_tab_default() will fetch those
                   6608: 			    if ($subp eq 'default') { next; }
1.736     albertel 6609: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6610: 			    my $unikey;
                   6611: 			    if ($pack =~ /_0$/) {
                   6612: 				$unikey='parameter_0_'.$name;
                   6613: 				$part=0;
                   6614: 			    } else {
                   6615: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6616: 			    }
1.339     albertel 6617: 			    if ($subp eq 'display') {
                   6618: 				$value.=' [Part: '.$part.']';
                   6619: 			    }
1.599     albertel 6620: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6621: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6622: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6623: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6624: 			    }
1.599     albertel 6625: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6626: 				$metaentry{':'.$unikey}=
                   6627: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6628: 			    }
1.339     albertel 6629: 			}
                   6630: 		    }
                   6631: 		} else {
1.172     www      6632: #
                   6633: # This is not a package - some other kind of start tag
1.339     albertel 6634: #
                   6635: 		    my $entry=$token->[1];
                   6636: 		    my $unikey;
                   6637: 		    if ($entry eq 'import') {
                   6638: 			$unikey='';
                   6639: 		    } else {
                   6640: 			$unikey=$entry;
                   6641: 		    }
                   6642: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6643: 
                   6644: 		    if (defined($token->[2]->{'id'})) { 
                   6645: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6646: 		    }
1.175     www      6647: 
1.339     albertel 6648: 		    if ($entry eq 'import') {
1.175     www      6649: #
                   6650: # Importing a library here
1.339     albertel 6651: #
                   6652: 			if ($depthcount<20) {
                   6653: 			    my $location=$parser->get_text('/import');
                   6654: 			    my $dir=$filename;
                   6655: 			    $dir=~s|[^/]*$||;
                   6656: 			    $location=&filelocation($dir,$location);
1.736     albertel 6657: 			    my $metadata = 
                   6658: 				&metadata($uri,'keys', $location,$unikey,
                   6659: 					  $depthcount+1);
                   6660: 			    foreach my $meta (split(',',$metadata)) {
                   6661: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6662: 				$metathesekeys{$meta}=1;
1.339     albertel 6663: 			    }
                   6664: 			}
                   6665: 		    } else { 
                   6666: 			
                   6667: 			if (defined($token->[2]->{'name'})) { 
                   6668: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6669: 			}
                   6670: 			$metathesekeys{$unikey}=1;
1.736     albertel 6671: 			foreach my $param (@{$token->[3]}) {
                   6672: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6673: 				$token->[2]->{$param};
1.339     albertel 6674: 			}
                   6675: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6676: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6677: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6678: 		 # only ws inside the tag, and not in default, so use default
                   6679: 		 # as value
1.599     albertel 6680: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6681: 			} else {
1.321     albertel 6682: 		  # either something interesting inside the tag or default
                   6683:                   # uninteresting
1.599     albertel 6684: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6685: 			}
1.172     www      6686: # end of not-a-package not-a-library import
1.339     albertel 6687: 		    }
1.172     www      6688: # end of not-a-package start tag
1.339     albertel 6689: 		}
1.172     www      6690: # the next is the end of "start tag"
1.339     albertel 6691: 	    }
                   6692: 	}
1.483     albertel 6693: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6694: 	$extension = lc($extension);
                   6695: 	if ($extension eq 'htm') { $extension='html'; }
                   6696: 
1.737     albertel 6697: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6698: 	    #no specific packages #how's our extension
                   6699: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6700: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6701: 					 \%metathesekeys);
                   6702: 	}
1.883     albertel 6703: 
                   6704: 	if (!exists($metaentry{':packages'})
                   6705: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6706: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6707: 		#no specific packages well let's get default then
                   6708: 		if ($key!~/^default&/) { next; }
1.488     albertel 6709: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6710: 					     \%metathesekeys);
                   6711: 	    }
                   6712: 	}
1.338     www      6713: # are there custom rights to evaluate
1.599     albertel 6714: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6715: 
1.338     www      6716:     #
                   6717:     # Importing a rights file here
1.339     albertel 6718:     #
                   6719: 	    unless ($depthcount) {
1.599     albertel 6720: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6721: 		my $dir=$filename;
                   6722: 		$dir=~s|[^/]*$||;
                   6723: 		$location=&filelocation($dir,$location);
1.736     albertel 6724: 		my $rights_metadata =
                   6725: 		    &metadata($uri,'keys',$location,'_rights',
                   6726: 			      $depthcount+1);
                   6727: 		foreach my $rights (split(',',$rights_metadata)) {
                   6728: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6729: 		    $metathesekeys{$rights}=1;
1.339     albertel 6730: 		}
                   6731: 	    }
                   6732: 	}
1.737     albertel 6733: 	# uniqifiy package listing
                   6734: 	my %seen;
                   6735: 	my @uniq_packages =
                   6736: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6737: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6738: 
                   6739: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6740: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6741: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6742: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6743: # this is the end of "was not already recently cached
1.71      www      6744:     }
1.599     albertel 6745:     return $metaentry{':'.$what};
1.261     albertel 6746: }
                   6747: 
1.488     albertel 6748: sub metadata_create_package_def {
1.483     albertel 6749:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6750:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6751:     if ($subp eq 'default') { next; }
                   6752:     
1.599     albertel 6753:     if (defined($metaentry{':packages'})) {
                   6754: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6755:     } else {
1.599     albertel 6756: 	$metaentry{':packages'}=$package;
1.483     albertel 6757:     }
                   6758:     my $value=$packagetab{$key};
                   6759:     my $unikey;
                   6760:     $unikey='parameter_0_'.$name;
1.599     albertel 6761:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6762:     $$metathesekeys{$unikey}=1;
1.599     albertel 6763:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6764: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6765:     }
1.599     albertel 6766:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6767: 	$metaentry{':'.$unikey}=
                   6768: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6769:     }
                   6770: }
                   6771: 
1.261     albertel 6772: sub metadata_generate_part0 {
                   6773:     my ($metadata,$metacache,$uri) = @_;
                   6774:     my %allnames;
1.737     albertel 6775:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6776: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6777: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6778: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6779: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6780: 	    $allnames{$name}=$part;
                   6781: 	  }
                   6782: 	}
                   6783:     }
                   6784:     foreach my $name (keys(%allnames)) {
                   6785:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6786:       my $key=":parameter_0_$name";
1.261     albertel 6787:       $$metacache{"$key.part"}='0';
                   6788:       $$metacache{"$key.name"}=$name;
1.428     albertel 6789:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6790: 					   $allnames{$name}.'_'.$name.
                   6791: 					   '.type'};
1.428     albertel 6792:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6793: 			     '.display'};
1.644     www      6794:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6795:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6796:       $$metacache{"$key.display"}=$olddis;
                   6797:     }
1.71      www      6798: }
                   6799: 
1.764     albertel 6800: # ------------------------------------------------------ Devalidate title cache
                   6801: 
                   6802: sub devalidate_title_cache {
                   6803:     my ($url)=@_;
                   6804:     if (!$env{'request.course.id'}) { return; }
                   6805:     my $symb=&symbread($url);
                   6806:     if (!$symb) { return; }
                   6807:     my $key=$env{'request.course.id'}."\0".$symb;
                   6808:     &devalidate_cache_new('title',$key);
                   6809: }
                   6810: 
1.301     www      6811: # ------------------------------------------------- Get the title of a resource
                   6812: 
                   6813: sub gettitle {
                   6814:     my $urlsymb=shift;
                   6815:     my $symb=&symbread($urlsymb);
1.534     albertel 6816:     if ($symb) {
1.620     albertel 6817: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6818: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6819: 	if (defined($cached)) { 
                   6820: 	    return $result;
                   6821: 	}
1.534     albertel 6822: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6823: 	my $title='';
                   6824: 	my %bighash;
1.620     albertel 6825: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6826: 		&GDBM_READER(),0640)) {
                   6827: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6828: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6829: 	    untie %bighash;
                   6830: 	}
                   6831: 	$title=~s/\&colon\;/\:/gs;
                   6832: 	if ($title) {
1.599     albertel 6833: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6834: 	}
                   6835: 	$urlsymb=$url;
                   6836:     }
                   6837:     my $title=&metadata($urlsymb,'title');
                   6838:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6839:     return $title;
1.301     www      6840: }
1.613     albertel 6841: 
1.614     albertel 6842: sub get_slot {
                   6843:     my ($which,$cnum,$cdom)=@_;
                   6844:     if (!$cnum || !$cdom) {
1.790     albertel 6845: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6846: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6847: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6848:     }
1.703     albertel 6849:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6850:     my %slotinfo;
                   6851:     if (exists($remembered{$key})) {
                   6852: 	$slotinfo{$which} = $remembered{$key};
                   6853:     } else {
                   6854: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6855: 	&Apache::lonhomework::showhash(%slotinfo);
                   6856: 	my ($tmp)=keys(%slotinfo);
                   6857: 	if ($tmp=~/^error:/) { return (); }
                   6858: 	$remembered{$key} = $slotinfo{$which};
                   6859:     }
1.616     albertel 6860:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6861: 	return %{$slotinfo{$which}};
                   6862:     }
                   6863:     return $slotinfo{$which};
1.614     albertel 6864: }
1.31      www      6865: # ------------------------------------------------- Update symbolic store links
                   6866: 
                   6867: sub symblist {
                   6868:     my ($mapname,%newhash)=@_;
1.438     www      6869:     $mapname=&deversion(&declutter($mapname));
1.31      www      6870:     my %hash;
1.620     albertel 6871:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6872:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6873:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6874: 	    foreach my $url (keys %newhash) {
                   6875: 		next if ($url eq 'last_known'
                   6876: 			 && $env{'form.no_update_last_known'});
                   6877: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6878: 						    $newhash{$url}->[1],
                   6879: 						    $newhash{$url}->[0]);
1.191     harris41 6880:             }
1.31      www      6881:             if (untie(%hash)) {
                   6882: 		return 'ok';
                   6883:             }
                   6884:         }
                   6885:     }
                   6886:     return 'error';
1.212     www      6887: }
                   6888: 
                   6889: # --------------------------------------------------------------- Verify a symb
                   6890: 
                   6891: sub symbverify {
1.510     www      6892:     my ($symb,$thisurl)=@_;
                   6893:     my $thisfn=$thisurl;
1.439     www      6894:     $thisfn=&declutter($thisfn);
1.215     www      6895: # direct jump to resource in page or to a sequence - will construct own symbs
                   6896:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6897: # check URL part
1.409     www      6898:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6899: 
1.431     www      6900:     unless ($url eq $thisfn) { return 0; }
1.213     www      6901: 
1.216     www      6902:     $symb=&symbclean($symb);
1.510     www      6903:     $thisurl=&deversion($thisurl);
1.439     www      6904:     $thisfn=&deversion($thisfn);
1.213     www      6905: 
                   6906:     my %bighash;
                   6907:     my $okay=0;
1.431     www      6908: 
1.620     albertel 6909:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6910:                             &GDBM_READER(),0640)) {
1.510     www      6911:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6912:         unless ($ids) { 
1.510     www      6913:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6914:         }
                   6915:         if ($ids) {
                   6916: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6917: 	    foreach my $id (split(/\,/,$ids)) {
                   6918: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6919:                if (
                   6920:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6921:    eq $symb) { 
1.620     albertel 6922: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6923: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6924: 		       $okay=1; 
                   6925: 		   }
                   6926: 	       }
1.216     www      6927: 	   }
                   6928:         }
1.213     www      6929: 	untie(%bighash);
                   6930:     }
                   6931:     return $okay;
1.31      www      6932: }
                   6933: 
1.210     www      6934: # --------------------------------------------------------------- Clean-up symb
                   6935: 
                   6936: sub symbclean {
                   6937:     my $symb=shift;
1.568     albertel 6938:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6939: # remove version from map
                   6940:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6941: 
1.210     www      6942: # remove version from URL
                   6943:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6944: 
1.507     www      6945: # remove wrapper
                   6946: 
1.510     www      6947:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6948:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6949:     return $symb;
1.409     www      6950: }
                   6951: 
                   6952: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6953: 
                   6954: sub encode_symb {
                   6955:     my ($map,$resid,$url)=@_;
                   6956:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6957: }
1.409     www      6958: 
                   6959: sub decode_symb {
1.568     albertel 6960:     my $symb=shift;
                   6961:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6962:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6963:     return (&fixversion($map),$resid,&fixversion($url));
                   6964: }
                   6965: 
                   6966: sub fixversion {
                   6967:     my $fn=shift;
1.609     banghart 6968:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6969:     my %bighash;
                   6970:     my $uri=&clutter($fn);
1.620     albertel 6971:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6972: # is this cached?
1.599     albertel 6973:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6974:     if (defined($cached)) { return $result; }
                   6975: # unfortunately not cached, or expired
1.620     albertel 6976:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6977: 	    &GDBM_READER(),0640)) {
                   6978:  	if ($bighash{'version_'.$uri}) {
                   6979:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6980:  	    unless (($version eq 'mostrecent') || 
                   6981: 		    ($version==&getversion($uri))) {
1.440     www      6982:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6983:  	    }
                   6984:  	}
                   6985:  	untie %bighash;
1.413     www      6986:     }
1.599     albertel 6987:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6988: }
                   6989: 
                   6990: sub deversion {
                   6991:     my $url=shift;
                   6992:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6993:     return $url;
1.210     www      6994: }
                   6995: 
1.31      www      6996: # ------------------------------------------------------ Return symb list entry
                   6997: 
                   6998: sub symbread {
1.249     www      6999:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7000:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7001:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7002: # no filename provided? try from environment
1.44      www      7003:     unless ($thisfn) {
1.620     albertel 7004:         if ($env{'request.symb'}) {
                   7005: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7006: 	}
1.620     albertel 7007: 	$thisfn=$env{'request.filename'};
1.44      www      7008:     }
1.569     albertel 7009:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7010: # is that filename actually a symb? Verify, clean, and return
                   7011:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7012: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7013: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7014: 	}
1.242     www      7015:     }
1.44      www      7016:     $thisfn=declutter($thisfn);
1.31      www      7017:     my %hash;
1.37      www      7018:     my %bighash;
                   7019:     my $syval='';
1.620     albertel 7020:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7021:         my $targetfn = $thisfn;
1.609     banghart 7022:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7023:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7024:         }
1.687     albertel 7025: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7026: 	    $targetfn=$1;
                   7027: 	}
1.620     albertel 7028:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7029:                       &GDBM_READER(),0640)) {
1.481     raeburn  7030: 	    $syval=$hash{$targetfn};
1.37      www      7031:             untie(%hash);
                   7032:         }
                   7033: # ---------------------------------------------------------- There was an entry
                   7034:         if ($syval) {
1.601     albertel 7035: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7036: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7037: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7038: 		    #return $env{$cache_str}='';
1.601     albertel 7039: 		#}    
                   7040: 		#$syval.=$1;
                   7041: 	    #}
1.37      www      7042:         } else {
                   7043: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7044:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7045:                             &GDBM_READER(),0640)) {
1.37      www      7046: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7047:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7048:               unless ($ids) { 
                   7049:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7050:               }
                   7051:               unless ($ids) {
                   7052: # alias?
                   7053: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7054:               }
1.37      www      7055:               if ($ids) {
                   7056: # ------------------------------------------------------------------- Has ID(s)
                   7057:                  my @possibilities=split(/\,/,$ids);
1.39      www      7058:                  if ($#possibilities==0) {
                   7059: # ----------------------------------------------- There is only one possibility
1.37      www      7060: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7061: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7062: 						    $resid,$thisfn);
1.249     www      7063:                  } elsif (!$donotrecurse) {
1.39      www      7064: # ------------------------------------------ There is more than one possibility
                   7065:                      my $realpossible=0;
1.800     albertel 7066:                      foreach my $id (@possibilities) {
                   7067: 			 my $file=$bighash{'src_'.$id};
1.39      www      7068:                          if (&allowed('bre',$file)) {
1.800     albertel 7069:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7070:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7071: 				$realpossible++;
1.626     albertel 7072:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7073: 						    $resid,$thisfn);
1.39      www      7074:                             }
                   7075: 			 }
1.191     harris41 7076:                      }
1.39      www      7077: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7078:                  } else {
                   7079:                      $syval='';
1.37      www      7080:                  }
                   7081: 	      }
                   7082:               untie(%bighash)
1.481     raeburn  7083:            }
1.31      www      7084:         }
1.62      www      7085:         if ($syval) {
1.620     albertel 7086: 	    return $env{$cache_str}=$syval;
1.62      www      7087:         }
1.31      www      7088:     }
1.44      www      7089:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7090:     return $env{$cache_str}='';
1.31      www      7091: }
                   7092: 
                   7093: # ---------------------------------------------------------- Return random seed
                   7094: 
1.32      www      7095: sub numval {
                   7096:     my $txt=shift;
                   7097:     $txt=~tr/A-J/0-9/;
                   7098:     $txt=~tr/a-j/0-9/;
                   7099:     $txt=~tr/K-T/0-9/;
                   7100:     $txt=~tr/k-t/0-9/;
                   7101:     $txt=~tr/U-Z/0-5/;
                   7102:     $txt=~tr/u-z/0-5/;
                   7103:     $txt=~s/\D//g;
1.564     albertel 7104:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7105:     return int($txt);
1.368     albertel 7106: }
                   7107: 
1.484     albertel 7108: sub numval2 {
                   7109:     my $txt=shift;
                   7110:     $txt=~tr/A-J/0-9/;
                   7111:     $txt=~tr/a-j/0-9/;
                   7112:     $txt=~tr/K-T/0-9/;
                   7113:     $txt=~tr/k-t/0-9/;
                   7114:     $txt=~tr/U-Z/0-5/;
                   7115:     $txt=~tr/u-z/0-5/;
                   7116:     $txt=~s/\D//g;
                   7117:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7118:     my $total;
                   7119:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7120:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7121:     return int($total);
                   7122: }
                   7123: 
1.575     albertel 7124: sub numval3 {
                   7125:     use integer;
                   7126:     my $txt=shift;
                   7127:     $txt=~tr/A-J/0-9/;
                   7128:     $txt=~tr/a-j/0-9/;
                   7129:     $txt=~tr/K-T/0-9/;
                   7130:     $txt=~tr/k-t/0-9/;
                   7131:     $txt=~tr/U-Z/0-5/;
                   7132:     $txt=~tr/u-z/0-5/;
                   7133:     $txt=~s/\D//g;
                   7134:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7135:     my $total;
                   7136:     foreach my $val (@txts) { $total+=$val; }
                   7137:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7138:     return $total;
                   7139: }
                   7140: 
1.675     albertel 7141: sub digest {
                   7142:     my ($data)=@_;
                   7143:     my $digest=&Digest::MD5::md5($data);
                   7144:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7145:     my ($e,$f);
                   7146:     {
                   7147:         use integer;
                   7148:         $e=($a+$b);
                   7149:         $f=($c+$d);
                   7150:         if ($_64bit) {
                   7151:             $e=(($e<<32)>>32);
                   7152:             $f=(($f<<32)>>32);
                   7153:         }
                   7154:     }
                   7155:     if (wantarray) {
                   7156: 	return ($e,$f);
                   7157:     } else {
                   7158: 	my $g;
                   7159: 	{
                   7160: 	    use integer;
                   7161: 	    $g=($e+$f);
                   7162: 	    if ($_64bit) {
                   7163: 		$g=(($g<<32)>>32);
                   7164: 	    }
                   7165: 	}
                   7166: 	return $g;
                   7167:     }
                   7168: }
                   7169: 
1.368     albertel 7170: sub latest_rnd_algorithm_id {
1.675     albertel 7171:     return '64bit5';
1.366     albertel 7172: }
1.32      www      7173: 
1.503     albertel 7174: sub get_rand_alg {
                   7175:     my ($courseid)=@_;
1.790     albertel 7176:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7177:     if ($courseid) {
1.620     albertel 7178: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7179:     }
                   7180:     return &latest_rnd_algorithm_id();
                   7181: }
                   7182: 
1.562     albertel 7183: sub validCODE {
                   7184:     my ($CODE)=@_;
                   7185:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7186:     return 0;
                   7187: }
                   7188: 
1.491     albertel 7189: sub getCODE {
1.620     albertel 7190:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7191:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7192: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7193: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7194: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7195:     }
                   7196:     return undef;
                   7197: }
                   7198: 
1.31      www      7199: sub rndseed {
1.155     albertel 7200:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7201:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7202:     if (!defined($symb)) {
1.366     albertel 7203: 	unless ($symb=$wsymb) { return time; }
                   7204:     }
                   7205:     if (!$courseid) { $courseid=$wcourseid; }
                   7206:     if (!$domain) { $domain=$wdomain; }
                   7207:     if (!$username) { $username=$wusername }
1.503     albertel 7208:     my $which=&get_rand_alg();
1.803     albertel 7209: 
1.491     albertel 7210:     if (defined(&getCODE())) {
1.675     albertel 7211: 	if ($which eq '64bit5') {
                   7212: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7213: 	} elsif ($which eq '64bit4') {
1.575     albertel 7214: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7215: 	} else {
                   7216: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7217: 	}
1.675     albertel 7218:     } elsif ($which eq '64bit5') {
                   7219: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7220:     } elsif ($which eq '64bit4') {
                   7221: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7222:     } elsif ($which eq '64bit3') {
                   7223: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7224:     } elsif ($which eq '64bit2') {
                   7225: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7226:     } elsif ($which eq '64bit') {
                   7227: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7228:     }
                   7229:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7230: }
                   7231: 
                   7232: sub rndseed_32bit {
                   7233:     my ($symb,$courseid,$domain,$username)=@_;
                   7234:     {
                   7235: 	use integer;
                   7236: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7237: 	my $symbseed=numval($symb) << 22;
                   7238: 	my $namechck=unpack("%32C*",$username) << 17;
                   7239: 	my $nameseed=numval($username) << 12;
                   7240: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7241: 	my $courseseed=unpack("%32C*",$courseid);
                   7242: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7243: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7244: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7245: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7246: 	return $num;
                   7247:     }
                   7248: }
                   7249: 
                   7250: sub rndseed_64bit {
                   7251:     my ($symb,$courseid,$domain,$username)=@_;
                   7252:     {
                   7253: 	use integer;
                   7254: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7255: 	my $symbseed=numval($symb) << 10;
                   7256: 	my $namechck=unpack("%32S*",$username);
                   7257: 	
                   7258: 	my $nameseed=numval($username) << 21;
                   7259: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7260: 	my $courseseed=unpack("%32S*",$courseid);
                   7261: 	
                   7262: 	my $num1=$symbchck+$symbseed+$namechck;
                   7263: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7264: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7265: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7266: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7267: 	return "$num1,$num2";
1.155     albertel 7268:     }
1.366     albertel 7269: }
                   7270: 
1.443     albertel 7271: sub rndseed_64bit2 {
                   7272:     my ($symb,$courseid,$domain,$username)=@_;
                   7273:     {
                   7274: 	use integer;
                   7275: 	# strings need to be an even # of cahracters long, it it is odd the
                   7276:         # last characters gets thrown away
                   7277: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7278: 	my $symbseed=numval($symb) << 10;
                   7279: 	my $namechck=unpack("%32S*",$username.' ');
                   7280: 	
                   7281: 	my $nameseed=numval($username) << 21;
1.501     albertel 7282: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7283: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7284: 	
                   7285: 	my $num1=$symbchck+$symbseed+$namechck;
                   7286: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7287: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7288: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7289: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7290: 	return "$num1,$num2";
                   7291:     }
                   7292: }
                   7293: 
                   7294: sub rndseed_64bit3 {
                   7295:     my ($symb,$courseid,$domain,$username)=@_;
                   7296:     {
                   7297: 	use integer;
                   7298: 	# strings need to be an even # of cahracters long, it it is odd the
                   7299:         # last characters gets thrown away
                   7300: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7301: 	my $symbseed=numval2($symb) << 10;
                   7302: 	my $namechck=unpack("%32S*",$username.' ');
                   7303: 	
                   7304: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7305: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7306: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7307: 	
                   7308: 	my $num1=$symbchck+$symbseed+$namechck;
                   7309: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7310: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7311: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7312: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7313: 	
1.503     albertel 7314: 	return "$num1:$num2";
1.443     albertel 7315:     }
                   7316: }
                   7317: 
1.575     albertel 7318: sub rndseed_64bit4 {
                   7319:     my ($symb,$courseid,$domain,$username)=@_;
                   7320:     {
                   7321: 	use integer;
                   7322: 	# strings need to be an even # of cahracters long, it it is odd the
                   7323:         # last characters gets thrown away
                   7324: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7325: 	my $symbseed=numval3($symb) << 10;
                   7326: 	my $namechck=unpack("%32S*",$username.' ');
                   7327: 	
                   7328: 	my $nameseed=numval3($username) << 21;
                   7329: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7330: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7331: 	
                   7332: 	my $num1=$symbchck+$symbseed+$namechck;
                   7333: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7334: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7335: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7336: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7337: 	
                   7338: 	return "$num1:$num2";
                   7339:     }
                   7340: }
                   7341: 
1.675     albertel 7342: sub rndseed_64bit5 {
                   7343:     my ($symb,$courseid,$domain,$username)=@_;
                   7344:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7345:     return "$num1:$num2";
                   7346: }
                   7347: 
1.366     albertel 7348: sub rndseed_CODE_64bit {
                   7349:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7350:     {
1.366     albertel 7351: 	use integer;
1.443     albertel 7352: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7353: 	my $symbseed=numval2($symb);
1.491     albertel 7354: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7355: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7356: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7357: 	my $num1=$symbseed+$CODEchck;
                   7358: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7359: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7360: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7361: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7362: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7363: 	return "$num1:$num2";
1.366     albertel 7364:     }
                   7365: }
                   7366: 
1.575     albertel 7367: sub rndseed_CODE_64bit4 {
                   7368:     my ($symb,$courseid,$domain,$username)=@_;
                   7369:     {
                   7370: 	use integer;
                   7371: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7372: 	my $symbseed=numval3($symb);
                   7373: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7374: 	my $CODEseed=numval3(&getCODE());
                   7375: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7376: 	my $num1=$symbseed+$CODEchck;
                   7377: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7378: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7379: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7380: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7381: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7382: 	return "$num1:$num2";
                   7383:     }
                   7384: }
                   7385: 
1.675     albertel 7386: sub rndseed_CODE_64bit5 {
                   7387:     my ($symb,$courseid,$domain,$username)=@_;
                   7388:     my $code = &getCODE();
                   7389:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7390:     return "$num1:$num2";
                   7391: }
                   7392: 
1.366     albertel 7393: sub setup_random_from_rndseed {
                   7394:     my ($rndseed)=@_;
1.503     albertel 7395:     if ($rndseed =~/([,:])/) {
                   7396: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7397: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7398:     } else {
                   7399: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7400:     }
1.36      albertel 7401: }
                   7402: 
1.474     albertel 7403: sub latest_receipt_algorithm_id {
1.835     albertel 7404:     return 'receipt3';
1.474     albertel 7405: }
                   7406: 
1.480     www      7407: sub recunique {
                   7408:     my $fucourseid=shift;
                   7409:     my $unique;
1.835     albertel 7410:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7411: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7412: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7413:     } else {
                   7414: 	$unique=$perlvar{'lonReceipt'};
                   7415:     }
                   7416:     return unpack("%32C*",$unique);
                   7417: }
                   7418: 
                   7419: sub recprefix {
                   7420:     my $fucourseid=shift;
                   7421:     my $prefix;
1.835     albertel 7422:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7423: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7424: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7425:     } else {
                   7426: 	$prefix=$perlvar{'lonHostID'};
                   7427:     }
                   7428:     return unpack("%32C*",$prefix);
                   7429: }
                   7430: 
1.76      www      7431: sub ireceipt {
1.474     albertel 7432:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7433: 
                   7434:     my $return =&recprefix($fucourseid).'-';
                   7435: 
                   7436:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7437: 	$env{'request.state'} eq 'construct') {
                   7438: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7439: 	return $return;
                   7440:     }
                   7441: 
1.76      www      7442:     my $cuname=unpack("%32C*",$funame);
                   7443:     my $cudom=unpack("%32C*",$fudom);
                   7444:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7445:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7446:     my $cunique=&recunique($fucourseid);
1.474     albertel 7447:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7448:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7449: 
1.790     albertel 7450: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7451: 			       
                   7452: 	$return.= ($cunique%$cuname+
                   7453: 		   $cunique%$cudom+
                   7454: 		   $cusymb%$cuname+
                   7455: 		   $cusymb%$cudom+
                   7456: 		   $cucourseid%$cuname+
                   7457: 		   $cucourseid%$cudom+
                   7458: 		   $cpart%$cuname+
                   7459: 		   $cpart%$cudom);
                   7460:     } else {
                   7461: 	$return.= ($cunique%$cuname+
                   7462: 		   $cunique%$cudom+
                   7463: 		   $cusymb%$cuname+
                   7464: 		   $cusymb%$cudom+
                   7465: 		   $cucourseid%$cuname+
                   7466: 		   $cucourseid%$cudom);
                   7467:     }
                   7468:     return $return;
1.76      www      7469: }
                   7470: 
                   7471: sub receipt {
1.474     albertel 7472:     my ($part)=@_;
1.790     albertel 7473:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7474:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7475: }
1.260     ng       7476: 
1.790     albertel 7477: sub whichuser {
                   7478:     my ($passedsymb)=@_;
                   7479:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7480:     if (defined($env{'form.grade_symb'})) {
                   7481: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7482: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7483: 	if (!$allowed &&
                   7484: 	    exists($env{'request.course.sec'}) &&
                   7485: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7486: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7487: 			      '/'.$env{'request.course.sec'});
                   7488: 	}
                   7489: 	if ($allowed) {
                   7490: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7491: 	    $courseid=$tmp_courseid;
                   7492: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7493: 	    ($name)=&get_env_multiple('form.grade_username');
                   7494: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7495: 	}
                   7496:     }
                   7497:     if (!$passedsymb) {
                   7498: 	$symb=&symbread();
                   7499:     } else {
                   7500: 	$symb=$passedsymb;
                   7501:     }
                   7502:     $courseid=$env{'request.course.id'};
                   7503:     $domain=$env{'user.domain'};
                   7504:     $name=$env{'user.name'};
                   7505:     if ($name eq 'public' && $domain eq 'public') {
                   7506: 	if (!defined($env{'form.username'})) {
                   7507: 	    $env{'form.username'}.=time.rand(10000000);
                   7508: 	}
                   7509: 	$name.=$env{'form.username'};
                   7510:     }
                   7511:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7512: 
                   7513: }
                   7514: 
1.36      albertel 7515: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7516: # returns either the contents of the file or 
                   7517: # -1 if the file doesn't exist
1.481     raeburn  7518: #
                   7519: # if the target is a file that was uploaded via DOCS, 
                   7520: # a check will be made to see if a current copy exists on the local server,
                   7521: # if it does this will be served, otherwise a copy will be retrieved from
                   7522: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7523: # the local server.   
1.472     albertel 7524: 
1.36      albertel 7525: sub getfile {
1.538     albertel 7526:     my ($file) = @_;
1.609     banghart 7527:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7528:     &repcopy($file);
                   7529:     return &readfile($file);
                   7530: }
                   7531: 
                   7532: sub repcopy_userfile {
                   7533:     my ($file)=@_;
1.609     banghart 7534:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7535:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7536:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7537: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7538:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7539:     if (-e "$file") {
1.828     www      7540: # we already have a local copy, check it out
1.538     albertel 7541: 	my @fileinfo = stat($file);
1.828     www      7542: 	my $rtncode;
                   7543: 	my $info;
1.538     albertel 7544: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7545: 	if ($lwpresp ne 'ok') {
1.828     www      7546: # there is no such file anymore, even though we had a local copy
1.482     albertel 7547: 	    if ($rtncode eq '404') {
1.538     albertel 7548: 		unlink($file);
1.482     albertel 7549: 	    }
                   7550: 	    return -1;
                   7551: 	}
                   7552: 	if ($info < $fileinfo[9]) {
1.828     www      7553: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7554: 	    return 'ok';
1.828     www      7555: 	} else {
                   7556: # the file is outdated, get rid of it
                   7557: 	    unlink($file);
1.482     albertel 7558: 	}
1.828     www      7559:     }
                   7560: # one way or the other, at this point, we don't have the file
                   7561: # construct the correct path for the file
                   7562:     my @parts = ($cdom,$cnum); 
                   7563:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7564: 	push @parts, split(/\//,$1);
                   7565:     }
                   7566:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7567:     foreach my $part (@parts) {
                   7568: 	$path .= '/'.$part;
                   7569: 	if (!-e $path) {
                   7570: 	    mkdir($path,0770);
1.482     albertel 7571: 	}
                   7572:     }
1.828     www      7573: # now the path exists for sure
                   7574: # get a user agent
                   7575:     my $ua=new LWP::UserAgent;
                   7576:     my $transferfile=$file.'.in.transfer';
                   7577: # FIXME: this should flock
                   7578:     if (-e $transferfile) { return 'ok'; }
                   7579:     my $request;
                   7580:     $uri=~s/^\///;
1.838     albertel 7581:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7582:     my $response=$ua->request($request,$transferfile);
                   7583: # did it work?
                   7584:     if ($response->is_error()) {
                   7585: 	unlink($transferfile);
                   7586: 	&logthis("Userfile repcopy failed for $uri");
                   7587: 	return -1;
                   7588:     }
                   7589: # worked, rename the transfer file
                   7590:     rename($transferfile,$file);
1.607     raeburn  7591:     return 'ok';
1.481     raeburn  7592: }
                   7593: 
1.517     albertel 7594: sub tokenwrapper {
                   7595:     my $uri=shift;
1.552     albertel 7596:     $uri=~s|^http\://([^/]+)||;
                   7597:     $uri=~s|^/||;
1.620     albertel 7598:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7599:     my $token=$1;
1.552     albertel 7600:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7601:     if ($udom && $uname && $file) {
                   7602: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7603:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7604:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7605:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7606:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7607:     } else {
                   7608:         return '/adm/notfound.html';
                   7609:     }
                   7610: }
                   7611: 
1.828     www      7612: # call with reqtype HEAD: get last modification time
                   7613: # call with reqtype GET: get the file contents
                   7614: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7615: #
1.481     raeburn  7616: sub getuploaded {
                   7617:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7618:     $uri=~s/^\///;
1.838     albertel 7619:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7620:     my $ua=new LWP::UserAgent;
                   7621:     my $request=new HTTP::Request($reqtype,$uri);
                   7622:     my $response=$ua->request($request);
                   7623:     $$rtncode = $response->code;
1.482     albertel 7624:     if (! $response->is_success()) {
                   7625: 	return 'failed';
                   7626:     }      
                   7627:     if ($reqtype eq 'HEAD') {
1.486     www      7628: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7629:     } elsif ($reqtype eq 'GET') {
                   7630: 	$$info = $response->content;
1.472     albertel 7631:     }
1.482     albertel 7632:     return 'ok';
1.36      albertel 7633: }
                   7634: 
1.481     raeburn  7635: sub readfile {
                   7636:     my $file = shift;
                   7637:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7638:     my $fh;
                   7639:     open($fh,"<$file");
                   7640:     my $a='';
1.800     albertel 7641:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7642:     return $a;
                   7643: }
                   7644: 
1.36      albertel 7645: sub filelocation {
1.590     banghart 7646:     my ($dir,$file) = @_;
                   7647:     my $location;
                   7648:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7649: 
                   7650:     if ($file =~ m-^/adm/-) {
                   7651: 	$file=~s-^/adm/wrapper/-/-;
                   7652: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7653:     }
1.882     albertel 7654: 
1.590     banghart 7655:     if ($file=~m:^/~:) { # is a contruction space reference
                   7656:         $location = $file;
                   7657:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7658:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7659: 	# is a correct contruction space reference
                   7660:         $location = $file;
1.609     banghart 7661:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7662:         my ($udom,$uname,$filename)=
1.811     albertel 7663:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7664:         my $home=&homeserver($uname,$udom);
                   7665:         my $is_me=0;
                   7666:         my @ids=&current_machine_ids();
                   7667:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7668:         if ($is_me) {
1.740     www      7669:   	    $location=&propath($udom,$uname).
1.590     banghart 7670:   	      '/userfiles/'.$filename;
                   7671:         } else {
                   7672:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7673:   	      $udom.'/'.$uname.'/'.$filename;
                   7674:         }
1.882     albertel 7675:     } elsif ($file =~ m-^/adm/-) {
                   7676: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7677:     } else {
                   7678:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7679:         $file=~s:^/res/:/:;
                   7680:         if ( !( $file =~ m:^/:) ) {
                   7681:             $location = $dir. '/'.$file;
                   7682:         } else {
                   7683:             $location = '/home/httpd/html/res'.$file;
                   7684:         }
1.59      albertel 7685:     }
1.590     banghart 7686:     $location=~s://+:/:g; # remove duplicate /
                   7687:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7688:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7689:     return $location;
1.46      www      7690: }
1.36      albertel 7691: 
1.46      www      7692: sub hreflocation {
                   7693:     my ($dir,$file)=@_;
1.460     albertel 7694:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7695: 	$file=filelocation($dir,$file);
1.700     albertel 7696:     } elsif ($file=~m-^/adm/-) {
                   7697: 	$file=~s-^/adm/wrapper/-/-;
                   7698: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7699:     }
                   7700:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7701: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7702:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7703: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7704:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7705: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7706: 	    -/uploaded/$1/$2/-x;
1.46      www      7707:     }
1.462     albertel 7708:     return $file;
1.465     albertel 7709: }
                   7710: 
                   7711: sub current_machine_domains {
1.853     albertel 7712:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7713: }
                   7714: 
                   7715: sub machine_domains {
                   7716:     my ($hostname) = @_;
1.465     albertel 7717:     my @domains;
1.838     albertel 7718:     my %hostname = &all_hostnames();
1.465     albertel 7719:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7720: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7721: 	if ($hostname eq $name) {
1.844     albertel 7722: 	    push(@domains,&host_domain($id));
1.465     albertel 7723: 	}
                   7724:     }
                   7725:     return @domains;
                   7726: }
                   7727: 
                   7728: sub current_machine_ids {
1.853     albertel 7729:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7730: }
                   7731: 
                   7732: sub machine_ids {
                   7733:     my ($hostname) = @_;
                   7734:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7735:     my @ids;
1.888     albertel 7736:     my %name_to_host = &all_names();
1.889     albertel 7737:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7738: 	return @{ $name_to_host{$hostname} };
                   7739:     }
                   7740:     return;
1.31      www      7741: }
                   7742: 
1.824     raeburn  7743: sub additional_machine_domains {
                   7744:     my @domains;
                   7745:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7746:     while( my $line = <$fh>) {
                   7747:         $line =~ s/\s//g;
                   7748:         push(@domains,$line);
                   7749:     }
                   7750:     return @domains;
                   7751: }
                   7752: 
                   7753: sub default_login_domain {
                   7754:     my $domain = $perlvar{'lonDefDomain'};
                   7755:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7756:     foreach my $posdom (&current_machine_domains(),
                   7757:                         &additional_machine_domains()) {
                   7758:         if (lc($posdom) eq lc($testdomain)) {
                   7759:             $domain=$posdom;
                   7760:             last;
                   7761:         }
                   7762:     }
                   7763:     return $domain;
                   7764: }
                   7765: 
1.31      www      7766: # ------------------------------------------------------------- Declutters URLs
                   7767: 
                   7768: sub declutter {
                   7769:     my $thisfn=shift;
1.569     albertel 7770:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7771:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7772:     $thisfn=~s/^\///;
1.697     albertel 7773:     $thisfn=~s|^adm/wrapper/||;
                   7774:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7775:     $thisfn=~s/^res\///;
1.235     www      7776:     $thisfn=~s/\?.+$//;
1.268     www      7777:     return $thisfn;
                   7778: }
                   7779: 
                   7780: # ------------------------------------------------------------- Clutter up URLs
                   7781: 
                   7782: sub clutter {
                   7783:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7784:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7785: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7786:        $thisfn='/res'.$thisfn; 
                   7787:     }
1.694     albertel 7788:     if ($thisfn !~m|/adm|) {
1.695     albertel 7789: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7790: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7791: 	} else {
                   7792: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7793: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7794: 	    if ($embstyle eq 'ssi'
                   7795: 		|| ($embstyle eq 'hdn')
                   7796: 		|| ($embstyle eq 'rat')
                   7797: 		|| ($embstyle eq 'prv')
                   7798: 		|| ($embstyle eq 'ign')) {
                   7799: 		#do nothing with these
                   7800: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7801: 		|| ($embstyle eq 'emb')
                   7802: 		|| ($embstyle eq 'wrp')) {
                   7803: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7804: 	    } elsif ($embstyle eq 'unk'
                   7805: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7806: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7807: 	    } else {
1.718     www      7808: #		&logthis("Got a blank emb style");
1.695     albertel 7809: 	    }
1.694     albertel 7810: 	}
                   7811:     }
1.31      www      7812:     return $thisfn;
1.12      www      7813: }
                   7814: 
1.787     albertel 7815: sub clutter_with_no_wrapper {
                   7816:     my $uri = &clutter(shift);
                   7817:     if ($uri =~ m-^/adm/-) {
                   7818: 	$uri =~ s-^/adm/wrapper/-/-;
                   7819: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7820:     }
                   7821:     return $uri;
                   7822: }
                   7823: 
1.557     albertel 7824: sub freeze_escape {
                   7825:     my ($value)=@_;
                   7826:     if (ref($value)) {
                   7827: 	$value=&nfreeze($value);
                   7828: 	return '__FROZEN__'.&escape($value);
                   7829:     }
                   7830:     return &escape($value);
                   7831: }
                   7832: 
1.11      www      7833: 
1.557     albertel 7834: sub thaw_unescape {
                   7835:     my ($value)=@_;
                   7836:     if ($value =~ /^__FROZEN__/) {
                   7837: 	substr($value,0,10,undef);
                   7838: 	$value=&unescape($value);
                   7839: 	return &thaw($value);
                   7840:     }
                   7841:     return &unescape($value);
                   7842: }
                   7843: 
1.436     albertel 7844: sub correct_line_ends {
                   7845:     my ($result)=@_;
                   7846:     $$result =~s/\r\n/\n/mg;
                   7847:     $$result =~s/\r/\n/mg;
1.415     albertel 7848: }
1.1       albertel 7849: # ================================================================ Main Program
                   7850: 
1.184     www      7851: sub goodbye {
1.204     albertel 7852:    &logthis("Starting Shut down");
1.443     albertel 7853: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7854:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7855: #converted
1.599     albertel 7856: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7857:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7858: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7859: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7860: #1.1 only
1.870     albertel 7861: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7862: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7863: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7864: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7865:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7866:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7867:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7868:    &flushcourselogs();
                   7869:    &logthis("Shutting down");
                   7870: }
                   7871: 
1.852     albertel 7872: sub get_dns {
1.869     albertel 7873:     my ($url,$func,$ignore_cache) = @_;
                   7874:     if (!$ignore_cache) {
                   7875: 	my ($content,$cached)=
                   7876: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7877: 	if ($cached) {
                   7878: 	    &$func($content);
                   7879: 	    return;
                   7880: 	}
                   7881:     }
                   7882: 
                   7883:     my %alldns;
1.852     albertel 7884:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7885:     foreach my $dns (<$config>) {
                   7886: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7887: 	$alldns{$1} = 1;
                   7888:     }
                   7889:     while (%alldns) {
                   7890: 	my ($dns) = keys(%alldns);
                   7891: 	delete($alldns{$dns});
1.852     albertel 7892: 	my $ua=new LWP::UserAgent;
                   7893: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7894: 	my $response=$ua->request($request);
                   7895: 	next if ($response->is_error());
                   7896: 	my @content = split("\n",$response->content);
1.869     albertel 7897: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7898: 	&$func(\@content);
1.869     albertel 7899: 	return;
1.852     albertel 7900:     }
                   7901:     close($config);
1.871     albertel 7902:     my $which = (split('/',$url))[3];
                   7903:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7904:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7905:     my @content = <$config>;
                   7906:     &$func(\@content);
                   7907:     return;
1.852     albertel 7908: }
1.327     albertel 7909: # ------------------------------------------------------------ Read domain file
                   7910: {
1.852     albertel 7911:     my $loaded;
1.846     albertel 7912:     my %domain;
                   7913: 
1.852     albertel 7914:     sub parse_domain_tab {
                   7915: 	my ($lines) = @_;
                   7916: 	foreach my $line (@$lines) {
                   7917: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7918: 
1.846     albertel 7919: 	    chomp($line);
1.852     albertel 7920: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7921: 	    my %this_domain;
                   7922: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7923: 			       'lang_def', 'city', 'longi', 'lati',
                   7924: 			       'primary') {
                   7925: 		$this_domain{$field} = shift(@elements);
                   7926: 	    }
                   7927: 	    $domain{$name} = \%this_domain;
1.852     albertel 7928: 	}
                   7929:     }
1.864     albertel 7930: 
                   7931:     sub reset_domain_info {
                   7932: 	undef($loaded);
                   7933: 	undef(%domain);
                   7934:     }
                   7935: 
1.852     albertel 7936:     sub load_domain_tab {
1.869     albertel 7937: 	my ($ignore_cache) = @_;
                   7938: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7939: 	my $fh;
                   7940: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7941: 	    my @lines = <$fh>;
                   7942: 	    &parse_domain_tab(\@lines);
1.448     albertel 7943: 	}
1.852     albertel 7944: 	close($fh);
                   7945: 	$loaded = 1;
1.327     albertel 7946:     }
1.846     albertel 7947: 
                   7948:     sub domain {
1.852     albertel 7949: 	&load_domain_tab() if (!$loaded);
                   7950: 
1.846     albertel 7951: 	my ($name,$what) = @_;
                   7952: 	return if ( !exists($domain{$name}) );
                   7953: 
                   7954: 	if (!$what) {
                   7955: 	    return $domain{$name}{'description'};
                   7956: 	}
                   7957: 	return $domain{$name}{$what};
                   7958:     }
1.327     albertel 7959: }
                   7960: 
                   7961: 
1.1       albertel 7962: # ------------------------------------------------------------- Read hosts file
                   7963: {
1.838     albertel 7964:     my %hostname;
1.844     albertel 7965:     my %hostdom;
1.845     albertel 7966:     my %libserv;
1.852     albertel 7967:     my $loaded;
1.888     albertel 7968:     my %name_to_host;
1.852     albertel 7969: 
                   7970:     sub parse_hosts_tab {
                   7971: 	my ($file) = @_;
                   7972: 	foreach my $configline (@$file) {
                   7973: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7974: 	    next if ($configline =~ /^\^/);
                   7975: 	    chomp($configline);
                   7976: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7977: 	    $name=~s/\s//g;
                   7978: 	    if ($id && $domain && $role && $name) {
                   7979: 		$hostname{$id}=$name;
1.888     albertel 7980: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 7981: 		$hostdom{$id}=$domain;
                   7982: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   7983: 	    }
                   7984: 	}
                   7985:     }
1.864     albertel 7986:     
                   7987:     sub reset_hosts_info {
1.897     albertel 7988: 	&purge_remembered();
1.864     albertel 7989: 	&reset_domain_info();
                   7990: 	&reset_hosts_ip_info();
1.892     albertel 7991: 	undef(%name_to_host);
1.864     albertel 7992: 	undef(%hostname);
                   7993: 	undef(%hostdom);
                   7994: 	undef(%libserv);
                   7995: 	undef($loaded);
                   7996:     }
1.1       albertel 7997: 
1.852     albertel 7998:     sub load_hosts_tab {
1.869     albertel 7999: 	my ($ignore_cache) = @_;
                   8000: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8001: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8002: 	my @config = <$config>;
                   8003: 	&parse_hosts_tab(\@config);
                   8004: 	close($config);
                   8005: 	$loaded=1;
1.1       albertel 8006:     }
1.852     albertel 8007: 
1.838     albertel 8008:     sub hostname {
1.852     albertel 8009: 	&load_hosts_tab() if (!$loaded);
                   8010: 
1.838     albertel 8011: 	my ($lonid) = @_;
                   8012: 	return $hostname{$lonid};
                   8013:     }
1.845     albertel 8014: 
1.838     albertel 8015:     sub all_hostnames {
1.852     albertel 8016: 	&load_hosts_tab() if (!$loaded);
                   8017: 
1.838     albertel 8018: 	return %hostname;
                   8019:     }
1.845     albertel 8020: 
1.888     albertel 8021:     sub all_names {
                   8022: 	&load_hosts_tab() if (!$loaded);
                   8023: 
                   8024: 	return %name_to_host;
                   8025:     }
                   8026: 
1.845     albertel 8027:     sub is_library {
1.852     albertel 8028: 	&load_hosts_tab() if (!$loaded);
                   8029: 
1.845     albertel 8030: 	return exists($libserv{$_[0]});
                   8031:     }
                   8032: 
                   8033:     sub all_library {
1.852     albertel 8034: 	&load_hosts_tab() if (!$loaded);
                   8035: 
1.845     albertel 8036: 	return %libserv;
                   8037:     }
                   8038: 
1.841     albertel 8039:     sub get_servers {
1.852     albertel 8040: 	&load_hosts_tab() if (!$loaded);
                   8041: 
1.841     albertel 8042: 	my ($domain,$type) = @_;
                   8043: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8044: 	                                          : %hostname;
                   8045: 	my %result;
1.842     albertel 8046: 	if (ref($domain) eq 'ARRAY') {
                   8047: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8048: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8049: 		    $result{$host} = $hostname;
                   8050: 		}
                   8051: 	    }
                   8052: 	} else {
                   8053: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8054: 		if ($hostdom{$host} eq $domain) {
                   8055: 		    $result{$host} = $hostname;
                   8056: 		}
1.841     albertel 8057: 	    }
                   8058: 	}
                   8059: 	return %result;
                   8060:     }
1.845     albertel 8061: 
1.844     albertel 8062:     sub host_domain {
1.852     albertel 8063: 	&load_hosts_tab() if (!$loaded);
                   8064: 
1.844     albertel 8065: 	my ($lonid) = @_;
                   8066: 	return $hostdom{$lonid};
                   8067:     }
                   8068: 
1.841     albertel 8069:     sub all_domains {
1.852     albertel 8070: 	&load_hosts_tab() if (!$loaded);
                   8071: 
1.841     albertel 8072: 	my %seen;
                   8073: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8074: 	return @uniq;
                   8075:     }
1.1       albertel 8076: }
                   8077: 
1.847     albertel 8078: { 
                   8079:     my %iphost;
1.856     albertel 8080:     my %name_to_ip;
                   8081:     my %lonid_to_ip;
1.869     albertel 8082: 
1.847     albertel 8083:     sub get_hosts_from_ip {
                   8084: 	my ($ip) = @_;
                   8085: 	my %iphosts = &get_iphost();
                   8086: 	if (ref($iphosts{$ip})) {
                   8087: 	    return @{$iphosts{$ip}};
                   8088: 	}
                   8089: 	return;
1.839     albertel 8090:     }
1.864     albertel 8091:     
                   8092:     sub reset_hosts_ip_info {
                   8093: 	undef(%iphost);
                   8094: 	undef(%name_to_ip);
                   8095: 	undef(%lonid_to_ip);
                   8096:     }
1.856     albertel 8097: 
                   8098:     sub get_host_ip {
                   8099: 	my ($lonid) = @_;
                   8100: 	if (exists($lonid_to_ip{$lonid})) {
                   8101: 	    return $lonid_to_ip{$lonid};
                   8102: 	}
                   8103: 	my $name=&hostname($lonid);
                   8104:    	my $ip = gethostbyname($name);
                   8105: 	return if (!$ip || length($ip) ne 4);
                   8106: 	$ip=inet_ntoa($ip);
                   8107: 	$name_to_ip{$name}   = $ip;
                   8108: 	$lonid_to_ip{$lonid} = $ip;
                   8109: 	return $ip;
                   8110:     }
1.847     albertel 8111:     
                   8112:     sub get_iphost {
1.869     albertel 8113: 	my ($ignore_cache) = @_;
1.894     albertel 8114: 
1.869     albertel 8115: 	if (!$ignore_cache) {
                   8116: 	    if (%iphost) {
                   8117: 		return %iphost;
                   8118: 	    }
                   8119: 	    my ($ip_info,$cached)=
                   8120: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8121: 	    if ($cached) {
                   8122: 		%iphost      = %{$ip_info->[0]};
                   8123: 		%name_to_ip  = %{$ip_info->[1]};
                   8124: 		%lonid_to_ip = %{$ip_info->[2]};
                   8125: 		return %iphost;
                   8126: 	    }
                   8127: 	}
1.894     albertel 8128: 
                   8129: 	# get yesterday's info for fallback
                   8130: 	my %old_name_to_ip;
                   8131: 	my ($ip_info,$cached)=
                   8132: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8133: 	if ($cached) {
                   8134: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8135: 	}
                   8136: 
1.888     albertel 8137: 	my %name_to_host = &all_names();
                   8138: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8139: 	    my $ip;
                   8140: 	    if (!exists($name_to_ip{$name})) {
                   8141: 		$ip = gethostbyname($name);
                   8142: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8143: 		    if (defined($old_name_to_ip{$name})) {
                   8144: 			$ip = $old_name_to_ip{$name};
                   8145: 			&logthis("Can't find $name defaulting to old $ip");
                   8146: 		    } else {
                   8147: 			&logthis("Name $name no IP found");
                   8148: 			next;
                   8149: 		    }
                   8150: 		} else {
                   8151: 		    $ip=inet_ntoa($ip);
1.847     albertel 8152: 		}
                   8153: 		$name_to_ip{$name} = $ip;
                   8154: 	    } else {
                   8155: 		$ip = $name_to_ip{$name};
1.653     albertel 8156: 	    }
1.888     albertel 8157: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8158: 		$lonid_to_ip{$id} = $ip;
                   8159: 	    }
                   8160: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8161: 	}
1.869     albertel 8162: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8163: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8164: 				      48*60*60);
1.869     albertel 8165: 
1.847     albertel 8166: 	return %iphost;
1.598     albertel 8167:     }
                   8168: }
                   8169: 
1.862     albertel 8170: BEGIN {
                   8171: 
                   8172: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8173:     unless ($readit) {
                   8174: {
                   8175:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8176:     %perlvar = (%perlvar,%{$configvars});
                   8177: }
                   8178: 
                   8179: 
1.1       albertel 8180: # ------------------------------------------------------ Read spare server file
                   8181: {
1.448     albertel 8182:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8183: 
                   8184:     while (my $configline=<$config>) {
                   8185:        chomp($configline);
1.284     matthew  8186:        if ($configline) {
1.784     albertel 8187: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8188: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8189: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8190:        }
                   8191:     }
1.448     albertel 8192:     close($config);
1.1       albertel 8193: }
1.11      www      8194: # ------------------------------------------------------------ Read permissions
                   8195: {
1.448     albertel 8196:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8197: 
                   8198:     while (my $configline=<$config>) {
1.448     albertel 8199: 	chomp($configline);
                   8200: 	if ($configline) {
                   8201: 	    my ($role,$perm)=split(/ /,$configline);
                   8202: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8203: 	}
1.11      www      8204:     }
1.448     albertel 8205:     close($config);
1.11      www      8206: }
                   8207: 
                   8208: # -------------------------------------------- Read plain texts for permissions
                   8209: {
1.448     albertel 8210:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8211: 
                   8212:     while (my $configline=<$config>) {
1.448     albertel 8213: 	chomp($configline);
                   8214: 	if ($configline) {
1.742     raeburn  8215: 	    my ($short,@plain)=split(/:/,$configline);
                   8216:             %{$prp{$short}} = ();
                   8217: 	    if (@plain > 0) {
                   8218:                 $prp{$short}{'std'} = $plain[0];
                   8219:                 for (my $i=1; $i<@plain; $i++) {
                   8220:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8221:                 }
                   8222:             }
1.448     albertel 8223: 	}
1.135     www      8224:     }
1.448     albertel 8225:     close($config);
1.135     www      8226: }
                   8227: 
                   8228: # ---------------------------------------------------------- Read package table
                   8229: {
1.448     albertel 8230:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8231: 
                   8232:     while (my $configline=<$config>) {
1.483     albertel 8233: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8234: 	chomp($configline);
                   8235: 	my ($short,$plain)=split(/:/,$configline);
                   8236: 	my ($pack,$name)=split(/\&/,$short);
                   8237: 	if ($plain ne '') {
                   8238: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8239: 	    $packagetab{$short}=$plain; 
                   8240: 	}
1.11      www      8241:     }
1.448     albertel 8242:     close($config);
1.329     matthew  8243: }
                   8244: 
                   8245: # ------------- set up temporary directory
                   8246: {
                   8247:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8248: 
1.11      www      8249: }
                   8250: 
1.794     albertel 8251: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8252: 				'compress_threshold'=> 20_000,
                   8253:  			        });
1.185     www      8254: 
1.281     www      8255: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8256: $dumpcount=0;
1.22      www      8257: 
1.163     harris41 8258: &logtouch();
1.672     albertel 8259: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8260: $readit=1;
1.564     albertel 8261:     {
                   8262: 	use integer;
                   8263: 	my $test=(2**32)+1;
1.568     albertel 8264: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8265: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8266:     }
1.195     www      8267: }
1.1       albertel 8268: }
1.179     www      8269: 
1.1       albertel 8270: 1;
1.191     harris41 8271: __END__
                   8272: 
1.243     albertel 8273: =pod
                   8274: 
1.191     harris41 8275: =head1 NAME
                   8276: 
1.243     albertel 8277: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8278: 
                   8279: =head1 SYNOPSIS
                   8280: 
1.243     albertel 8281: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8282: 
                   8283:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8284: 
1.243     albertel 8285: Common parameters:
                   8286: 
                   8287: =over 4
                   8288: 
                   8289: =item *
                   8290: 
                   8291: $uname : an internal username (if $cname expecting a course Id specifically)
                   8292: 
                   8293: =item *
                   8294: 
                   8295: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8296: 
                   8297: =item *
                   8298: 
                   8299: $symb : a resource instance identifier
                   8300: 
                   8301: =item *
                   8302: 
                   8303: $namespace : the name of a .db file that contains the data needed or
                   8304: being set.
                   8305: 
                   8306: =back
                   8307: 
1.394     bowersj2 8308: =head1 OVERVIEW
1.191     harris41 8309: 
1.394     bowersj2 8310: lonnet provides subroutines which interact with the
                   8311: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8312: about classes, users, and resources.
1.243     albertel 8313: 
                   8314: For many of these objects you can also use this to store data about
                   8315: them or modify them in various ways.
1.191     harris41 8316: 
1.394     bowersj2 8317: =head2 Symbs
1.191     harris41 8318: 
1.394     bowersj2 8319: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8320: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8321: map, the resource number of the resource in the map, and the URL of
                   8322: the resource itself. The latter is somewhat redundant, but might help
                   8323: if maps change.
                   8324: 
                   8325: An example is
                   8326: 
                   8327:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8328: 
                   8329: The respective map entry is
                   8330: 
                   8331:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8332:   title="Problem 2">
                   8333:  </resource>
                   8334: 
                   8335: Symbs are used by the random number generator, as well as to store and
                   8336: restore data specific to a certain instance of for example a problem.
                   8337: 
                   8338: =head2 Storing And Retrieving Data
                   8339: 
                   8340: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8341: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8342: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8343: is is the non-critical message twin of cstore. These functions are for
                   8344: handlers to store a perl hash to a user's permanent data space in an
                   8345: easy manner, and to retrieve it again on another call. It is expected
                   8346: that a handler would use this once at the beginning to retrieve data,
                   8347: and then again once at the end to send only the new data back.
                   8348: 
                   8349: The data is stored in the user's data directory on the user's
                   8350: homeserver under the ID of the course.
                   8351: 
                   8352: The hash that is returned by restore will have all of the previous
                   8353: value for all of the elements of the hash.
                   8354: 
                   8355: Example:
                   8356: 
                   8357:  #creating a hash
                   8358:  my %hash;
                   8359:  $hash{'foo'}='bar';
                   8360: 
                   8361:  #storing it
                   8362:  &Apache::lonnet::cstore(\%hash);
                   8363: 
                   8364:  #changing a value
                   8365:  $hash{'foo'}='notbar';
                   8366: 
                   8367:  #adding a new value
                   8368:  $hash{'bar'}='foo';
                   8369:  &Apache::lonnet::cstore(\%hash);
                   8370: 
                   8371:  #retrieving the hash
                   8372:  my %history=&Apache::lonnet::restore();
                   8373: 
                   8374:  #print the hash
                   8375:  foreach my $key (sort(keys(%history))) {
                   8376:    print("\%history{$key} = $history{$key}");
                   8377:  }
                   8378: 
                   8379: Will print out:
1.191     harris41 8380: 
1.394     bowersj2 8381:  %history{1:foo} = bar
                   8382:  %history{1:keys} = foo:timestamp
                   8383:  %history{1:timestamp} = 990455579
                   8384:  %history{2:bar} = foo
                   8385:  %history{2:foo} = notbar
                   8386:  %history{2:keys} = foo:bar:timestamp
                   8387:  %history{2:timestamp} = 990455580
                   8388:  %history{bar} = foo
                   8389:  %history{foo} = notbar
                   8390:  %history{timestamp} = 990455580
                   8391:  %history{version} = 2
                   8392: 
                   8393: Note that the special hash entries C<keys>, C<version> and
                   8394: C<timestamp> were added to the hash. C<version> will be equal to the
                   8395: total number of versions of the data that have been stored. The
                   8396: C<timestamp> attribute will be the UNIX time the hash was
                   8397: stored. C<keys> is available in every historical section to list which
                   8398: keys were added or changed at a specific historical revision of a
                   8399: hash.
                   8400: 
                   8401: B<Warning>: do not store the hash that restore returns directly. This
                   8402: will cause a mess since it will restore the historical keys as if the
                   8403: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8404: 
1.394     bowersj2 8405: Calling convention:
1.191     harris41 8406: 
1.394     bowersj2 8407:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8408:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8409: 
1.394     bowersj2 8410: For more detailed information, see lonnet specific documentation.
1.191     harris41 8411: 
1.394     bowersj2 8412: =head1 RETURN MESSAGES
1.191     harris41 8413: 
1.394     bowersj2 8414: =over 4
1.191     harris41 8415: 
1.394     bowersj2 8416: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8417: 
1.394     bowersj2 8418: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8419: when the connection is brought back up
1.191     harris41 8420: 
1.394     bowersj2 8421: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8422: for later delivery
1.191     harris41 8423: 
1.394     bowersj2 8424: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8425: 
1.394     bowersj2 8426: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8427: that was requested
1.191     harris41 8428: 
1.243     albertel 8429: =back
1.191     harris41 8430: 
1.243     albertel 8431: =head1 PUBLIC SUBROUTINES
1.191     harris41 8432: 
1.243     albertel 8433: =head2 Session Environment Functions
1.191     harris41 8434: 
1.243     albertel 8435: =over 4
1.191     harris41 8436: 
1.394     bowersj2 8437: =item * 
                   8438: X<appenv()>
                   8439: B<appenv(%hash)>: the value of %hash is written to
                   8440: the user envirnoment file, and will be restored for each access this
1.620     albertel 8441: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8442: process
1.191     harris41 8443: 
                   8444: =item *
1.394     bowersj2 8445: X<delenv()>
                   8446: B<delenv($regexp)>: removes all items from the session
                   8447: environment file that matches the regular expression in $regexp. The
1.620     albertel 8448: values are also delted from the current processes %env.
1.191     harris41 8449: 
1.795     albertel 8450: =item * get_env_multiple($name) 
                   8451: 
                   8452: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8453: values may be defined and end up as an array ref.
                   8454: 
                   8455: returns an array of values
                   8456: 
1.243     albertel 8457: =back
                   8458: 
                   8459: =head2 User Information
1.191     harris41 8460: 
1.243     albertel 8461: =over 4
1.191     harris41 8462: 
                   8463: =item *
1.394     bowersj2 8464: X<queryauthenticate()>
                   8465: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8466: authentication scheme
                   8467: 
                   8468: =item *
1.394     bowersj2 8469: X<authenticate()>
                   8470: B<authenticate($uname,$upass,$udom)>: try to
                   8471: authenticate user from domain's lib servers (first use the current
                   8472: one). C<$upass> should be the users password.
1.191     harris41 8473: 
                   8474: =item *
1.394     bowersj2 8475: X<homeserver()>
                   8476: B<homeserver($uname,$udom)>: find the server which has
                   8477: the user's directory and files (there must be only one), this caches
                   8478: the answer, and also caches if there is a borken connection.
1.191     harris41 8479: 
                   8480: =item *
1.394     bowersj2 8481: X<idget()>
                   8482: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8483: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8484: username, and only 1 username per ID in a specific domain) (returns
                   8485: hash: id=>name,id=>name)
1.191     harris41 8486: 
                   8487: =item *
1.394     bowersj2 8488: X<idrget()>
                   8489: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8490: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8491: 
                   8492: =item *
1.394     bowersj2 8493: X<idput()>
                   8494: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8495: 
                   8496: =item *
1.394     bowersj2 8497: X<rolesinit()>
                   8498: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8499: 
                   8500: =item *
1.551     albertel 8501: X<getsection()>
                   8502: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8503: course $cname, return section name/number or '' for "not in course"
                   8504: and '-1' for "no section"
                   8505: 
                   8506: =item *
1.394     bowersj2 8507: X<userenvironment()>
                   8508: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8509: passed in @what from the requested user's environment, returns a hash
                   8510: 
1.858     raeburn  8511: =item * 
                   8512: X<userlog_query()>
1.859     albertel 8513: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8514: activity.log file. %filters defines filters applied when parsing the
                   8515: log file. These can be start or end timestamps, or the type of action
                   8516: - log to look for Login or Logout events, check for Checkin or
                   8517: Checkout, role for role selection. The response is in the form
                   8518: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8519: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8520: 
1.243     albertel 8521: =back
                   8522: 
                   8523: =head2 User Roles
                   8524: 
                   8525: =over 4
                   8526: 
                   8527: =item *
                   8528: 
1.810     raeburn  8529: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8530:  F: full access
                   8531:  U,I,K: authentication modes (cxx only)
                   8532:  '': forbidden
                   8533:  1: user needs to choose course
                   8534:  2: browse allowed
1.766     albertel 8535:  A: passphrase authentication needed
1.243     albertel 8536: 
                   8537: =item *
                   8538: 
                   8539: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8540: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8541: and course level
                   8542: 
                   8543: =item *
                   8544: 
                   8545: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8546: explanation of a user role term
                   8547: 
1.832     raeburn  8548: =item *
                   8549: 
1.858     raeburn  8550: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8551: All arguments are optional. Returns a hash of a roles, either for
                   8552: co-author/assistant author roles for a user's Construction Space
                   8553: (default), or if $context is 'user', roles for the user himself,
                   8554: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8555: and value is set to colon-separated start and end times for the role.
                   8556: If no username and domain are specified, will default to current
                   8557: user/domain. Types, roles, and roledoms are references to arrays,
                   8558: of role statuses (active, future or previous), roles 
                   8559: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8560: to restrict the list of roles reported. If no array ref is 
                   8561: provided for types, will default to return only active roles.
1.834     albertel 8562: 
1.243     albertel 8563: =back
                   8564: 
                   8565: =head2 User Modification
                   8566: 
                   8567: =over 4
                   8568: 
                   8569: =item *
                   8570: 
                   8571: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8572: user for the level given by URL.  Optional start and end dates (leave empty
                   8573: string or zero for "no date")
1.191     harris41 8574: 
                   8575: =item *
                   8576: 
1.243     albertel 8577: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8578: change a users, password, possible return values are: ok,
                   8579: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8580: refused
1.191     harris41 8581: 
                   8582: =item *
                   8583: 
1.243     albertel 8584: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8585: 
                   8586: =item *
                   8587: 
1.243     albertel 8588: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8589: modify user
1.191     harris41 8590: 
                   8591: =item *
                   8592: 
1.286     matthew  8593: modifystudent
                   8594: 
                   8595: modify a students enrollment and identification information.
                   8596: The course id is resolved based on the current users environment.  
                   8597: This means the envoking user must be a course coordinator or otherwise
                   8598: associated with a course.
                   8599: 
1.297     matthew  8600: This call is essentially a wrapper for lonnet::modifyuser and
                   8601: lonnet::modify_student_enrollment
1.286     matthew  8602: 
                   8603: Inputs: 
                   8604: 
                   8605: =over 4
                   8606: 
                   8607: =item B<$udom> Students loncapa domain
                   8608: 
                   8609: =item B<$uname> Students loncapa login name
                   8610: 
                   8611: =item B<$uid> Students id/student number
                   8612: 
                   8613: =item B<$umode> Students authentication mode
                   8614: 
                   8615: =item B<$upass> Students password
                   8616: 
                   8617: =item B<$first> Students first name
                   8618: 
                   8619: =item B<$middle> Students middle name
                   8620: 
                   8621: =item B<$last> Students last name
                   8622: 
                   8623: =item B<$gene> Students generation
                   8624: 
                   8625: =item B<$usec> Students section in course
                   8626: 
                   8627: =item B<$end> Unix time of the roles expiration
                   8628: 
                   8629: =item B<$start> Unix time of the roles start date
                   8630: 
                   8631: =item B<$forceid> If defined, allow $uid to be changed
                   8632: 
                   8633: =item B<$desiredhome> server to use as home server for student
                   8634: 
                   8635: =back
1.297     matthew  8636: 
                   8637: =item *
                   8638: 
                   8639: modify_student_enrollment
                   8640: 
                   8641: Change a students enrollment status in a class.  The environment variable
                   8642: 'role.request.course' must be defined for this function to proceed.
                   8643: 
                   8644: Inputs:
                   8645: 
                   8646: =over 4
                   8647: 
                   8648: =item $udom, students domain
                   8649: 
                   8650: =item $uname, students name
                   8651: 
                   8652: =item $uid, students user id
                   8653: 
                   8654: =item $first, students first name
                   8655: 
                   8656: =item $middle
                   8657: 
                   8658: =item $last
                   8659: 
                   8660: =item $gene
                   8661: 
                   8662: =item $usec
                   8663: 
                   8664: =item $end
                   8665: 
                   8666: =item $start
                   8667: 
                   8668: =back
                   8669: 
1.191     harris41 8670: 
                   8671: =item *
                   8672: 
1.243     albertel 8673: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8674: custom role; give a custom role to a user for the level given by URL.  Specify
                   8675: name and domain of role author, and role name
1.191     harris41 8676: 
                   8677: =item *
                   8678: 
1.243     albertel 8679: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8680: 
                   8681: =item *
                   8682: 
1.243     albertel 8683: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8684: 
                   8685: =back
                   8686: 
                   8687: =head2 Course Infomation
                   8688: 
                   8689: =over 4
1.191     harris41 8690: 
                   8691: =item *
                   8692: 
1.631     albertel 8693: coursedescription($courseid) : returns a hash of information about the
                   8694: specified course id, including all environment settings for the
                   8695: course, the description of the course will be in the hash under the
                   8696: key 'description'
1.191     harris41 8697: 
                   8698: =item *
                   8699: 
1.624     albertel 8700: resdata($name,$domain,$type,@which) : request for current parameter
                   8701: setting for a specific $type, where $type is either 'course' or 'user',
                   8702: @what should be a list of parameters to ask about. This routine caches
                   8703: answers for 5 minutes.
1.243     albertel 8704: 
1.877     foxr     8705: =item *
                   8706: 
                   8707: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8708: data base, returning a hash that is keyed by the resource name and has
                   8709: values that are the resource value.  I believe that the timestamps and
                   8710: versions are also returned.
                   8711: 
                   8712: 
1.243     albertel 8713: =back
                   8714: 
                   8715: =head2 Course Modification
                   8716: 
                   8717: =over 4
1.191     harris41 8718: 
                   8719: =item *
                   8720: 
1.243     albertel 8721: writecoursepref($courseid,%prefs) : write preferences (environment
                   8722: database) for a course
1.191     harris41 8723: 
                   8724: =item *
                   8725: 
1.243     albertel 8726: createcourse($udom,$description,$url) : make/modify course
                   8727: 
                   8728: =back
                   8729: 
                   8730: =head2 Resource Subroutines
                   8731: 
                   8732: =over 4
1.191     harris41 8733: 
                   8734: =item *
                   8735: 
1.243     albertel 8736: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8737: 
                   8738: =item *
                   8739: 
1.243     albertel 8740: repcopy($filename) : subscribes to the requested file, and attempts to
                   8741: replicate from the owning library server, Might return
1.607     raeburn  8742: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8743: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8744: resource. Expects the local filesystem pathname
                   8745: (/home/httpd/html/res/....)
                   8746: 
                   8747: =back
                   8748: 
                   8749: =head2 Resource Information
                   8750: 
                   8751: =over 4
1.191     harris41 8752: 
                   8753: =item *
                   8754: 
1.243     albertel 8755: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8756: a vairety of different possible values, $varname should be a request
                   8757: string, and the other parameters can be used to specify who and what
                   8758: one is asking about.
                   8759: 
                   8760: Possible values for $varname are environment.lastname (or other item
                   8761: from the envirnment hash), user.name (or someother aspect about the
                   8762: user), resource.0.maxtries (or some other part and parameter of a
                   8763: resource)
1.204     albertel 8764: 
                   8765: =item *
                   8766: 
1.243     albertel 8767: directcondval($number) : get current value of a condition; reads from a state
                   8768: string
1.204     albertel 8769: 
                   8770: =item *
                   8771: 
1.243     albertel 8772: condval($condidx) : value of condition index based on state
1.204     albertel 8773: 
                   8774: =item *
                   8775: 
1.243     albertel 8776: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8777: resource's metadata, $what should be either a specific key, or either
                   8778: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8779: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8780: 
                   8781: this function automatically caches all requests
1.191     harris41 8782: 
                   8783: =item *
                   8784: 
1.243     albertel 8785: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8786: network of library servers; returns file handle of where SQL and regex results
                   8787: will be stored for query
1.191     harris41 8788: 
                   8789: =item *
                   8790: 
1.243     albertel 8791: symbread($filename) : return symbolic list entry (filename argument optional);
                   8792: returns the data handle
1.191     harris41 8793: 
                   8794: =item *
                   8795: 
1.243     albertel 8796: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8797: a possible symb for the URL in $thisfn, and if is an encryypted
                   8798: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8799: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8800: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8801: 
1.191     harris41 8802: 
                   8803: =item *
                   8804: 
1.243     albertel 8805: symbclean($symb) : removes versions numbers from a symb, returns the
                   8806: cleaned symb
1.191     harris41 8807: 
                   8808: =item *
                   8809: 
1.243     albertel 8810: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8811: course map, user must be in a course for it to work.
1.191     harris41 8812: 
                   8813: =item *
                   8814: 
1.243     albertel 8815: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8816: 
                   8817: =item *
                   8818: 
1.243     albertel 8819: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8820: a random seed, all arguments are optional, if they aren't sent it uses the
                   8821: environment to derive them. Note: if symb isn't sent and it can't get one
                   8822: from &symbread it will use the current time as its return value
1.191     harris41 8823: 
                   8824: =item *
                   8825: 
1.243     albertel 8826: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8827: unfakeable, receipt
1.191     harris41 8828: 
                   8829: =item *
                   8830: 
1.620     albertel 8831: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8832: 
                   8833: =item *
                   8834: 
1.243     albertel 8835: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8836: 
                   8837: =item *
                   8838: 
1.243     albertel 8839: 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 8840: 
                   8841: =item *
                   8842: 
1.243     albertel 8843: 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 8844: 
                   8845: =item *
                   8846: 
1.243     albertel 8847: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8848: 
                   8849: =item *
                   8850: 
1.243     albertel 8851: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8852: forcing spreadsheet to reevaluate the resource scores next time.
                   8853: 
                   8854: =back
                   8855: 
                   8856: =head2 Storing/Retreiving Data
                   8857: 
                   8858: =over 4
1.191     harris41 8859: 
                   8860: =item *
                   8861: 
1.243     albertel 8862: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8863: for this url; hashref needs to be given and should be a \%hashname; the
                   8864: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8865: be derived from the env
1.191     harris41 8866: 
                   8867: =item *
                   8868: 
1.243     albertel 8869: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8870: uses critical subroutine
1.191     harris41 8871: 
                   8872: =item *
                   8873: 
1.243     albertel 8874: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8875: all args are optional
1.191     harris41 8876: 
                   8877: =item *
                   8878: 
1.717     albertel 8879: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8880: dumps the complete (or key matching regexp) namespace into a hash
                   8881: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8882: normally &store()ed into
                   8883: 
                   8884: $range should be either an integer '100' (give me the first 100
                   8885:                                            matching records)
                   8886:               or be  two integers sperated by a - with no spaces
                   8887:                  '30-50' (give me the 30th through the 50th matching
                   8888:                           records)
                   8889: 
                   8890: 
                   8891: =item *
                   8892: 
                   8893: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8894: replaces a &store() version of data with a replacement set of data
                   8895: for a particular resource in a namespace passed in the $storehash hash 
                   8896: reference
                   8897: 
                   8898: =item *
                   8899: 
1.243     albertel 8900: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8901: works very similar to store/cstore, but all data is stored in a
                   8902: temporary location and can be reset using tmpreset, $storehash should
                   8903: be a hash reference, returns nothing on success
1.191     harris41 8904: 
                   8905: =item *
                   8906: 
1.243     albertel 8907: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8908: similar to restore, but all data is stored in a temporary location and
                   8909: can be reset using tmpreset. Returns a hash of values on success,
                   8910: error string otherwise.
1.191     harris41 8911: 
                   8912: =item *
                   8913: 
1.243     albertel 8914: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8915: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8916: 
                   8917: =item *
                   8918: 
1.243     albertel 8919: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8920: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8921: 
                   8922: =item *
                   8923: 
1.243     albertel 8924: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8925: namesp ($udom and $uname are optional)
1.191     harris41 8926: 
                   8927: =item *
                   8928: 
1.702     albertel 8929: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8930: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8931: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8932: 
1.702     albertel 8933: $range should be either an integer '100' (give me the first 100
                   8934:                                            matching records)
                   8935:               or be  two integers sperated by a - with no spaces
                   8936:                  '30-50' (give me the 30th through the 50th matching
                   8937:                           records)
1.449     matthew  8938: =item *
                   8939: 
                   8940: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8941: $store can be a scalar, an array reference, or if the amount to be 
                   8942: incremented is > 1, a hash reference.
                   8943: 
                   8944: ($udom and $uname are optional)
1.191     harris41 8945: 
                   8946: =item *
                   8947: 
1.243     albertel 8948: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8949: ($udom and $uname are optional)
1.191     harris41 8950: 
                   8951: =item *
                   8952: 
1.243     albertel 8953: cput($namespace,$storehash,$udom,$uname) : critical put
                   8954: ($udom and $uname are optional)
1.191     harris41 8955: 
                   8956: =item *
                   8957: 
1.748     albertel 8958: newput($namespace,$storehash,$udom,$uname) :
                   8959: 
                   8960: Attempts to store the items in the $storehash, but only if they don't
                   8961: currently exist, if this succeeds you can be certain that you have 
                   8962: successfully created a new key value pair in the $namespace db.
                   8963: 
                   8964: 
                   8965: Args:
                   8966:  $namespace: name of database to store values to
                   8967:  $storehash: hashref to store to the db
                   8968:  $udom: (optional) domain of user containing the db
                   8969:  $uname: (optional) name of user caontaining the db
                   8970: 
                   8971: Returns:
                   8972:  'ok' -> succeeded in storing all keys of $storehash
                   8973:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8974:                         least <key> already existed in the db (other
                   8975:                         requested keys may also already exist)
                   8976:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8977:  'con_lost' -> unable to contact request server
                   8978:  'refused' -> action was not allowed by remote machine
                   8979: 
                   8980: 
                   8981: =item *
                   8982: 
1.243     albertel 8983: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8984: reference filled in from namesp (encrypts the return communication)
                   8985: ($udom and $uname are optional)
1.191     harris41 8986: 
                   8987: =item *
                   8988: 
1.243     albertel 8989: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8990: critical subroutine
                   8991: 
1.806     raeburn  8992: =item *
                   8993: 
1.860     raeburn  8994: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   8995: array reference filled in from namespace found in domain level on either
                   8996: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  8997: 
                   8998: =item *
                   8999: 
1.860     raeburn  9000: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9001: domain level either on specified domain server ($uhome) or primary domain 
                   9002: server ($udom and $uhome are optional)
1.806     raeburn  9003: 
1.243     albertel 9004: =back
                   9005: 
                   9006: =head2 Network Status Functions
                   9007: 
                   9008: =over 4
1.191     harris41 9009: 
                   9010: =item *
                   9011: 
                   9012: dirlist($uri) : return directory list based on URI
                   9013: 
                   9014: =item *
                   9015: 
1.243     albertel 9016: spareserver() : find server with least workload from spare.tab
                   9017: 
                   9018: =back
                   9019: 
                   9020: =head2 Apache Request
                   9021: 
                   9022: =over 4
1.191     harris41 9023: 
                   9024: =item *
                   9025: 
1.243     albertel 9026: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9027: localhost, posts hash
                   9028: 
                   9029: =back
                   9030: 
                   9031: =head2 Data to String to Data
                   9032: 
                   9033: =over 4
1.191     harris41 9034: 
                   9035: =item *
                   9036: 
1.243     albertel 9037: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9038: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9039: 
                   9040: =item *
                   9041: 
1.243     albertel 9042: hashref2str($hashref) : convert a hashref into a string complete with
                   9043: escaping and '=' and '&' separators, supports elements that are
                   9044: arrayrefs and hashrefs
1.191     harris41 9045: 
                   9046: =item *
                   9047: 
1.243     albertel 9048: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9049: with escaping and '&' separators, supports elements that are arrayrefs
                   9050: and hashrefs
1.191     harris41 9051: 
                   9052: =item *
                   9053: 
1.243     albertel 9054: str2hash($string) : convert string to hash using unescaping and
                   9055: splitting on '=' and '&', supports elements that are arrayrefs and
                   9056: hashrefs
1.191     harris41 9057: 
                   9058: =item *
                   9059: 
1.243     albertel 9060: str2array($string) : convert string to hash using unescaping and
                   9061: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9062: 
                   9063: =back
                   9064: 
                   9065: =head2 Logging Routines
                   9066: 
                   9067: =over 4
                   9068: 
                   9069: These routines allow one to make log messages in the lonnet.log and
                   9070: lonnet.perm logfiles.
1.191     harris41 9071: 
                   9072: =item *
                   9073: 
1.243     albertel 9074: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9075: 
                   9076: =item *
                   9077: 
1.243     albertel 9078: logthis() : append message to the normal lonnet.log file, it gets
                   9079: preiodically rolled over and deleted.
1.191     harris41 9080: 
                   9081: =item *
                   9082: 
1.243     albertel 9083: logperm() : append a permanent message to lonnet.perm.log, this log
                   9084: file never gets deleted by any automated portion of the system, only
                   9085: messages of critical importance should go in here.
                   9086: 
                   9087: =back
                   9088: 
                   9089: =head2 General File Helper Routines
                   9090: 
                   9091: =over 4
1.191     harris41 9092: 
                   9093: =item *
                   9094: 
1.481     raeburn  9095: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9096: (a) files in /uploaded
                   9097:   (i) If a local copy of the file exists - 
                   9098:       compares modification date of local copy with last-modified date for 
                   9099:       definitive version stored on home server for course. If local copy is 
                   9100:       stale, requests a new version from the home server and stores it. 
                   9101:       If the original has been removed from the home server, then local copy 
                   9102:       is unlinked.
                   9103:   (ii) If local copy does not exist -
                   9104:       requests the file from the home server and stores it. 
                   9105:   
                   9106:   If $caller is 'uploadrep':  
                   9107:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9108:     for request for files originally uploaded via DOCS. 
                   9109:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9110:   
                   9111:   Otherwise:
                   9112:      This indicates a call from the content generation phase of the request.
                   9113:      -  returns the entire contents of the file or -1.
                   9114:      
                   9115: (b) files in /res
                   9116:    - returns the entire contents of a file or -1; 
                   9117:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9118: 
1.712     albertel 9119: 
                   9120: =item *
                   9121: 
                   9122: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9123:                   reference
                   9124: 
                   9125: returns either a stat() list of data about the file or an empty list
                   9126: if the file doesn't exist or couldn't find out about it (connection
                   9127: problems or user unknown)
                   9128: 
1.191     harris41 9129: =item *
                   9130: 
1.243     albertel 9131: filelocation($dir,$file) : returns file system location of a file
                   9132: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9133: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9134: and a file of ../bob will become /a/bob)
1.191     harris41 9135: 
                   9136: =item *
                   9137: 
                   9138: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9139: filelocation except for hrefs
                   9140: 
                   9141: =item *
                   9142: 
                   9143: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9144: 
1.243     albertel 9145: =back
                   9146: 
1.608     albertel 9147: =head2 Usererfile file routines (/uploaded*)
                   9148: 
                   9149: =over 4
                   9150: 
                   9151: =item *
                   9152: 
                   9153: userfileupload(): main rotine for putting a file in a user or course's
                   9154:                   filespace, arguments are,
                   9155: 
1.620     albertel 9156:  formname - required - this is the name of the element in $env where the
1.608     albertel 9157:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9158:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9159:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9160:  coursedoc - if true, store the file in the course of the active role
                   9161:              of the current user
                   9162:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9163:          if undefined, it will be placed in "unknown"
                   9164: 
                   9165:  (This routine calls clean_filename() to remove any dangerous
                   9166:  characters from the filename, and then calls finuserfileupload() to
                   9167:  complete the transaction)
                   9168: 
                   9169:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9170:  and /adm/notfound.html if unsuccessful
                   9171: 
                   9172: =item *
                   9173: 
                   9174: clean_filename(): routine for cleaing a filename up for storage in
                   9175:                  userfile space, argument is:
                   9176: 
                   9177:  filename - proposed filename
                   9178: 
                   9179: returns: the new clean filename
                   9180: 
                   9181: =item *
                   9182: 
                   9183: finishuserfileupload(): routine that creaes and sends the file to
                   9184: userspace, probably shouldn't be called directly
                   9185: 
                   9186:   docuname: username or courseid of destination for the file
                   9187:   docudom: domain of user/course of destination for the file
                   9188:   formname: same as for userfileupload()
                   9189:   fname: filename (inculding subdirectories) for the file
                   9190: 
                   9191:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9192:  and /adm/notfound.html if unsuccessful
                   9193: 
                   9194: =item *
                   9195: 
                   9196: renameuserfile(): renames an existing userfile to a new name
                   9197: 
                   9198:   Args:
                   9199:    docuname: username or courseid of destination for the file
                   9200:    docudom: domain of user/course of destination for the file
                   9201:    old: current file name (including any subdirs under userfiles)
                   9202:    new: desired file name (including any subdirs under userfiles)
                   9203: 
                   9204: =item *
                   9205: 
                   9206: mkdiruserfile(): creates a directory is a userfiles dir
                   9207: 
                   9208:   Args:
                   9209:    docuname: username or courseid of destination for the file
                   9210:    docudom: domain of user/course of destination for the file
                   9211:    dir: dir to create (including any subdirs under userfiles)
                   9212: 
                   9213: =item *
                   9214: 
                   9215: removeuserfile(): removes a file that exists in userfiles
                   9216: 
                   9217:   Args:
                   9218:    docuname: username or courseid of destination for the file
                   9219:    docudom: domain of user/course of destination for the file
                   9220:    fname: filname to delete (including any subdirs under userfiles)
                   9221: 
                   9222: =item *
                   9223: 
                   9224: removeuploadedurl(): convience function for removeuserfile()
                   9225: 
                   9226:   Args:
                   9227:    url:  a full /uploaded/... url to delete
                   9228: 
1.747     albertel 9229: =item * 
                   9230: 
                   9231: get_portfile_permissions():
                   9232:   Args:
                   9233:     domain: domain of user or course contain the portfolio files
                   9234:     user: name of user or num of course contain the portfolio files
                   9235:   Returns:
                   9236:     hashref of a dump of the proper file_permissions.db
                   9237:    
                   9238: 
                   9239: =item * 
                   9240: 
                   9241: get_access_controls():
                   9242: 
                   9243: Args:
                   9244:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9245:   group: (optional) the group you want the files associated with
                   9246:   file: (optional) the file you want access info on
                   9247: 
                   9248: Returns:
1.749     raeburn  9249:     a hash (keys are file names) of hashes containing
                   9250:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9251:         values are XML containing access control settings (see below) 
1.747     albertel 9252: 
                   9253: Internal notes:
                   9254: 
1.749     raeburn  9255:  access controls are stored in file_permissions.db as key=value pairs.
                   9256:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9257:         where scope -> public,guest,course,group,domains or users.
                   9258:               end -> UNIX time for end of access (0 -> no end date)
                   9259:               start -> UNIX time for start of access
                   9260: 
                   9261:     value -> XML description of access control
                   9262:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9263:             <start></start>
                   9264:             <end></end>
                   9265: 
                   9266:             <password></password>  for scope type = guest
                   9267: 
                   9268:             <domain></domain>     for scope type = course or group
                   9269:             <number></number>
                   9270:             <roles id="">
                   9271:              <role></role>
                   9272:              <access></access>
                   9273:              <section></section>
                   9274:              <group></group>
                   9275:             </roles>
                   9276: 
                   9277:             <dom></dom>         for scope type = domains
                   9278: 
                   9279:             <users>             for scope type = users
                   9280:              <user>
                   9281:               <uname></uname>
                   9282:               <udom></udom>
                   9283:              </user>
                   9284:             </users>
                   9285:            </scope> 
                   9286:               
                   9287:  Access data is also aggregated for each file in an additional key=value pair:
                   9288:  key -> path to file/file_name\0accesscontrol 
                   9289:  value -> reference to hash
                   9290:           hash contains key = value pairs
                   9291:           where key = uniqueID:scope_end_start
                   9292:                 value = UNIX time record was last updated
                   9293: 
                   9294:           Used to improve speed of look-ups of access controls for each file.  
                   9295:  
                   9296:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9297: 
                   9298: modify_access_controls():
                   9299: 
                   9300: Modifies access controls for a portfolio file
                   9301: Args
                   9302: 1. file name
                   9303: 2. reference to hash of required changes,
                   9304: 3. domain
                   9305: 4. username
                   9306:   where domain,username are the domain of the portfolio owner 
                   9307:   (either a user or a course) 
                   9308: 
                   9309: Returns:
                   9310: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9311: 2. result of deletions ('ok' or 'error', with error message).
                   9312: 3. reference to hash of any new or updated access controls.
                   9313: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9314:    key = integer (inbound ID)
                   9315:    value = uniqueID  
1.747     albertel 9316: 
1.608     albertel 9317: =back
                   9318: 
1.243     albertel 9319: =head2 HTTP Helper Routines
                   9320: 
                   9321: =over 4
                   9322: 
1.191     harris41 9323: =item *
                   9324: 
                   9325: escape() : unpack non-word characters into CGI-compatible hex codes
                   9326: 
                   9327: =item *
                   9328: 
                   9329: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9330: 
1.243     albertel 9331: =back
                   9332: 
                   9333: =head1 PRIVATE SUBROUTINES
                   9334: 
                   9335: =head2 Underlying communication routines (Shouldn't call)
                   9336: 
                   9337: =over 4
                   9338: 
                   9339: =item *
                   9340: 
                   9341: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9342: 
                   9343: =item *
                   9344: 
                   9345: reply() : uses subreply to send a message to remote machine, logs all failures
                   9346: 
                   9347: =item *
                   9348: 
                   9349: critical() : passes a critical message to another server; if cannot
                   9350: get through then place message in connection buffer directory and
                   9351: returns con_delayed, if incapable of saving message, returns
                   9352: con_failed
                   9353: 
                   9354: =item *
                   9355: 
                   9356: reconlonc() : tries to reconnect lonc client processes.
                   9357: 
                   9358: =back
                   9359: 
                   9360: =head2 Resource Access Logging
                   9361: 
                   9362: =over 4
                   9363: 
                   9364: =item *
                   9365: 
                   9366: flushcourselogs() : flush (save) buffer logs and access logs
                   9367: 
                   9368: =item *
                   9369: 
                   9370: courselog($what) : save message for course in hash
                   9371: 
                   9372: =item *
                   9373: 
                   9374: courseacclog($what) : save message for course using &courselog().  Perform
                   9375: special processing for specific resource types (problems, exams, quizzes, etc).
                   9376: 
1.191     harris41 9377: =item *
                   9378: 
                   9379: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9380: as a PerlChildExitHandler
1.243     albertel 9381: 
                   9382: =back
                   9383: 
                   9384: =head2 Other
                   9385: 
                   9386: =over 4
                   9387: 
                   9388: =item *
                   9389: 
                   9390: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9391: 
                   9392: =back
                   9393: 
                   9394: =cut
1.877     foxr     9395: 

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