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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.912   ! raeburn     4: # $Id: lonnet.pm,v 1.911 2007/09/12 03:40:35 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');
1.909     raeburn   864:     my $outcome;
1.899     raeburn   865:     if ($homeserver ne '') {
1.904     albertel  866: 	my $queryid=&reply("querysend:instdirsearch:".
                    867: 			   &escape($srch->{'srchby'}).':'.
                    868: 			   &escape($srch->{'srchterm'}).':'.
                    869: 			   &escape($srch->{'srchtype'}),$homeserver);
                    870: 	my $host=&hostname($homeserver);
                    871: 	if ($queryid !~/^\Q$host\E\_/) {
                    872: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    873: 	    return;
                    874: 	}
                    875: 	my $response = &get_query_reply($queryid);
                    876: 	my $maxtries = 5;
                    877: 	my $tries = 1;
                    878: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    879: 	    $response = &get_query_reply($queryid);
                    880: 	    $tries ++;
                    881: 	}
                    882: 
                    883:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn   884:             if ($response eq 'unavailable') {
                    885:                 $outcome = $response;
                    886:             } else {
                    887:                 $outcome = 'ok';
                    888:                 my @matches = split(/\n/,$response);
                    889:                 foreach my $match (@matches) {
                    890:                     my ($key,$value) = split(/=/,$match);
                    891:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                    892:                 }
1.899     raeburn   893:             }
                    894:         }
                    895:     }
1.909     raeburn   896:     return ($outcome,%results);
1.899     raeburn   897: }
                    898: 
                    899: sub usersearch {
                    900:     my ($srch) = @_;
                    901:     my $dom = $srch->{'srchdomain'};
                    902:     my %results;
                    903:     my %libserv = &all_library();
                    904:     my $query = 'usersearch';
                    905:     foreach my $tryserver (keys(%libserv)) {
                    906:         if (&host_domain($tryserver) eq $dom) {
                    907:             my $host=&hostname($tryserver);
                    908:             my $queryid=
1.911     raeburn   909:                 &reply("querysend:".&escape($query).':'.
                    910:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn   911:                        &escape($srch->{'srchtype'}).':'.
                    912:                        &escape($srch->{'srchterm'}),$tryserver);
                    913:             if ($queryid !~/^\Q$host\E\_/) {
                    914:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   915:                 next;
1.899     raeburn   916:             }
                    917:             my $reply = &get_query_reply($queryid);
                    918:             my $maxtries = 1;
                    919:             my $tries = 1;
                    920:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    921:                 $reply = &get_query_reply($queryid);
                    922:                 $tries ++;
                    923:             }
                    924:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    925:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    926:             } else {
1.911     raeburn   927:                 my @matches;
                    928:                 if ($reply =~ /\n/) {
                    929:                     @matches = split(/\n/,$reply);
                    930:                 } else {
                    931:                     @matches = split(/\&/,$reply);
                    932:                 }
1.899     raeburn   933:                 foreach my $match (@matches) {
                    934:                     my ($uname,$udom,%userhash);
1.911     raeburn   935:                     foreach my $entry (split(/:/,$match)) {
                    936:                         my ($key,$value) =
                    937:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn   938:                         $userhash{$key} = $value;
                    939:                         if ($key eq 'username') {
                    940:                             $uname = $value;
                    941:                         } elsif ($key eq 'domain') {
                    942:                             $udom = $value;
1.911     raeburn   943:                         }
1.899     raeburn   944:                     }
                    945:                     $results{$uname.':'.$udom} = \%userhash;
                    946:                 }
                    947:             }
                    948:         }
                    949:     }
                    950:     return %results;
                    951: }
                    952: 
1.912   ! raeburn   953: sub get_instuser {
        !           954:     my ($udom,$uname,$id) = @_;
        !           955:     my $homeserver = &domain($udom,'primary');
        !           956:     my ($outcome,%results);
        !           957:     if ($homeserver ne '') {
        !           958:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
        !           959:                            &escape($id).':'.&escape($udom),$homeserver);
        !           960:         my $host=&hostname($homeserver);
        !           961:         if ($queryid !~/^\Q$host\E\_/) {
        !           962:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
        !           963:             return;
        !           964:         }
        !           965:         my $response = &get_query_reply($queryid);
        !           966:         my $maxtries = 5;
        !           967:         my $tries = 1;
        !           968:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
        !           969:             $response = &get_query_reply($queryid);
        !           970:             $tries ++;
        !           971:         }
        !           972:         if (!&error($response) && $response ne 'refused') {
        !           973:             if ($response eq 'unavailable') {
        !           974:                 $outcome = $response;
        !           975:             } else {
        !           976:                 $outcome = 'ok';
        !           977:                 my @matches = split(/\n/,$response);
        !           978:                 foreach my $match (@matches) {
        !           979:                     my ($key,$value) = split(/=/,$match);
        !           980:                     $results{&unescape($key)} = &thaw_unescape($value);
        !           981:                 }
        !           982:             }
        !           983:         }
        !           984:     }
        !           985:     my %userinfo;
        !           986:     if (ref($results{$uname}) eq 'HASH') {
        !           987:         %userinfo = %{$results{$uname}};
        !           988:     } 
        !           989:     return ($outcome,%userinfo);
        !           990: }
        !           991: 
        !           992: sub inst_rulecheck {
        !           993:     my ($udom,$uname,$rules) = @_;
        !           994:     my %returnhash;
        !           995:     if ($udom ne '') {
        !           996:         if (ref($rules) eq 'ARRAY') {
        !           997:             @{$rules} = map {&escape($_);} (@{$rules});
        !           998:             my $rulestr = join(':',@{$rules});
        !           999:             my $homeserver=&domain($udom,'primary');
        !          1000:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
        !          1001:                 my $response=&unescape(&reply('instrulecheck:'.&escape($udom).':'.
        !          1002:                                               &escape($uname).':'.$rulestr,
        !          1003:                                               $homeserver));
        !          1004:                 if ($response ne 'refused') {
        !          1005:                     my @pairs=split(/\&/,$response);
        !          1006:                     foreach my $item (@pairs) {
        !          1007:                         my ($key,$value)=split(/=/,$item,2);
        !          1008:                         $key = &unescape($key);
        !          1009:                         next if ($key =~ /^error: 2 /);
        !          1010:                         $returnhash{$key}=&thaw_unescape($value);
        !          1011:                     }
        !          1012:                 }
        !          1013:             }
        !          1014:         }
        !          1015:     }
        !          1016:     return %returnhash;
        !          1017: }
        !          1018: 
        !          1019: sub inst_userrules {
        !          1020:     my ($udom) = @_;
        !          1021:     my (%ruleshash,@ruleorder);
        !          1022:     if ($udom ne '') {
        !          1023:         my $homeserver=&domain($udom,'primary');
        !          1024:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
        !          1025:             my $response=&reply('instuserrules:'.&escape($udom),
        !          1026:                                  $homeserver);
        !          1027:             if (($response ne 'refused') && ($response ne 'error') && 
        !          1028:                 ($response ne 'no_such_host')) {
        !          1029:                 my ($hashitems,$orderitems) = split(/:/,$response);
        !          1030:                 my @pairs=split(/\&/,$hashitems);
        !          1031:                 foreach my $item (@pairs) {
        !          1032:                     my ($key,$value)=split(/=/,$item,2);
        !          1033:                     $key = &unescape($key);
        !          1034:                     next if ($key =~ /^error: 2 /);
        !          1035:                     $ruleshash{$key}=&thaw_unescape($value);
        !          1036:                 }
        !          1037:                 my @esc_order = split(/\&/,$orderitems);
        !          1038:                 foreach my $item (@esc_order) {
        !          1039:                     push(@ruleorder,&unescape($item));
        !          1040:                 }
        !          1041:             }
        !          1042:         }
        !          1043:     }
        !          1044:     return (\%ruleshash,\@ruleorder);
        !          1045: }
        !          1046: 
1.344     www      1047: # --------------------------------------------------- Assign a key to a student
                   1048: 
                   1049: sub assign_access_key {
1.364     www      1050: #
                   1051: # a valid key looks like uname:udom#comments
                   1052: # comments are being appended
                   1053: #
1.498     www      1054:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1055:     $kdom=
1.620     albertel 1056:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1057:     $knum=
1.620     albertel 1058:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1059:     $cdom=
1.620     albertel 1060:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1061:     $cnum=
1.620     albertel 1062:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1063:     $udom=$env{'user.name'} unless (defined($udom));
                   1064:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1065:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1066:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1067:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1068:                                                   # assigned to this person
                   1069:                                                   # - this should not happen,
1.345     www      1070:                                                   # unless something went wrong
                   1071:                                                   # the first time around
                   1072: # ready to assign
1.364     www      1073:         $logentry=$1.'; '.$logentry;
1.496     www      1074:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1075:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1076: # key now belongs to user
1.346     www      1077: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1078:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                   1079:                 &appenv('environment.'.$envkey => $ckey);
                   1080:                 return 'ok';
                   1081:             } else {
                   1082:                 return 
                   1083:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1084: 	    }
                   1085:         } else {
                   1086:             return 'error: Could not assign key, try again later.';
                   1087:         }
1.364     www      1088:     } elsif (!$existing{$ckey}) {
1.345     www      1089: # the key does not exist
                   1090: 	return 'error: The key does not exist';
                   1091:     } else {
                   1092: # the key is somebody else's
                   1093: 	return 'error: The key is already in use';
                   1094:     }
1.344     www      1095: }
                   1096: 
1.364     www      1097: # ------------------------------------------ put an additional comment on a key
                   1098: 
                   1099: sub comment_access_key {
                   1100: #
                   1101: # a valid key looks like uname:udom#comments
                   1102: # comments are being appended
                   1103: #
                   1104:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1105:     $cdom=
1.620     albertel 1106:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1107:     $cnum=
1.620     albertel 1108:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1109:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1110:     if ($existing{$ckey}) {
                   1111:         $existing{$ckey}.='; '.$logentry;
                   1112: # ready to assign
1.367     www      1113:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1114:                                                  $cdom,$cnum) eq 'ok') {
                   1115: 	    return 'ok';
                   1116:         } else {
                   1117: 	    return 'error: Count not store comment.';
                   1118:         }
                   1119:     } else {
                   1120: # the key does not exist
                   1121: 	return 'error: The key does not exist';
                   1122:     }
                   1123: }
                   1124: 
1.344     www      1125: # ------------------------------------------------------ Generate a set of keys
                   1126: 
                   1127: sub generate_access_keys {
1.364     www      1128:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1129:     $cdom=
1.620     albertel 1130:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1131:     $cnum=
1.620     albertel 1132:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1133:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1134:     unless (($cdom) && ($cnum)) { return 0; }
                   1135:     if ($number>10000) { return 0; }
                   1136:     sleep(2); # make sure don't get same seed twice
                   1137:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1138:     my $total=0;
                   1139:     for (my $i=1;$i<=$number;$i++) {
                   1140:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1141:                   sprintf("%lx",int(100000*rand)).'-'.
                   1142:                   sprintf("%lx",int(100000*rand));
                   1143:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1144:        $newkey=~s/0/h/g; # and also 0 and O
                   1145:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1146:        if ($existing{$newkey}) {
                   1147:            $i--;
                   1148:        } else {
1.364     www      1149: 	  if (&put('accesskeys',
                   1150:               { $newkey => '# generated '.localtime().
1.620     albertel 1151:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1152:                            '; '.$logentry },
                   1153: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1154:               $total++;
                   1155: 	  }
                   1156:        }
                   1157:     }
1.620     albertel 1158:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1159:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1160:     return $total;
                   1161: }
                   1162: 
                   1163: # ------------------------------------------------------- Validate an accesskey
                   1164: 
                   1165: sub validate_access_key {
                   1166:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1167:     $cdom=
1.620     albertel 1168:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1169:     $cnum=
1.620     albertel 1170:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1171:     $udom=$env{'user.domain'} unless (defined($udom));
                   1172:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1173:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1174:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1175: }
                   1176: 
                   1177: # ------------------------------------- Find the section of student in a course
1.652     albertel 1178: sub devalidate_getsection_cache {
                   1179:     my ($udom,$unam,$courseid)=@_;
                   1180:     my $hashid="$udom:$unam:$courseid";
                   1181:     &devalidate_cache_new('getsection',$hashid);
                   1182: }
1.298     matthew  1183: 
1.815     albertel 1184: sub courseid_to_courseurl {
                   1185:     my ($courseid) = @_;
                   1186:     #already url style courseid
                   1187:     return $courseid if ($courseid =~ m{^/});
                   1188: 
                   1189:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1190: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1191: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1192: 	return "/$cdom/$cnum";
                   1193:     }
                   1194: 
                   1195:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1196:     if (exists($courseinfo{'num'})) {
                   1197: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1198:     }
                   1199: 
                   1200:     return undef;
                   1201: }
                   1202: 
1.298     matthew  1203: sub getsection {
                   1204:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1205:     my $cachetime=1800;
1.551     albertel 1206: 
                   1207:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1208:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1209:     if (defined($cached)) { return $result; }
                   1210: 
1.298     matthew  1211:     my %Pending; 
                   1212:     my %Expired;
                   1213:     #
                   1214:     # Each role can either have not started yet (pending), be active, 
                   1215:     #    or have expired.
                   1216:     #
                   1217:     # If there is an active role, we are done.
                   1218:     #
                   1219:     # If there is more than one role which has not started yet, 
                   1220:     #     choose the one which will start sooner
                   1221:     # If there is one role which has not started yet, return it.
                   1222:     #
                   1223:     # If there is more than one expired role, choose the one which ended last.
                   1224:     # If there is a role which has expired, return it.
                   1225:     #
1.815     albertel 1226:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1227:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1228:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1229:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1230:         my $section=$1;
                   1231:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1232:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1233:         my $now=time;
1.548     albertel 1234:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1235:             $Expired{$end}=$section;
                   1236:             next;
                   1237:         }
1.548     albertel 1238:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1239:             $Pending{$start}=$section;
                   1240:             next;
                   1241:         }
1.599     albertel 1242:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1243:     }
                   1244:     #
                   1245:     # Presumedly there will be few matching roles from the above
                   1246:     # loop and the sorting time will be negligible.
                   1247:     if (scalar(keys(%Pending))) {
                   1248:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1249:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1250:     } 
                   1251:     if (scalar(keys(%Expired))) {
                   1252:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1253:         my $time = pop(@sorted);
1.599     albertel 1254:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1255:     }
1.599     albertel 1256:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1257: }
1.70      www      1258: 
1.599     albertel 1259: sub save_cache {
                   1260:     &purge_remembered();
1.722     albertel 1261:     #&Apache::loncommon::validate_page();
1.620     albertel 1262:     undef(%env);
1.780     albertel 1263:     undef($env_loaded);
1.599     albertel 1264: }
1.452     albertel 1265: 
1.599     albertel 1266: my $to_remember=-1;
                   1267: my %remembered;
                   1268: my %accessed;
                   1269: my $kicks=0;
                   1270: my $hits=0;
1.849     albertel 1271: sub make_key {
                   1272:     my ($name,$id) = @_;
1.872     albertel 1273:     if (length($id) > 65 
                   1274: 	&& length(&escape($id)) > 200) {
                   1275: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1276:     }
1.849     albertel 1277:     return &escape($name.':'.$id);
                   1278: }
                   1279: 
1.599     albertel 1280: sub devalidate_cache_new {
                   1281:     my ($name,$id,$debug) = @_;
                   1282:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1283:     $id=&make_key($name,$id);
1.599     albertel 1284:     $memcache->delete($id);
                   1285:     delete($remembered{$id});
                   1286:     delete($accessed{$id});
                   1287: }
                   1288: 
                   1289: sub is_cached_new {
                   1290:     my ($name,$id,$debug) = @_;
1.849     albertel 1291:     $id=&make_key($name,$id);
1.599     albertel 1292:     if (exists($remembered{$id})) {
                   1293: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1294: 	$accessed{$id}=[&gettimeofday()];
                   1295: 	$hits++;
                   1296: 	return ($remembered{$id},1);
                   1297:     }
                   1298:     my $value = $memcache->get($id);
                   1299:     if (!(defined($value))) {
                   1300: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1301: 	return (undef,undef);
1.416     albertel 1302:     }
1.599     albertel 1303:     if ($value eq '__undef__') {
                   1304: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1305: 	$value=undef;
                   1306:     }
                   1307:     &make_room($id,$value,$debug);
                   1308:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1309:     return ($value,1);
                   1310: }
                   1311: 
                   1312: sub do_cache_new {
                   1313:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1314:     $id=&make_key($name,$id);
1.599     albertel 1315:     my $setvalue=$value;
                   1316:     if (!defined($setvalue)) {
                   1317: 	$setvalue='__undef__';
                   1318:     }
1.623     albertel 1319:     if (!defined($time) ) {
                   1320: 	$time=600;
                   1321:     }
1.599     albertel 1322:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1323:     my $result = $memcache->set($id,$setvalue,$time);
                   1324:     if (! $result) {
1.872     albertel 1325: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1326: 	$memcache->disconnect_all();
1.872     albertel 1327:     }
1.600     albertel 1328:     # need to make a copy of $value
                   1329:     #&make_room($id,$value,$debug);
1.599     albertel 1330:     return $value;
                   1331: }
                   1332: 
                   1333: sub make_room {
                   1334:     my ($id,$value,$debug)=@_;
                   1335:     $remembered{$id}=$value;
                   1336:     if ($to_remember<0) { return; }
                   1337:     $accessed{$id}=[&gettimeofday()];
                   1338:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1339:     my $to_kick;
                   1340:     my $max_time=0;
                   1341:     foreach my $other (keys(%accessed)) {
                   1342: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1343: 	    $to_kick=$other;
                   1344: 	    $max_time=&tv_interval($accessed{$other});
                   1345: 	}
                   1346:     }
                   1347:     delete($remembered{$to_kick});
                   1348:     delete($accessed{$to_kick});
                   1349:     $kicks++;
                   1350:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1351:     return;
                   1352: }
                   1353: 
1.599     albertel 1354: sub purge_remembered {
1.604     albertel 1355:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1356:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1357:     undef(%remembered);
                   1358:     undef(%accessed);
1.428     albertel 1359: }
1.70      www      1360: # ------------------------------------- Read an entry from a user's environment
                   1361: 
                   1362: sub userenvironment {
                   1363:     my ($udom,$unam,@what)=@_;
                   1364:     my %returnhash=();
                   1365:     my @answer=split(/\&/,
                   1366:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1367:                       &homeserver($unam,$udom)));
                   1368:     my $i;
                   1369:     for ($i=0;$i<=$#what;$i++) {
                   1370: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1371:     }
                   1372:     return %returnhash;
1.1       albertel 1373: }
                   1374: 
1.617     albertel 1375: # ---------------------------------------------------------- Get a studentphoto
                   1376: sub studentphoto {
                   1377:     my ($udom,$unam,$ext) = @_;
                   1378:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1379:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1380:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1381:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1382:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1383:             } else {
                   1384:                 my ($result,$perm_reqd)=
1.707     albertel 1385: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1386:                 if ($result eq 'ok') {
                   1387:                     if (!($perm_reqd eq 'yes')) {
                   1388:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1389:                     }
                   1390:                 }
                   1391:             }
                   1392:         }
                   1393:     } else {
                   1394:         my ($result,$perm_reqd) = 
1.707     albertel 1395: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1396:         if ($result eq 'ok') {
                   1397:             if (!($perm_reqd eq 'yes')) {
                   1398:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1399:             }
                   1400:         }
                   1401:     }
                   1402:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1403: }
                   1404: 
                   1405: sub retrievestudentphoto {
                   1406:     my ($udom,$unam,$ext,$type) = @_;
                   1407:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1408:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1409:     if ($ret eq 'ok') {
                   1410:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1411:         if ($type eq 'thumbnail') {
                   1412:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1413:         }
                   1414:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1415:         return $tokenurl;
                   1416:     } else {
                   1417:         if ($type eq 'thumbnail') {
                   1418:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1419:         } else { 
                   1420:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1421:         }
1.617     albertel 1422:     }
                   1423: }
                   1424: 
1.263     www      1425: # -------------------------------------------------------------------- New chat
                   1426: 
                   1427: sub chatsend {
1.724     raeburn  1428:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1429:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1430:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1431:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1432:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1433: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1434: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1435: }
                   1436: 
                   1437: # ------------------------------------------ Find current version of a resource
                   1438: 
                   1439: sub getversion {
                   1440:     my $fname=&clutter(shift);
                   1441:     unless ($fname=~/^\/res\//) { return -1; }
                   1442:     return &currentversion(&filelocation('',$fname));
                   1443: }
                   1444: 
                   1445: sub currentversion {
                   1446:     my $fname=shift;
1.599     albertel 1447:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1448:     if (defined($cached)) { return $result; }
1.292     www      1449:     my $author=$fname;
                   1450:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1451:     my ($udom,$uname)=split(/\//,$author);
                   1452:     my $home=homeserver($uname,$udom);
                   1453:     if ($home eq 'no_host') { 
                   1454:         return -1; 
                   1455:     }
                   1456:     my $answer=reply("currentversion:$fname",$home);
                   1457:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1458: 	return -1;
                   1459:     }
1.599     albertel 1460:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1461: }
                   1462: 
1.1       albertel 1463: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1464: 
1.1       albertel 1465: sub subscribe {
                   1466:     my $fname=shift;
1.761     raeburn  1467:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1468:     $fname=~s/[\n\r]//g;
1.1       albertel 1469:     my $author=$fname;
                   1470:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1471:     my ($udom,$uname)=split(/\//,$author);
                   1472:     my $home=homeserver($uname,$udom);
1.335     albertel 1473:     if ($home eq 'no_host') {
                   1474:         return 'not_found';
1.1       albertel 1475:     }
                   1476:     my $answer=reply("sub:$fname",$home);
1.64      www      1477:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1478: 	$answer.=' by '.$home;
                   1479:     }
1.1       albertel 1480:     return $answer;
                   1481: }
                   1482:     
1.8       www      1483: # -------------------------------------------------------------- Replicate file
                   1484: 
                   1485: sub repcopy {
                   1486:     my $filename=shift;
1.23      www      1487:     $filename=~s/\/+/\//g;
1.607     raeburn  1488:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1489:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1490:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1491: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1492: 	return &repcopy_userfile($filename);
                   1493:     }
1.532     albertel 1494:     $filename=~s/[\n\r]//g;
1.8       www      1495:     my $transname="$filename.in.transfer";
1.828     www      1496: # FIXME: this should flock
1.607     raeburn  1497:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1498:     my $remoteurl=subscribe($filename);
1.64      www      1499:     if ($remoteurl =~ /^con_lost by/) {
                   1500: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1501:            return 'unavailable';
1.8       www      1502:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1503: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1504: 	   return 'not_found';
1.64      www      1505:     } elsif ($remoteurl =~ /^rejected by/) {
                   1506: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1507:            return 'forbidden';
1.20      www      1508:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1509:            return 'ok';
1.8       www      1510:     } else {
1.290     www      1511:         my $author=$filename;
                   1512:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1513:         my ($udom,$uname)=split(/\//,$author);
                   1514:         my $home=homeserver($uname,$udom);
                   1515:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1516:            my @parts=split(/\//,$filename);
                   1517:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1518:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1519:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1520: 	       return 'bad_request';
1.8       www      1521:            }
                   1522:            my $count;
                   1523:            for ($count=5;$count<$#parts;$count++) {
                   1524:                $path.="/$parts[$count]";
                   1525:                if ((-e $path)!=1) {
                   1526: 		   mkdir($path,0777);
                   1527:                }
                   1528:            }
                   1529:            my $ua=new LWP::UserAgent;
                   1530:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1531:            my $response=$ua->request($request,$transname);
                   1532:            if ($response->is_error()) {
                   1533: 	       unlink($transname);
                   1534:                my $message=$response->status_line;
1.672     albertel 1535:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1536:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1537:                return 'unavailable';
1.8       www      1538:            } else {
1.16      www      1539: 	       if ($remoteurl!~/\.meta$/) {
                   1540:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1541:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1542:                   if ($mresponse->is_error()) {
                   1543: 		      unlink($filename.'.meta');
                   1544:                       &logthis(
1.672     albertel 1545:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1546:                   }
                   1547: 	       }
1.8       www      1548:                rename($transname,$filename);
1.607     raeburn  1549:                return 'ok';
1.8       www      1550:            }
1.290     www      1551:        }
1.8       www      1552:     }
1.330     www      1553: }
                   1554: 
                   1555: # ------------------------------------------------ Get server side include body
                   1556: sub ssi_body {
1.381     albertel 1557:     my ($filelink,%form)=@_;
1.606     matthew  1558:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1559:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1560:     }
1.330     www      1561:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1562:                                      &ssi($filelink,%form));
1.778     albertel 1563:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1564:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1565:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1566:     return $output;
1.8       www      1567: }
                   1568: 
1.15      www      1569: # --------------------------------------------------------- Server Side Include
                   1570: 
1.782     albertel 1571: sub absolute_url {
                   1572:     my ($host_name) = @_;
                   1573:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1574:     if ($host_name eq '') {
                   1575: 	$host_name = $ENV{'SERVER_NAME'};
                   1576:     }
                   1577:     return $protocol.$host_name;
                   1578: }
                   1579: 
1.15      www      1580: sub ssi {
                   1581: 
1.23      www      1582:     my ($fn,%form)=@_;
1.15      www      1583: 
                   1584:     my $ua=new LWP::UserAgent;
1.23      www      1585:     
                   1586:     my $request;
1.711     albertel 1587: 
                   1588:     $form{'no_update_last_known'}=1;
1.895     albertel 1589:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1590:     if (%form) {
1.782     albertel 1591:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1592:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1593:     } else {
1.782     albertel 1594:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1595:     }
                   1596: 
1.15      www      1597:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1598:     my $response=$ua->request($request);
                   1599: 
1.324     www      1600:     return $response->content;
                   1601: }
                   1602: 
                   1603: sub externalssi {
                   1604:     my ($url)=@_;
                   1605:     my $ua=new LWP::UserAgent;
                   1606:     my $request=new HTTP::Request('GET',$url);
                   1607:     my $response=$ua->request($request);
1.15      www      1608:     return $response->content;
                   1609: }
1.254     www      1610: 
1.492     albertel 1611: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1612: 
                   1613: sub allowuploaded {
                   1614:     my ($srcurl,$url)=@_;
                   1615:     $url=&clutter(&declutter($url));
                   1616:     my $dir=$url;
                   1617:     $dir=~s/\/[^\/]+$//;
                   1618:     my %httpref=();
                   1619:     my $httpurl=&hreflocation('',$url);
                   1620:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1621:     &Apache::lonnet::appenv(%httpref);
1.254     www      1622: }
1.477     raeburn  1623: 
1.478     albertel 1624: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1625: # input: action, courseID, current domain, intended
1.637     raeburn  1626: #        path to file, source of file, instruction to parse file for objects,
                   1627: #        ref to hash for embedded objects,
                   1628: #        ref to hash for codebase of java objects.
                   1629: #
1.485     raeburn  1630: # output: url to file (if action was uploaddoc), 
                   1631: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1632: #
1.478     albertel 1633: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1634: # course.
1.477     raeburn  1635: #
1.478     albertel 1636: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1637: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1638: #          course's home server.
1.477     raeburn  1639: #
1.478     albertel 1640: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1641: #          be copied from $source (current location) to 
                   1642: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1643: #         and will then be copied to
                   1644: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1645: #         course's home server.
1.485     raeburn  1646: #
1.481     raeburn  1647: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1648: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1649: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1650: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1651: #         in course's home server.
1.637     raeburn  1652: #
1.477     raeburn  1653: 
                   1654: sub process_coursefile {
1.638     albertel 1655:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1656:     my $fetchresult;
1.638     albertel 1657:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1658:     if ($action eq 'propagate') {
1.638     albertel 1659:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1660: 			     $home);
1.481     raeburn  1661:     } else {
1.477     raeburn  1662:         my $fpath = '';
                   1663:         my $fname = $file;
1.478     albertel 1664:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1665:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1666:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1667:         if ($action eq 'copy') {
                   1668:             if ($source eq '') {
                   1669:                 $fetchresult = 'no source file';
                   1670:                 return $fetchresult;
                   1671:             } else {
                   1672:                 my $destination = $filepath.'/'.$fname;
                   1673:                 rename($source,$destination);
                   1674:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1675:                                  $home);
1.481     raeburn  1676:             }
                   1677:         } elsif ($action eq 'uploaddoc') {
                   1678:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1679:             print $fh $env{'form.'.$source};
1.481     raeburn  1680:             close($fh);
1.637     raeburn  1681:             if ($parser eq 'parse') {
                   1682:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1683:                 unless ($parse_result eq 'ok') {
                   1684:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1685:                 }
                   1686:             }
1.477     raeburn  1687:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1688:                                  $home);
1.481     raeburn  1689:             if ($fetchresult eq 'ok') {
                   1690:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1691:             } else {
                   1692:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1693:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1694:                 return '/adm/notfound.html';
                   1695:             }
1.477     raeburn  1696:         }
                   1697:     }
1.485     raeburn  1698:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1699:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1700:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1701:     }
                   1702:     return $fetchresult;
                   1703: }
                   1704: 
1.637     raeburn  1705: sub build_filepath {
                   1706:     my ($fpath) = @_;
                   1707:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1708:     unless ($fpath eq '') {
                   1709:         my @parts=split('/',$fpath);
                   1710:         foreach my $part (@parts) {
                   1711:             $filepath.= '/'.$part;
                   1712:             if ((-e $filepath)!=1) {
                   1713:                 mkdir($filepath,0777);
                   1714:             }
                   1715:         }
                   1716:     }
                   1717:     return $filepath;
                   1718: }
                   1719: 
                   1720: sub store_edited_file {
1.638     albertel 1721:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1722:     my $file = $primary_url;
                   1723:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1724:     my $fpath = '';
                   1725:     my $fname = $file;
                   1726:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1727:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1728:     my $filepath = &build_filepath($fpath);
                   1729:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1730:     print $fh $content;
                   1731:     close($fh);
1.638     albertel 1732:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1733:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1734: 			  $home);
1.637     raeburn  1735:     if ($$fetchresult eq 'ok') {
                   1736:         return '/uploaded/'.$fpath.'/'.$fname;
                   1737:     } else {
1.638     albertel 1738:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1739: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1740:         return '/adm/notfound.html';
                   1741:     }
                   1742: }
                   1743: 
1.531     albertel 1744: sub clean_filename {
1.831     albertel 1745:     my ($fname,$args)=@_;
1.315     www      1746: # Replace Windows backslashes by forward slashes
1.257     www      1747:     $fname=~s/\\/\//g;
1.831     albertel 1748:     if (!$args->{'keep_path'}) {
                   1749:         # Get rid of everything but the actual filename
                   1750: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1751:     }
1.315     www      1752: # Replace spaces by underscores
                   1753:     $fname=~s/\s+/\_/g;
                   1754: # Replace all other weird characters by nothing
1.831     albertel 1755:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1756: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1757: # numbers
                   1758:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1759:     return $fname;
                   1760: }
                   1761: 
1.608     albertel 1762: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1763: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1764: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1765: #        $coursedoc - if true up to the current course
                   1766: #                     if false
                   1767: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1768: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1769: #        $allfiles - reference to hash for embedded objects
                   1770: #        $codebase - reference to hash for codebase of java objects
                   1771: #        $desuname - username for permanent storage of uploaded file
                   1772: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1773: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1774: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1775: # 
1.686     albertel 1776: # output: url of file in userspace, or error: <message> 
                   1777: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1778: 
                   1779: 
1.531     albertel 1780: sub userfileupload {
1.860     raeburn  1781:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1782:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1783:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1784:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1785:     $fname=&clean_filename($fname);
1.315     www      1786: # See if there is anything left
1.257     www      1787:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1788:     chop($env{'form.'.$formname});
1.523     raeburn  1789:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1790:         my $now = time;
                   1791:         my $filepath = 'tmp/helprequests/'.$now;
                   1792:         my @parts=split(/\//,$filepath);
                   1793:         my $fullpath = $perlvar{'lonDaemons'};
                   1794:         for (my $i=0;$i<@parts;$i++) {
                   1795:             $fullpath .= '/'.$parts[$i];
                   1796:             if ((-e $fullpath)!=1) {
                   1797:                 mkdir($fullpath,0777);
                   1798:             }
                   1799:         }
                   1800:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1801:         print $fh $env{'form.'.$formname};
1.523     raeburn  1802:         close($fh);
1.741     raeburn  1803:         return $fullpath.'/'.$fname;
                   1804:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1805:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1806:                        '_'.$env{'user.domain'}.'/pending';
                   1807:         my @parts=split(/\//,$filepath);
                   1808:         my $fullpath = $perlvar{'lonDaemons'};
                   1809:         for (my $i=0;$i<@parts;$i++) {
                   1810:             $fullpath .= '/'.$parts[$i];
                   1811:             if ((-e $fullpath)!=1) {
                   1812:                 mkdir($fullpath,0777);
                   1813:             }
                   1814:         }
                   1815:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1816:         print $fh $env{'form.'.$formname};
                   1817:         close($fh);
                   1818:         return $fullpath.'/'.$fname;
1.523     raeburn  1819:     }
1.719     banghart 1820:     
1.258     www      1821: # Create the directory if not present
1.493     albertel 1822:     $fname="$subdir/$fname";
1.259     www      1823:     if ($coursedoc) {
1.638     albertel 1824: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1825: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1826:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1827:             return &finishuserfileupload($docuname,$docudom,
                   1828: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1829: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1830:         } else {
1.620     albertel 1831:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1832:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1833: 				       $fname,$formname,$parser,
                   1834: 				       $allfiles,$codebase);
1.481     raeburn  1835:         }
1.719     banghart 1836:     } elsif (defined($destuname)) {
                   1837:         my $docuname=$destuname;
                   1838:         my $docudom=$destudom;
1.860     raeburn  1839: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1840: 				     $parser,$allfiles,$codebase,
                   1841:                                      $thumbwidth,$thumbheight);
1.719     banghart 1842:         
1.259     www      1843:     } else {
1.638     albertel 1844:         my $docuname=$env{'user.name'};
                   1845:         my $docudom=$env{'user.domain'};
1.714     raeburn  1846:         if (exists($env{'form.group'})) {
                   1847:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1848:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1849:         }
1.860     raeburn  1850: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1851: 				     $parser,$allfiles,$codebase,
                   1852:                                      $thumbwidth,$thumbheight);
1.259     www      1853:     }
1.271     www      1854: }
                   1855: 
                   1856: sub finishuserfileupload {
1.860     raeburn  1857:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1858:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1859:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1860:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1861:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1862:     $file=$fname;
                   1863:     if ($fname=~m|/|) {
                   1864:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1865: 	$path.=$fnamepath.'/';
                   1866:     }
1.259     www      1867:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1868:     my $count;
                   1869:     for ($count=4;$count<=$#parts;$count++) {
                   1870:         $filepath.="/$parts[$count]";
                   1871:         if ((-e $filepath)!=1) {
                   1872: 	    mkdir($filepath,0777);
                   1873:         }
                   1874:     }
                   1875: # Save the file
                   1876:     {
1.701     albertel 1877: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1878: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1879: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1880: 	    return '/adm/notfound.html';
                   1881: 	}
                   1882: 	if (!print FH ($env{'form.'.$formname})) {
                   1883: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1884: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1885: 	    return '/adm/notfound.html';
                   1886: 	}
1.570     albertel 1887: 	close(FH);
1.258     www      1888:     }
1.637     raeburn  1889:     if ($parser eq 'parse') {
1.638     albertel 1890:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1891: 						   $codebase);
1.637     raeburn  1892:         unless ($parse_result eq 'ok') {
1.638     albertel 1893:             &logthis('Failed to parse '.$filepath.$file.
                   1894: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1895:         }
                   1896:     }
1.860     raeburn  1897:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1898:         my $input = $filepath.'/'.$file;
                   1899:         my $output = $filepath.'/'.'tn-'.$file;
                   1900:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1901:         system("convert -sample $thumbsize $input $output");
                   1902:         if (-e $filepath.'/'.'tn-'.$file) {
                   1903:             $fetchthumb  = 1; 
                   1904:         }
                   1905:     }
1.858     raeburn  1906:  
1.259     www      1907: # Notify homeserver to grep it
                   1908: #
1.638     albertel 1909:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1910:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1911:     if ($fetchresult eq 'ok') {
1.860     raeburn  1912:         if ($fetchthumb) {
                   1913:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1914:             if ($thumbresult ne 'ok') {
                   1915:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1916:                          $docuhome.': '.$thumbresult);
                   1917:             }
                   1918:         }
1.259     www      1919: #
1.258     www      1920: # Return the URL to it
1.494     albertel 1921:         return '/uploaded/'.$path.$file;
1.263     www      1922:     } else {
1.494     albertel 1923:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1924: 		 ': '.$fetchresult);
1.263     www      1925:         return '/adm/notfound.html';
1.858     raeburn  1926:     }
1.493     albertel 1927: }
                   1928: 
1.637     raeburn  1929: sub extract_embedded_items {
1.648     raeburn  1930:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1931:     my @state = ();
                   1932:     my %javafiles = (
                   1933:                       codebase => '',
                   1934:                       code => '',
                   1935:                       archive => ''
                   1936:                     );
                   1937:     my %mediafiles = (
                   1938:                       src => '',
                   1939:                       movie => '',
                   1940:                      );
1.648     raeburn  1941:     my $p;
                   1942:     if ($content) {
                   1943:         $p = HTML::LCParser->new($content);
                   1944:     } else {
                   1945:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1946:     }
1.641     albertel 1947:     while (my $t=$p->get_token()) {
1.640     albertel 1948: 	if ($t->[0] eq 'S') {
                   1949: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1950: 	    push(@state, $tagname);
1.648     raeburn  1951:             if (lc($tagname) eq 'allow') {
                   1952:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1953:             }
1.640     albertel 1954: 	    if (lc($tagname) eq 'img') {
                   1955: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1956: 	    }
1.886     albertel 1957: 	    if (lc($tagname) eq 'a') {
                   1958: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1959: 	    }
1.645     raeburn  1960:             if (lc($tagname) eq 'script') {
                   1961:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1962:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1963:                 } else {
                   1964:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1965:                 }
                   1966:             }
                   1967:             if (lc($tagname) eq 'link') {
                   1968:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1969:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1970:                 }
                   1971:             }
1.640     albertel 1972: 	    if (lc($tagname) eq 'object' ||
                   1973: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1974: 		foreach my $item (keys(%javafiles)) {
                   1975: 		    $javafiles{$item} = '';
                   1976: 		}
                   1977: 	    }
                   1978: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1979: 		my $name = lc($attr->{'name'});
                   1980: 		foreach my $item (keys(%javafiles)) {
                   1981: 		    if ($name eq $item) {
                   1982: 			$javafiles{$item} = $attr->{'value'};
                   1983: 			last;
                   1984: 		    }
                   1985: 		}
                   1986: 		foreach my $item (keys(%mediafiles)) {
                   1987: 		    if ($name eq $item) {
                   1988: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1989: 			last;
                   1990: 		    }
                   1991: 		}
                   1992: 	    }
                   1993: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1994: 		foreach my $item (keys(%javafiles)) {
                   1995: 		    if ($attr->{$item}) {
                   1996: 			$javafiles{$item} = $attr->{$item};
                   1997: 			last;
                   1998: 		    }
                   1999: 		}
                   2000: 		foreach my $item (keys(%mediafiles)) {
                   2001: 		    if ($attr->{$item}) {
                   2002: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2003: 			last;
                   2004: 		    }
                   2005: 		}
                   2006: 	    }
                   2007: 	} elsif ($t->[0] eq 'E') {
                   2008: 	    my ($tagname) = ($t->[1]);
                   2009: 	    if ($javafiles{'codebase'} ne '') {
                   2010: 		$javafiles{'codebase'} .= '/';
                   2011: 	    }  
                   2012: 	    if (lc($tagname) eq 'applet' ||
                   2013: 		lc($tagname) eq 'object' ||
                   2014: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2015: 		) {
                   2016: 		foreach my $item (keys(%javafiles)) {
                   2017: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2018: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2019: 			&add_filetype($allfiles,$file,$item);
                   2020: 		    }
                   2021: 		}
                   2022: 	    } 
                   2023: 	    pop @state;
                   2024: 	}
                   2025:     }
1.637     raeburn  2026:     return 'ok';
                   2027: }
                   2028: 
1.639     albertel 2029: sub add_filetype {
                   2030:     my ($allfiles,$file,$type)=@_;
                   2031:     if (exists($allfiles->{$file})) {
                   2032: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2033: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2034: 	}
                   2035:     } else {
                   2036: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2037:     }
                   2038: }
                   2039: 
1.493     albertel 2040: sub removeuploadedurl {
                   2041:     my ($url)=@_;
                   2042:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2043:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2044: }
                   2045: 
                   2046: sub removeuserfile {
                   2047:     my ($docuname,$docudom,$fname)=@_;
                   2048:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2049:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2050:     if ($result eq 'ok') {
                   2051:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2052:             my $metafile = $fname.'.meta';
                   2053:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2054: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2055:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2056:             my $sqlresult = 
1.823     albertel 2057:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2058:                                         'portfolio_metadata',$group,
                   2059:                                         'delete');
1.798     raeburn  2060:         }
                   2061:     }
                   2062:     return $result;
1.257     www      2063: }
1.15      www      2064: 
1.530     albertel 2065: sub mkdiruserfile {
                   2066:     my ($docuname,$docudom,$dir)=@_;
                   2067:     my $home=&homeserver($docuname,$docudom);
                   2068:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2069: }
                   2070: 
1.531     albertel 2071: sub renameuserfile {
                   2072:     my ($docuname,$docudom,$old,$new)=@_;
                   2073:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2074:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2075:                         &escape("$old").':'.&escape("$new"),$home);
                   2076:     if ($result eq 'ok') {
                   2077:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2078:             my $oldmeta = $old.'.meta';
                   2079:             my $newmeta = $new.'.meta';
                   2080:             my $metaresult = 
                   2081:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2082: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2083:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2084:             my $sqlresult = 
1.823     albertel 2085:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2086:                                         'portfolio_metadata',$group,
                   2087:                                         'delete');
1.798     raeburn  2088:         }
                   2089:     }
                   2090:     return $result;
1.531     albertel 2091: }
                   2092: 
1.14      www      2093: # ------------------------------------------------------------------------- Log
                   2094: 
                   2095: sub log {
                   2096:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2097:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2098: }
                   2099: 
                   2100: # ------------------------------------------------------------------ Course Log
1.352     www      2101: #
                   2102: # This routine flushes several buffers of non-mission-critical nature
                   2103: #
1.157     www      2104: 
                   2105: sub flushcourselogs {
1.352     www      2106:     &logthis('Flushing log buffers');
                   2107: #
                   2108: # course logs
                   2109: # This is a log of all transactions in a course, which can be used
                   2110: # for data mining purposes
                   2111: #
                   2112: # It also collects the courseid database, which lists last transaction
                   2113: # times and course titles for all courseids
                   2114: #
                   2115:     my %courseidbuffer=();
1.800     albertel 2116:     foreach my $crsid (keys %courselogs) {
1.352     www      2117:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2118: 		          &escape($courselogs{$crsid}),
                   2119: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2120: 	    delete $courselogs{$crsid};
                   2121:         } else {
                   2122:             &logthis('Failed to flush log buffer for '.$crsid);
                   2123:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2124:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2125:                         " exceeded maximum size, deleting.</font>");
                   2126:                delete $courselogs{$crsid};
                   2127:             }
1.352     www      2128:         }
                   2129:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2130:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2131: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2132:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2133:         } else {
                   2134:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2135: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2136:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2137:         }
1.191     harris41 2138:     }
1.352     www      2139: #
                   2140: # Write course id database (reverse lookup) to homeserver of courses 
                   2141: # Is used in pickcourse
                   2142: #
1.840     albertel 2143:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2144:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2145: 		     $crs_home);
1.352     www      2146:     }
                   2147: #
                   2148: # File accesses
                   2149: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2150: #
1.449     matthew  2151:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2152:         if ($entry =~ /___count$/) {
                   2153:             my ($dom,$name);
1.807     albertel 2154:             ($dom,$name,undef)=
1.811     albertel 2155: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2156:             if (! defined($dom) || $dom eq '' || 
                   2157:                 ! defined($name) || $name eq '') {
1.620     albertel 2158:                 my $cid = $env{'request.course.id'};
                   2159:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2160:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2161:             }
1.450     matthew  2162:             my $value = $accesshash{$entry};
                   2163:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2164:             my %temphash=($url => $value);
1.449     matthew  2165:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2166:             if ($result eq 'ok') {
                   2167:                 delete $accesshash{$entry};
                   2168:             } elsif ($result eq 'unknown_cmd') {
                   2169:                 # Target server has old code running on it.
1.450     matthew  2170:                 my %temphash=($entry => $value);
1.449     matthew  2171:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2172:                     delete $accesshash{$entry};
                   2173:                 }
                   2174:             }
                   2175:         } else {
1.811     albertel 2176:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2177:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2178:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2179:                 delete $accesshash{$entry};
                   2180:             }
1.185     www      2181:         }
1.191     harris41 2182:     }
1.352     www      2183: #
                   2184: # Roles
                   2185: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2186: #
1.800     albertel 2187:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2188:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2189: 	    split(/\:/,$entry);
                   2190:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2191:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2192:                 $rudom,$runame) eq 'ok') {
                   2193: 	    delete $userrolehash{$entry};
                   2194:         }
                   2195:     }
1.662     raeburn  2196: #
                   2197: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2198: #
                   2199:     my %domrolebuffer = ();
                   2200:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2201:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2202:         if ($domrolebuffer{$rudom}) {
                   2203:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2204:                       '='.&escape($domainrolehash{$entry});
                   2205:         } else {
                   2206:             $domrolebuffer{$rudom}.=&escape($entry).
                   2207:                       '='.&escape($domainrolehash{$entry});
                   2208:         }
                   2209:         delete $domainrolehash{$entry};
                   2210:     }
                   2211:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2212: 	my %servers = &get_servers($dom,'library');
                   2213: 	foreach my $tryserver (keys(%servers)) {
                   2214: 	    unless (&reply('domroleput:'.$dom.':'.
                   2215: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2216: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2217: 	    }
1.662     raeburn  2218:         }
                   2219:     }
1.186     www      2220:     $dumpcount++;
1.157     www      2221: }
                   2222: 
                   2223: sub courselog {
                   2224:     my $what=shift;
1.158     www      2225:     $what=time.':'.$what;
1.620     albertel 2226:     unless ($env{'request.course.id'}) { return ''; }
                   2227:     $coursedombuf{$env{'request.course.id'}}=
                   2228:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2229:     $coursenumbuf{$env{'request.course.id'}}=
                   2230:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2231:     $coursehombuf{$env{'request.course.id'}}=
                   2232:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2233:     $coursedescrbuf{$env{'request.course.id'}}=
                   2234:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2235:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2236:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2237:     $courseownerbuf{$env{'request.course.id'}}=
                   2238:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2239:     $coursetypebuf{$env{'request.course.id'}}=
                   2240:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2241:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2242: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2243:     } else {
1.620     albertel 2244: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2245:     }
1.620     albertel 2246:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2247: 	&flushcourselogs();
                   2248:     }
1.158     www      2249: }
                   2250: 
                   2251: sub courseacclog {
                   2252:     my $fnsymb=shift;
1.620     albertel 2253:     unless ($env{'request.course.id'}) { return ''; }
                   2254:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2255:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2256:         $what.=':POST';
1.583     matthew  2257:         # FIXME: Probably ought to escape things....
1.800     albertel 2258: 	foreach my $key (keys(%env)) {
                   2259:             if ($key=~/^form\.(.*)/) {
                   2260: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2261:             }
1.191     harris41 2262:         }
1.583     matthew  2263:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2264:         # FIXME: We should not be depending on a form parameter that someone
                   2265:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2266:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2267:             $what.= ':POST';
                   2268:             # FIXME: Probably ought to escape things....
                   2269:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2270:                                  'crsdiscuss') {
1.620     albertel 2271:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2272:             }
                   2273:         }
1.158     www      2274:     }
                   2275:     &courselog($what);
1.149     www      2276: }
                   2277: 
1.185     www      2278: sub countacc {
                   2279:     my $url=&declutter(shift);
1.458     matthew  2280:     return if (! defined($url) || $url eq '');
1.620     albertel 2281:     unless ($env{'request.course.id'}) { return ''; }
                   2282:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2283:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2284:     $accesshash{$key}++;
1.185     www      2285: }
1.349     www      2286: 
1.361     www      2287: sub linklog {
                   2288:     my ($from,$to)=@_;
                   2289:     $from=&declutter($from);
                   2290:     $to=&declutter($to);
                   2291:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2292:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2293: }
                   2294:   
1.349     www      2295: sub userrolelog {
                   2296:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2297:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2298:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2299:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2300:         ($trole=~/^ta/)) {
1.350     www      2301:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2302:        $userrolehash
                   2303:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2304:                     =$tend.':'.$tstart;
1.662     raeburn  2305:     }
1.898     albertel 2306:     if (($env{'request.role'} =~ /dc\./) &&
                   2307: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2308: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2309: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2310:        $userrolehash
                   2311:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2312:                     =$tend.':'.$tstart;
                   2313:     }
1.662     raeburn  2314:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2315:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2316:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2317:         ($trole=~/^sc/)) {
                   2318:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2319:        $domainrolehash
                   2320:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2321:                     = $tend.':'.$tstart;
                   2322:     }
1.351     www      2323: }
                   2324: 
                   2325: sub get_course_adv_roles {
                   2326:     my $cid=shift;
1.620     albertel 2327:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2328:     my %coursehash=&coursedescription($cid);
1.470     www      2329:     my %nothide=();
1.800     albertel 2330:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2331: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2332:     }
1.351     www      2333:     my %returnhash=();
                   2334:     my %dumphash=
                   2335:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2336:     my $now=time;
1.800     albertel 2337:     foreach my $entry (keys %dumphash) {
                   2338: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2339:         if (($tstart) && ($tstart<0)) { next; }
                   2340:         if (($tend) && ($tend<$now)) { next; }
                   2341:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2342:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2343: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2344: 	if ((&privileged($username,$domain)) && 
                   2345: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2346: 	if ($role eq 'cr') { next; }
1.351     www      2347:         my $key=&plaintext($role);
                   2348:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2349:         if ($returnhash{$key}) {
                   2350: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2351:         } else {
                   2352:             $returnhash{$key}=$username.':'.$domain;
                   2353:         }
1.400     www      2354:      }
                   2355:     return %returnhash;
                   2356: }
                   2357: 
                   2358: sub get_my_roles {
1.858     raeburn  2359:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2360:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2361:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2362:     my %dumphash;
                   2363:     if ($context eq 'userroles') { 
                   2364:         %dumphash = &dump('roles',$udom,$uname);
                   2365:     } else {
                   2366:         %dumphash=
1.400     www      2367:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2368:     }
1.400     www      2369:     my %returnhash=();
                   2370:     my $now=time;
1.800     albertel 2371:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2372:         my ($role,$tend,$tstart);
                   2373:         if ($context eq 'userroles') {
                   2374: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2375:         } else {
                   2376:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2377:         }
1.400     www      2378:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2379:         my $status = 'active';
                   2380:         if (($tend) && ($tend<$now)) {
                   2381:             $status = 'previous';
                   2382:         } 
                   2383:         if (($tstart) && ($now<$tstart)) {
                   2384:             $status = 'future';
                   2385:         }
                   2386:         if (ref($types) eq 'ARRAY') {
                   2387:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2388:                 next;
                   2389:             } 
                   2390:         } else {
                   2391:             if ($status ne 'active') {
                   2392:                 next;
                   2393:             }
                   2394:         }
1.867     raeburn  2395:         my ($rolecode,$username,$domain,$section,$area);
                   2396:         if ($context eq 'userroles') {
                   2397:             ($area,$rolecode) = split(/_/,$entry);
                   2398:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2399:         } else {
                   2400:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2401:         }
1.832     raeburn  2402:         if (ref($roledoms) eq 'ARRAY') {
                   2403:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2404:                 next;
                   2405:             }
                   2406:         }
                   2407:         if (ref($roles) eq 'ARRAY') {
                   2408:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2409:                 next;
                   2410:             }
1.867     raeburn  2411:         }
1.400     www      2412: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2413:     }
1.373     www      2414:     return %returnhash;
1.399     www      2415: }
                   2416: 
                   2417: # ----------------------------------------------------- Frontpage Announcements
                   2418: #
                   2419: #
                   2420: 
                   2421: sub postannounce {
                   2422:     my ($server,$text)=@_;
1.844     albertel 2423:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2424:     unless ($text=~/\w/) { $text=''; }
                   2425:     return &reply('setannounce:'.&escape($text),$server);
                   2426: }
                   2427: 
                   2428: sub getannounce {
1.448     albertel 2429: 
                   2430:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2431: 	my $announcement='';
1.800     albertel 2432: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2433: 	close($fh);
1.399     www      2434: 	if ($announcement=~/\w/) { 
                   2435: 	    return 
                   2436:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2437:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2438: 	} else {
                   2439: 	    return '';
                   2440: 	}
                   2441:     } else {
                   2442: 	return '';
                   2443:     }
1.351     www      2444: }
1.353     www      2445: 
                   2446: # ---------------------------------------------------------- Course ID routines
                   2447: # Deal with domain's nohist_courseid.db files
                   2448: #
                   2449: 
                   2450: sub courseidput {
                   2451:     my ($domain,$what,$coursehome)=@_;
                   2452:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2453: }
                   2454: 
                   2455: sub courseiddump {
1.791     raeburn  2456:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2457:     my %returnhash=();
1.355     www      2458:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2459:     my %libserv = &all_library();
                   2460:     foreach my $tryserver (keys(%libserv)) {
                   2461:         if ( (  $hostidflag == 1 
                   2462: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2463: 	     || (!defined($hostidflag)) ) {
                   2464: 
                   2465: 	    if ($domfilter eq ''
                   2466: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2467: 	        foreach my $line (
1.844     albertel 2468:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2469: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2470:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2471:                                $tryserver))) {
1.800     albertel 2472: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2473:                     if (($key) && ($value)) {
1.516     raeburn  2474: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2475:                     }
1.353     www      2476:                 }
                   2477:             }
                   2478:         }
                   2479:     }
                   2480:     return %returnhash;
                   2481: }
                   2482: 
1.658     raeburn  2483: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2484: 
                   2485: sub dcmailput {
1.685     raeburn  2486:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2487:     my $status = &Apache::lonnet::critical(
1.740     www      2488:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2489:        &escape($message),$server);
1.662     raeburn  2490:     return $status;
                   2491: }
                   2492: 
1.658     raeburn  2493: sub dcmaildump {
                   2494:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2495:     my %returnhash=();
1.846     albertel 2496: 
                   2497:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2498:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2499:                                                          &escape($enddate).':';
                   2500: 	my @esc_senders=map { &escape($_)} @$senders;
                   2501: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2502: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2503:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2504:             if (($key) && ($value)) {
                   2505:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2506:             }
                   2507:         }
                   2508:     }
                   2509:     return %returnhash;
                   2510: }
1.662     raeburn  2511: # ---------------------------------------------------------- Domain roles
                   2512: 
                   2513: sub get_domain_roles {
                   2514:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2515:     if (undef($startdate) || $startdate eq '') {
                   2516:         $startdate = '.';
                   2517:     }
                   2518:     if (undef($enddate) || $enddate eq '') {
                   2519:         $enddate = '.';
                   2520:     }
                   2521:     my $rolelist = join(':',@{$roles});
                   2522:     my %personnel = ();
1.841     albertel 2523: 
                   2524:     my %servers = &get_servers($dom,'library');
                   2525:     foreach my $tryserver (keys(%servers)) {
                   2526: 	%{$personnel{$tryserver}}=();
                   2527: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2528: 					    &escape($startdate).':'.
                   2529: 					    &escape($enddate).':'.
                   2530: 					    &escape($rolelist), $tryserver))) {
                   2531: 	    my ($key,$value) = split(/\=/,$line,2);
                   2532: 	    if (($key) && ($value)) {
                   2533: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2534: 	    }
                   2535: 	}
1.662     raeburn  2536:     }
                   2537:     return %personnel;
                   2538: }
1.658     raeburn  2539: 
1.149     www      2540: # ----------------------------------------------------------- Check out an item
                   2541: 
1.504     albertel 2542: sub get_first_access {
                   2543:     my ($type,$argsymb)=@_;
1.790     albertel 2544:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2545:     if ($argsymb) { $symb=$argsymb; }
                   2546:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2547:     if ($type eq 'map') {
                   2548: 	$res=&symbread($map);
                   2549:     } else {
                   2550: 	$res=$symb;
                   2551:     }
                   2552:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2553:     return $times{"$courseid\0$res"};
1.504     albertel 2554: }
                   2555: 
                   2556: sub set_first_access {
                   2557:     my ($type)=@_;
1.790     albertel 2558:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2559:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2560:     if ($type eq 'map') {
                   2561: 	$res=&symbread($map);
                   2562:     } else {
                   2563: 	$res=$symb;
                   2564:     }
                   2565:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2566:     if (!$firstaccess) {
1.588     albertel 2567: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2568:     }
                   2569:     return 'already_set';
1.504     albertel 2570: }
                   2571: 
1.149     www      2572: sub checkout {
                   2573:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2574:     my $now=time;
                   2575:     my $lonhost=$perlvar{'lonHostID'};
                   2576:     my $infostr=&escape(
1.234     www      2577:                  'CHECKOUTTOKEN&'.
1.149     www      2578:                  $tuname.'&'.
                   2579:                  $tudom.'&'.
                   2580:                  $tcrsid.'&'.
                   2581:                  $symb.'&'.
                   2582: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2583:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2584:     if ($token=~/^error\:/) { 
1.672     albertel 2585:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2586:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2587:                  "</font>");
                   2588:         return ''; 
                   2589:     }
                   2590: 
1.149     www      2591:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2592:     $token=~tr/a-z/A-Z/;
                   2593: 
1.153     www      2594:     my %infohash=('resource.0.outtoken' => $token,
                   2595:                   'resource.0.checkouttime' => $now,
                   2596:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2597: 
                   2598:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2599:        return '';
1.151     www      2600:     } else {
1.672     albertel 2601:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2602:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2603:                  "</font>");
1.149     www      2604:     }    
                   2605: 
                   2606:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2607:                          &escape('Checkout '.$infostr.' - '.
                   2608:                                                  $token)) ne 'ok') {
                   2609: 	return '';
1.151     www      2610:     } else {
1.672     albertel 2611:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2612:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2613:                  "</font>");
1.149     www      2614:     }
1.151     www      2615:     return $token;
1.149     www      2616: }
                   2617: 
                   2618: # ------------------------------------------------------------ Check in an item
                   2619: 
                   2620: sub checkin {
                   2621:     my $token=shift;
1.150     www      2622:     my $now=time;
                   2623:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2624:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2625:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2626:     $dtoken=~s/\W/\_/g;
1.234     www      2627:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2628:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2629: 
1.154     www      2630:     unless (($tuname) && ($tudom)) {
                   2631:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2632:         return '';
                   2633:     }
                   2634:     
                   2635:     unless (&allowed('mgr',$tcrsid)) {
                   2636:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2637:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2638:         return '';
                   2639:     }
                   2640: 
1.153     www      2641:     my %infohash=('resource.0.intoken' => $token,
                   2642:                   'resource.0.checkintime' => $now,
                   2643:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2644: 
                   2645:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2646:        return '';
                   2647:     }    
                   2648: 
                   2649:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2650:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2651: 	return '';
                   2652:     }
                   2653: 
                   2654:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2655: }
                   2656: 
                   2657: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2658: 
                   2659: sub expirespread {
                   2660:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2661:     my $cid=$env{'request.course.id'}; 
1.110     www      2662:     if ($cid) {
                   2663:        my $now=time;
                   2664:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2665:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2666:                             $env{'course.'.$cid.'.num'}.
1.110     www      2667: 	        	    ':nohist_expirationdates:'.
                   2668:                             &escape($key).'='.$now,
1.620     albertel 2669:                             $env{'course.'.$cid.'.home'})
1.110     www      2670:     }
                   2671:     return 'ok';
1.14      www      2672: }
                   2673: 
1.109     www      2674: # ----------------------------------------------------- Devalidate Spreadsheets
                   2675: 
                   2676: sub devalidate {
1.325     www      2677:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2678:     my $cid=$env{'request.course.id'}; 
1.109     www      2679:     if ($cid) {
1.391     matthew  2680:         # delete the stored spreadsheets for
                   2681:         # - the student level sheet of this user in course's homespace
                   2682:         # - the assessment level sheet for this resource 
                   2683:         #   for this user in user's homespace
1.553     albertel 2684: 	# - current conditional state info
1.325     www      2685: 	my $key=$uname.':'.$udom.':';
1.109     www      2686:         my $status=
1.299     matthew  2687: 	    &del('nohist_calculatedsheets',
1.391     matthew  2688: 		 [$key.'studentcalc:'],
1.620     albertel 2689: 		 $env{'course.'.$cid.'.domain'},
                   2690: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2691: 		.' '.
                   2692: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2693: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2694:         unless ($status eq 'ok ok') {
                   2695:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2696:                     $uname.' at '.$udom.' for '.
1.109     www      2697: 		    $symb.': '.$status);
1.133     albertel 2698:         }
1.553     albertel 2699: 	&delenv('user.state.'.$cid);
1.109     www      2700:     }
                   2701: }
                   2702: 
1.265     albertel 2703: sub get_scalar {
                   2704:     my ($string,$end) = @_;
                   2705:     my $value;
                   2706:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2707: 	$value = $1;
                   2708:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2709: 	$value = $1;
                   2710:     }
                   2711:     return &unescape($value);
                   2712: }
                   2713: 
                   2714: sub array2str {
                   2715:   my (@array) = @_;
                   2716:   my $result=&arrayref2str(\@array);
                   2717:   $result=~s/^__ARRAY_REF__//;
                   2718:   $result=~s/__END_ARRAY_REF__$//;
                   2719:   return $result;
                   2720: }
                   2721: 
1.204     albertel 2722: sub arrayref2str {
                   2723:   my ($arrayref) = @_;
1.265     albertel 2724:   my $result='__ARRAY_REF__';
1.204     albertel 2725:   foreach my $elem (@$arrayref) {
1.265     albertel 2726:     if(ref($elem) eq 'ARRAY') {
                   2727:       $result.=&arrayref2str($elem).'&';
                   2728:     } elsif(ref($elem) eq 'HASH') {
                   2729:       $result.=&hashref2str($elem).'&';
                   2730:     } elsif(ref($elem)) {
                   2731:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2732:     } else {
                   2733:       $result.=&escape($elem).'&';
                   2734:     }
                   2735:   }
                   2736:   $result=~s/\&$//;
1.265     albertel 2737:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2738:   return $result;
                   2739: }
                   2740: 
1.168     albertel 2741: sub hash2str {
1.204     albertel 2742:   my (%hash) = @_;
                   2743:   my $result=&hashref2str(\%hash);
1.265     albertel 2744:   $result=~s/^__HASH_REF__//;
                   2745:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2746:   return $result;
                   2747: }
                   2748: 
                   2749: sub hashref2str {
                   2750:   my ($hashref)=@_;
1.265     albertel 2751:   my $result='__HASH_REF__';
1.800     albertel 2752:   foreach my $key (sort(keys(%$hashref))) {
                   2753:     if (ref($key) eq 'ARRAY') {
                   2754:       $result.=&arrayref2str($key).'=';
                   2755:     } elsif (ref($key) eq 'HASH') {
                   2756:       $result.=&hashref2str($key).'=';
                   2757:     } elsif (ref($key)) {
1.265     albertel 2758:       $result.='=';
1.800     albertel 2759:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2760:     } else {
1.800     albertel 2761: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2762:     }
                   2763: 
1.800     albertel 2764:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2765:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2766:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2767:       $result.=&hashref2str($hashref->{$key}).'&';
                   2768:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2769:        $result.='&';
1.800     albertel 2770:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2771:     } else {
1.800     albertel 2772:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2773:     }
                   2774:   }
1.168     albertel 2775:   $result=~s/\&$//;
1.265     albertel 2776:   $result .= '__END_HASH_REF__';
1.168     albertel 2777:   return $result;
                   2778: }
                   2779: 
                   2780: sub str2hash {
1.265     albertel 2781:     my ($string)=@_;
                   2782:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2783:     return %$hash;
                   2784: }
                   2785: 
                   2786: sub str2hashref {
1.168     albertel 2787:   my ($string) = @_;
1.265     albertel 2788: 
                   2789:   my %hash;
                   2790: 
                   2791:   if($string !~ /^__HASH_REF__/) {
                   2792:       if (! ($string eq '' || !defined($string))) {
                   2793: 	  $hash{'error'}='Not hash reference';
                   2794:       }
                   2795:       return (\%hash, $string);
                   2796:   }
                   2797: 
                   2798:   $string =~ s/^__HASH_REF__//;
                   2799: 
                   2800:   while($string !~ /^__END_HASH_REF__/) {
                   2801:       #key
                   2802:       my $key='';
                   2803:       if($string =~ /^__HASH_REF__/) {
                   2804:           ($key, $string)=&str2hashref($string);
                   2805:           if(defined($key->{'error'})) {
                   2806:               $hash{'error'}='Bad data';
                   2807:               return (\%hash, $string);
                   2808:           }
                   2809:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2810:           ($key, $string)=&str2arrayref($string);
                   2811:           if($key->[0] eq 'Array reference error') {
                   2812:               $hash{'error'}='Bad data';
                   2813:               return (\%hash, $string);
                   2814:           }
                   2815:       } else {
                   2816:           $string =~ s/^(.*?)=//;
1.267     albertel 2817: 	  $key=&unescape($1);
1.265     albertel 2818:       }
                   2819:       $string =~ s/^=//;
                   2820: 
                   2821:       #value
                   2822:       my $value='';
                   2823:       if($string =~ /^__HASH_REF__/) {
                   2824:           ($value, $string)=&str2hashref($string);
                   2825:           if(defined($value->{'error'})) {
                   2826:               $hash{'error'}='Bad data';
                   2827:               return (\%hash, $string);
                   2828:           }
                   2829:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2830:           ($value, $string)=&str2arrayref($string);
                   2831:           if($value->[0] eq 'Array reference error') {
                   2832:               $hash{'error'}='Bad data';
                   2833:               return (\%hash, $string);
                   2834:           }
                   2835:       } else {
                   2836: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2837:       }
                   2838:       $string =~ s/^&//;
                   2839: 
                   2840:       $hash{$key}=$value;
1.204     albertel 2841:   }
1.265     albertel 2842: 
                   2843:   $string =~ s/^__END_HASH_REF__//;
                   2844: 
                   2845:   return (\%hash, $string);
1.204     albertel 2846: }
                   2847: 
                   2848: sub str2array {
1.265     albertel 2849:     my ($string)=@_;
                   2850:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2851:     return @$array;
                   2852: }
                   2853: 
                   2854: sub str2arrayref {
1.204     albertel 2855:   my ($string) = @_;
1.265     albertel 2856:   my @array;
                   2857: 
                   2858:   if($string !~ /^__ARRAY_REF__/) {
                   2859:       if (! ($string eq '' || !defined($string))) {
                   2860: 	  $array[0]='Array reference error';
                   2861:       }
                   2862:       return (\@array, $string);
                   2863:   }
                   2864: 
                   2865:   $string =~ s/^__ARRAY_REF__//;
                   2866: 
                   2867:   while($string !~ /^__END_ARRAY_REF__/) {
                   2868:       my $value='';
                   2869:       if($string =~ /^__HASH_REF__/) {
                   2870:           ($value, $string)=&str2hashref($string);
                   2871:           if(defined($value->{'error'})) {
                   2872:               $array[0] ='Array reference error';
                   2873:               return (\@array, $string);
                   2874:           }
                   2875:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2876:           ($value, $string)=&str2arrayref($string);
                   2877:           if($value->[0] eq 'Array reference error') {
                   2878:               $array[0] ='Array reference error';
                   2879:               return (\@array, $string);
                   2880:           }
                   2881:       } else {
                   2882: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2883:       }
                   2884:       $string =~ s/^&//;
                   2885: 
                   2886:       push(@array, $value);
1.191     harris41 2887:   }
1.265     albertel 2888: 
                   2889:   $string =~ s/^__END_ARRAY_REF__//;
                   2890: 
                   2891:   return (\@array, $string);
1.168     albertel 2892: }
                   2893: 
1.167     albertel 2894: # -------------------------------------------------------------------Temp Store
                   2895: 
1.168     albertel 2896: sub tmpreset {
                   2897:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2898:   if (!$symb) {
                   2899:     $symb=&symbread();
1.620     albertel 2900:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2901:   }
                   2902:   $symb=escape($symb);
                   2903: 
1.620     albertel 2904:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2905:   $namespace=~s/\//\_/g;
                   2906:   $namespace=~s/\W//g;
                   2907: 
1.620     albertel 2908:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2909:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2910:   if ($domain eq 'public' && $stuname eq 'public') {
                   2911:       $stuname=$ENV{'REMOTE_ADDR'};
                   2912:   }
1.168     albertel 2913:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2914:   my %hash;
                   2915:   if (tie(%hash,'GDBM_File',
                   2916: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2917: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2918:     foreach my $key (keys %hash) {
1.180     albertel 2919:       if ($key=~ /:$symb/) {
1.168     albertel 2920: 	delete($hash{$key});
                   2921:       }
                   2922:     }
                   2923:   }
                   2924: }
                   2925: 
1.167     albertel 2926: sub tmpstore {
1.168     albertel 2927:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2928: 
                   2929:   if (!$symb) {
                   2930:     $symb=&symbread();
1.620     albertel 2931:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2932:   }
                   2933:   $symb=escape($symb);
                   2934: 
                   2935:   if (!$namespace) {
                   2936:     # I don't think we would ever want to store this for a course.
                   2937:     # it seems this will only be used if we don't have a course.
1.620     albertel 2938:     #$namespace=$env{'request.course.id'};
1.168     albertel 2939:     #if (!$namespace) {
1.620     albertel 2940:       $namespace=$env{'request.state'};
1.168     albertel 2941:     #}
                   2942:   }
                   2943:   $namespace=~s/\//\_/g;
                   2944:   $namespace=~s/\W//g;
1.620     albertel 2945:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2946:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2947:   if ($domain eq 'public' && $stuname eq 'public') {
                   2948:       $stuname=$ENV{'REMOTE_ADDR'};
                   2949:   }
1.168     albertel 2950:   my $now=time;
                   2951:   my %hash;
                   2952:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2953:   if (tie(%hash,'GDBM_File',
                   2954: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2955: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2956:     $hash{"version:$symb"}++;
                   2957:     my $version=$hash{"version:$symb"};
                   2958:     my $allkeys=''; 
                   2959:     foreach my $key (keys(%$storehash)) {
                   2960:       $allkeys.=$key.':';
1.591     albertel 2961:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2962:     }
                   2963:     $hash{"$version:$symb:timestamp"}=$now;
                   2964:     $allkeys.='timestamp';
                   2965:     $hash{"$version:keys:$symb"}=$allkeys;
                   2966:     if (untie(%hash)) {
                   2967:       return 'ok';
                   2968:     } else {
                   2969:       return "error:$!";
                   2970:     }
                   2971:   } else {
                   2972:     return "error:$!";
                   2973:   }
                   2974: }
1.167     albertel 2975: 
1.168     albertel 2976: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2977: 
1.168     albertel 2978: sub tmprestore {
                   2979:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2980: 
1.168     albertel 2981:   if (!$symb) {
                   2982:     $symb=&symbread();
1.620     albertel 2983:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2984:   }
                   2985:   $symb=escape($symb);
                   2986: 
1.620     albertel 2987:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2988: 
1.620     albertel 2989:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2990:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2991:   if ($domain eq 'public' && $stuname eq 'public') {
                   2992:       $stuname=$ENV{'REMOTE_ADDR'};
                   2993:   }
1.168     albertel 2994:   my %returnhash;
                   2995:   $namespace=~s/\//\_/g;
                   2996:   $namespace=~s/\W//g;
                   2997:   my %hash;
                   2998:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2999:   if (tie(%hash,'GDBM_File',
                   3000: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3001: 	  &GDBM_READER(),0640)) {
1.168     albertel 3002:     my $version=$hash{"version:$symb"};
                   3003:     $returnhash{'version'}=$version;
                   3004:     my $scope;
                   3005:     for ($scope=1;$scope<=$version;$scope++) {
                   3006:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3007:       my @keys=split(/:/,$vkeys);
                   3008:       my $key;
                   3009:       $returnhash{"$scope:keys"}=$vkeys;
                   3010:       foreach $key (@keys) {
1.591     albertel 3011: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3012: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3013:       }
                   3014:     }
1.168     albertel 3015:     if (!(untie(%hash))) {
                   3016:       return "error:$!";
                   3017:     }
                   3018:   } else {
                   3019:     return "error:$!";
                   3020:   }
                   3021:   return %returnhash;
1.167     albertel 3022: }
                   3023: 
1.9       www      3024: # ----------------------------------------------------------------------- Store
                   3025: 
                   3026: sub store {
1.124     www      3027:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3028:     my $home='';
                   3029: 
1.168     albertel 3030:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3031: 
1.213     www      3032:     $symb=&symbclean($symb);
1.122     albertel 3033:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3034: 
1.620     albertel 3035:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3036:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3037: 
                   3038:     &devalidate($symb,$stuname,$domain);
1.109     www      3039: 
                   3040:     $symb=escape($symb);
1.187     www      3041:     if (!$namespace) { 
1.620     albertel 3042:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3043:           return ''; 
                   3044:        } 
                   3045:     }
1.620     albertel 3046:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3047: 
                   3048:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3049:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3050: 
1.12      www      3051:     my $namevalue='';
1.800     albertel 3052:     foreach my $key (keys(%$storehash)) {
                   3053:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3054:     }
1.12      www      3055:     $namevalue=~s/\&$//;
1.187     www      3056:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3057:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3058: }
                   3059: 
1.47      www      3060: # -------------------------------------------------------------- Critical Store
                   3061: 
                   3062: sub cstore {
1.124     www      3063:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3064:     my $home='';
                   3065: 
1.168     albertel 3066:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3067: 
1.213     www      3068:     $symb=&symbclean($symb);
1.122     albertel 3069:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3070: 
1.620     albertel 3071:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3072:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3073: 
                   3074:     &devalidate($symb,$stuname,$domain);
1.109     www      3075: 
                   3076:     $symb=escape($symb);
1.187     www      3077:     if (!$namespace) { 
1.620     albertel 3078:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3079:           return ''; 
                   3080:        } 
                   3081:     }
1.620     albertel 3082:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3083: 
                   3084:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3085:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3086: 
1.47      www      3087:     my $namevalue='';
1.800     albertel 3088:     foreach my $key (keys(%$storehash)) {
                   3089:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3090:     }
1.47      www      3091:     $namevalue=~s/\&$//;
1.187     www      3092:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3093:     return critical
                   3094:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3095: }
                   3096: 
1.9       www      3097: # --------------------------------------------------------------------- Restore
                   3098: 
                   3099: sub restore {
1.124     www      3100:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3101:     my $home='';
                   3102: 
1.168     albertel 3103:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3104: 
1.122     albertel 3105:     if (!$symb) {
                   3106:       unless ($symb=escape(&symbread())) { return ''; }
                   3107:     } else {
1.213     www      3108:       $symb=&escape(&symbclean($symb));
1.122     albertel 3109:     }
1.188     www      3110:     if (!$namespace) { 
1.620     albertel 3111:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3112:           return ''; 
                   3113:        } 
                   3114:     }
1.620     albertel 3115:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3116:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3117:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3118:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3119: 
1.12      www      3120:     my %returnhash=();
1.800     albertel 3121:     foreach my $line (split(/\&/,$answer)) {
                   3122: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3123:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3124:     }
1.75      www      3125:     my $version;
                   3126:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3127:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3128:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3129:        }
1.75      www      3130:     }
1.13      www      3131:     return %returnhash;
1.34      www      3132: }
                   3133: 
                   3134: # ---------------------------------------------------------- Course Description
                   3135: 
                   3136: sub coursedescription {
1.731     albertel 3137:     my ($courseid,$args)=@_;
1.34      www      3138:     $courseid=~s/^\///;
1.49      www      3139:     $courseid=~s/\_/\//g;
1.34      www      3140:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3141:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3142:     my $normalid=$cdomain.'_'.$cnum;
                   3143:     # need to always cache even if we get errors otherwise we keep 
                   3144:     # trying and trying and trying to get the course description.
                   3145:     my %envhash=();
                   3146:     my %returnhash=();
1.731     albertel 3147:     
                   3148:     my $expiretime=600;
                   3149:     if ($env{'request.course.id'} eq $normalid) {
                   3150: 	$expiretime=120;
                   3151:     }
                   3152: 
                   3153:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3154:     if (!$args->{'freshen_cache'}
                   3155: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3156: 	foreach my $key (keys(%env)) {
                   3157: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3158: 	    my ($setting) = $1;
                   3159: 	    $returnhash{$setting} = $env{$key};
                   3160: 	}
                   3161: 	return %returnhash;
                   3162:     }
                   3163: 
                   3164:     # get the data agin
                   3165:     if (!$args->{'one_time'}) {
                   3166: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3167:     }
1.811     albertel 3168: 
1.34      www      3169:     if ($chome ne 'no_host') {
1.302     albertel 3170:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3171:        if (!exists($returnhash{'con_lost'})) {
                   3172:            $returnhash{'home'}= $chome;
                   3173: 	   $returnhash{'domain'} = $cdomain;
                   3174: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3175:            if (!defined($returnhash{'type'})) {
                   3176:                $returnhash{'type'} = 'Course';
                   3177:            }
1.130     albertel 3178:            while (my ($name,$value) = each %returnhash) {
1.53      www      3179:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3180:            }
1.270     www      3181:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3182:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3183: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3184:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3185:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3186:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3187:        }
                   3188:     }
1.731     albertel 3189:     if (!$args->{'one_time'}) {
                   3190: 	&appenv(%envhash);
                   3191:     }
1.302     albertel 3192:     return %returnhash;
1.461     www      3193: }
                   3194: 
                   3195: # -------------------------------------------------See if a user is privileged
                   3196: 
                   3197: sub privileged {
                   3198:     my ($username,$domain)=@_;
                   3199:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3200: 			&homeserver($username,$domain));
                   3201:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3202:     my $now=time;
                   3203:     if ($rolesdump ne '') {
1.800     albertel 3204:         foreach my $entry (split(/&/,$rolesdump)) {
                   3205: 	    if ($entry!~/^rolesdef_/) {
                   3206: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3207: 		$area=~s/\_\w\w$//;
                   3208: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3209: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3210: 		    my $active=1;
                   3211: 		    if ($tend) {
                   3212: 			if ($tend<$now) { $active=0; }
                   3213: 		    }
                   3214: 		    if ($tstart) {
                   3215: 			if ($tstart>$now) { $active=0; }
                   3216: 		    }
                   3217: 		    if ($active) { return 1; }
                   3218: 		}
                   3219: 	    }
                   3220: 	}
                   3221:     }
                   3222:     return 0;
1.9       www      3223: }
1.1       albertel 3224: 
1.103     harris41 3225: # -------------------------------------------------------- Get user privileges
1.11      www      3226: 
                   3227: sub rolesinit {
                   3228:     my ($domain,$username,$authhost)=@_;
                   3229:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3230:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3231:     my %allroles=();
1.678     raeburn  3232:     my %allgroups=();   
1.11      www      3233:     my $now=time;
1.743     albertel 3234:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3235:     my $group_privs;
1.11      www      3236: 
                   3237:     if ($rolesdump ne '') {
1.800     albertel 3238:         foreach my $entry (split(/&/,$rolesdump)) {
                   3239: 	  if ($entry!~/^rolesdef_/) {
                   3240:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3241: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3242:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3243: 	    if ($role=~/^cr/) { 
1.807     albertel 3244: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3245: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3246: 		    ($tend,$tstart)=split('_',$trest);
                   3247: 		} else {
                   3248: 		    $trole=$role;
                   3249: 		}
1.678     raeburn  3250:             } elsif ($role =~ m|^gr/|) {
                   3251:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3252:                 ($trole,$group_privs) = split(/\//,$trole);
                   3253:                 $group_privs = &unescape($group_privs);
1.587     albertel 3254: 	    } else {
                   3255: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3256: 	    }
1.743     albertel 3257: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3258: 					 $username);
                   3259: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3260:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3261:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3262:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3263: 		my $spec=$trole.'.'.$area;
                   3264: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3265: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3266:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3267:                 } elsif ($trole eq 'gr') {
                   3268:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3269: 		} else {
1.567     raeburn  3270:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3271: 		}
1.12      www      3272:             }
1.662     raeburn  3273:           }
1.191     harris41 3274:         }
1.743     albertel 3275:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3276:         $userroles{'user.adv'}    = $adv;
                   3277: 	$userroles{'user.author'} = $author;
1.620     albertel 3278:         $env{'user.adv'}=$adv;
1.11      www      3279:     }
1.743     albertel 3280:     return \%userroles;  
1.11      www      3281: }
                   3282: 
1.567     raeburn  3283: sub set_arearole {
                   3284:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3285: # log the associated role with the area
                   3286:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3287:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3288: }
                   3289: 
                   3290: sub custom_roleprivs {
                   3291:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3292:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3293:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3294:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3295:         my ($rdummy,$roledef)=
                   3296:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3297:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3298:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3299:             if (defined($syspriv)) {
                   3300:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3301:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3302:             }
                   3303:             if ($tdomain ne '') {
                   3304:                 if (defined($dompriv)) {
                   3305:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3306:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3307:                 }
                   3308:                 if (($trest ne '') && (defined($coursepriv))) {
                   3309:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3310:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3311:                 }
                   3312:             }
                   3313:         }
                   3314:     }
                   3315: }
                   3316: 
1.678     raeburn  3317: sub group_roleprivs {
                   3318:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3319:     my $access = 1;
                   3320:     my $now = time;
                   3321:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3322:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3323:     if ($access) {
1.811     albertel 3324:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3325:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3326:     }
                   3327: }
1.567     raeburn  3328: 
                   3329: sub standard_roleprivs {
                   3330:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3331:     if (defined($pr{$trole.':s'})) {
                   3332:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3333:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3334:     }
                   3335:     if ($tdomain ne '') {
                   3336:         if (defined($pr{$trole.':d'})) {
                   3337:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3338:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3339:         }
                   3340:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3341:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3342:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3343:         }
                   3344:     }
                   3345: }
                   3346: 
                   3347: sub set_userprivs {
1.678     raeburn  3348:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3349:     my $author=0;
                   3350:     my $adv=0;
1.678     raeburn  3351:     my %grouproles = ();
                   3352:     if (keys(%{$allgroups}) > 0) {
                   3353:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3354:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3355:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3356:                 $trole = $1;
                   3357:                 $area = $2;
1.681     raeburn  3358:                 $sec = $3;
                   3359:                 $extendedarea = $area.$sec;
                   3360:                 if (exists($$allgroups{$area})) {
                   3361:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3362:                         my $spec = $trole.'.'.$extendedarea;
                   3363:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3364:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3365:                     }
                   3366:                 }
                   3367:             }
                   3368:         }
                   3369:     }
1.800     albertel 3370:     foreach my $group (keys(%grouproles)) {
                   3371:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3372:     }
1.800     albertel 3373:     foreach my $role (keys(%{$allroles})) {
                   3374:         my %thesepriv;
                   3375:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3376:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3377:             if ($item ne '') {
                   3378:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3379:                 if ($restrictions eq '') {
                   3380:                     $thesepriv{$privilege}='F';
                   3381:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3382:                     $thesepriv{$privilege}.=$restrictions;
                   3383:                 }
                   3384:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3385:             }
                   3386:         }
                   3387:         my $thesestr='';
1.800     albertel 3388:         foreach my $priv (keys(%thesepriv)) {
                   3389: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3390: 	}
                   3391:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3392:     }
                   3393:     return ($author,$adv);
                   3394: }
                   3395: 
1.12      www      3396: # --------------------------------------------------------------- get interface
                   3397: 
                   3398: sub get {
1.131     albertel 3399:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3400:    my $items='';
1.800     albertel 3401:    foreach my $item (@$storearr) {
                   3402:        $items.=&escape($item).'&';
1.191     harris41 3403:    }
1.12      www      3404:    $items=~s/\&$//;
1.620     albertel 3405:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3406:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3407:    my $uhome=&homeserver($uname,$udomain);
                   3408: 
1.133     albertel 3409:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3410:    my @pairs=split(/\&/,$rep);
1.273     albertel 3411:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3412:      return @pairs;
                   3413:    }
1.15      www      3414:    my %returnhash=();
1.42      www      3415:    my $i=0;
1.800     albertel 3416:    foreach my $item (@$storearr) {
                   3417:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3418:       $i++;
1.191     harris41 3419:    }
1.15      www      3420:    return %returnhash;
1.27      www      3421: }
                   3422: 
                   3423: # --------------------------------------------------------------- del interface
                   3424: 
                   3425: sub del {
1.133     albertel 3426:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3427:    my $items='';
1.800     albertel 3428:    foreach my $item (@$storearr) {
                   3429:        $items.=&escape($item).'&';
1.191     harris41 3430:    }
1.27      www      3431:    $items=~s/\&$//;
1.620     albertel 3432:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3433:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3434:    my $uhome=&homeserver($uname,$udomain);
                   3435: 
                   3436:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3437: }
                   3438: 
                   3439: # -------------------------------------------------------------- dump interface
                   3440: 
                   3441: sub dump {
1.755     albertel 3442:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3443:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3444:     if (!$uname) { $uname=$env{'user.name'}; }
                   3445:     my $uhome=&homeserver($uname,$udomain);
                   3446:     if ($regexp) {
                   3447: 	$regexp=&escape($regexp);
                   3448:     } else {
                   3449: 	$regexp='.';
                   3450:     }
                   3451:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3452:     my @pairs=split(/\&/,$rep);
                   3453:     my %returnhash=();
                   3454:     foreach my $item (@pairs) {
                   3455: 	my ($key,$value)=split(/=/,$item,2);
                   3456: 	$key = &unescape($key);
                   3457: 	next if ($key =~ /^error: 2 /);
                   3458: 	$returnhash{$key}=&thaw_unescape($value);
                   3459:     }
                   3460:     return %returnhash;
1.407     www      3461: }
                   3462: 
1.717     albertel 3463: # --------------------------------------------------------- dumpstore interface
                   3464: 
                   3465: sub dumpstore {
                   3466:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3467:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3468:    if (!$uname) { $uname=$env{'user.name'}; }
                   3469:    my $uhome=&homeserver($uname,$udomain);
                   3470:    if ($regexp) {
                   3471:        $regexp=&escape($regexp);
                   3472:    } else {
                   3473:        $regexp='.';
                   3474:    }
                   3475:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3476:    my @pairs=split(/\&/,$rep);
                   3477:    my %returnhash=();
                   3478:    foreach my $item (@pairs) {
                   3479:        my ($key,$value)=split(/=/,$item,2);
                   3480:        next if ($key =~ /^error: 2 /);
                   3481:        $returnhash{$key}=&thaw_unescape($value);
                   3482:    }
                   3483:    return %returnhash;
1.717     albertel 3484: }
                   3485: 
1.407     www      3486: # -------------------------------------------------------------- keys interface
                   3487: 
                   3488: sub getkeys {
                   3489:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3490:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3491:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3492:    my $uhome=&homeserver($uname,$udomain);
                   3493:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3494:    my @keyarray=();
1.800     albertel 3495:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3496:       next if ($key =~ /^error: 2 /);
1.800     albertel 3497:       push(@keyarray,&unescape($key));
1.407     www      3498:    }
                   3499:    return @keyarray;
1.318     matthew  3500: }
                   3501: 
1.319     matthew  3502: # --------------------------------------------------------------- currentdump
                   3503: sub currentdump {
1.328     matthew  3504:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3505:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3506:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3507:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3508:    my $uhome = &homeserver($sname,$sdom);
                   3509:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3510:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3511:    #
1.318     matthew  3512:    my %returnhash=();
1.319     matthew  3513:    #
                   3514:    if ($rep eq "unknown_cmd") { 
                   3515:        # an old lond will not know currentdump
                   3516:        # Do a dump and make it look like a currentdump
1.822     albertel 3517:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3518:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3519:        my %hash = @tmp;
                   3520:        @tmp=();
1.424     matthew  3521:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3522:    } else {
                   3523:        my @pairs=split(/\&/,$rep);
1.800     albertel 3524:        foreach my $pair (@pairs) {
                   3525:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3526:            my ($symb,$param) = split(/:/,$key);
                   3527:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3528:                                                         &thaw_unescape($value);
1.319     matthew  3529:        }
1.191     harris41 3530:    }
1.12      www      3531:    return %returnhash;
1.424     matthew  3532: }
                   3533: 
                   3534: sub convert_dump_to_currentdump{
                   3535:     my %hash = %{shift()};
                   3536:     my %returnhash;
                   3537:     # Code ripped from lond, essentially.  The only difference
                   3538:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3539:     # we might run in to problems with parameter names =~ /^v\./
                   3540:     while (my ($key,$value) = each(%hash)) {
                   3541:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3542: 	$symb  = &unescape($symb);
                   3543: 	$param = &unescape($param);
1.424     matthew  3544:         next if ($v eq 'version' || $symb eq 'keys');
                   3545:         next if (exists($returnhash{$symb}) &&
                   3546:                  exists($returnhash{$symb}->{$param}) &&
                   3547:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3548:         $returnhash{$symb}->{$param}=$value;
                   3549:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3550:     }
                   3551:     #
                   3552:     # Remove all of the keys in the hashes which keep track of
                   3553:     # the version of the parameter.
                   3554:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3555:         # use a foreach because we are going to delete from the hash.
                   3556:         foreach my $key (keys(%$param_hash)) {
                   3557:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3558:         }
                   3559:     }
                   3560:     return \%returnhash;
1.12      www      3561: }
                   3562: 
1.627     albertel 3563: # ------------------------------------------------------ critical inc interface
                   3564: 
                   3565: sub cinc {
                   3566:     return &inc(@_,'critical');
                   3567: }
                   3568: 
1.449     matthew  3569: # --------------------------------------------------------------- inc interface
                   3570: 
                   3571: sub inc {
1.627     albertel 3572:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3573:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3574:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3575:     my $uhome=&homeserver($uname,$udomain);
                   3576:     my $items='';
                   3577:     if (! ref($store)) {
                   3578:         # got a single value, so use that instead
                   3579:         $items = &escape($store).'=&';
                   3580:     } elsif (ref($store) eq 'SCALAR') {
                   3581:         $items = &escape($$store).'=&';        
                   3582:     } elsif (ref($store) eq 'ARRAY') {
                   3583:         $items = join('=&',map {&escape($_);} @{$store});
                   3584:     } elsif (ref($store) eq 'HASH') {
                   3585:         while (my($key,$value) = each(%{$store})) {
                   3586:             $items.= &escape($key).'='.&escape($value).'&';
                   3587:         }
                   3588:     }
                   3589:     $items=~s/\&$//;
1.627     albertel 3590:     if ($critical) {
                   3591: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3592:     } else {
                   3593: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3594:     }
1.449     matthew  3595: }
                   3596: 
1.12      www      3597: # --------------------------------------------------------------- put interface
                   3598: 
                   3599: sub put {
1.134     albertel 3600:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3601:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3602:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3603:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3604:    my $items='';
1.800     albertel 3605:    foreach my $item (keys(%$storehash)) {
                   3606:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3607:    }
1.12      www      3608:    $items=~s/\&$//;
1.134     albertel 3609:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3610: }
                   3611: 
1.631     albertel 3612: # ------------------------------------------------------------ newput interface
                   3613: 
                   3614: sub newput {
                   3615:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3616:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3617:    if (!$uname) { $uname=$env{'user.name'}; }
                   3618:    my $uhome=&homeserver($uname,$udomain);
                   3619:    my $items='';
                   3620:    foreach my $key (keys(%$storehash)) {
                   3621:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3622:    }
                   3623:    $items=~s/\&$//;
                   3624:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3625: }
                   3626: 
                   3627: # ---------------------------------------------------------  putstore interface
                   3628: 
1.524     raeburn  3629: sub putstore {
1.715     albertel 3630:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3631:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3632:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3633:    my $uhome=&homeserver($uname,$udomain);
                   3634:    my $items='';
1.715     albertel 3635:    foreach my $key (keys(%$storehash)) {
                   3636:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3637:    }
1.715     albertel 3638:    $items=~s/\&$//;
1.716     albertel 3639:    my $esc_symb=&escape($symb);
                   3640:    my $esc_v=&escape($version);
1.715     albertel 3641:    my $reply =
1.716     albertel 3642:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3643: 	      $uhome);
                   3644:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3645:        # gfall back to way things use to be done
1.715     albertel 3646:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3647: 			    $uname);
1.524     raeburn  3648:    }
1.715     albertel 3649:    return $reply;
                   3650: }
                   3651: 
                   3652: sub old_putstore {
1.716     albertel 3653:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3654:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3655:     if (!$uname) { $uname=$env{'user.name'}; }
                   3656:     my $uhome=&homeserver($uname,$udomain);
                   3657:     my %newstorehash;
1.800     albertel 3658:     foreach my $item (keys(%$storehash)) {
                   3659: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3660: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3661:     }
                   3662:     my $items='';
                   3663:     my %allitems = ();
1.800     albertel 3664:     foreach my $item (keys(%newstorehash)) {
                   3665: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3666: 	    my $key = $1.':keys:'.$2;
                   3667: 	    $allitems{$key} .= $3.':';
                   3668: 	}
1.800     albertel 3669: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3670:     }
1.800     albertel 3671:     foreach my $item (keys(%allitems)) {
                   3672: 	$allitems{$item} =~ s/\:$//;
                   3673: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3674:     }
                   3675:     $items=~s/\&$//;
                   3676:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3677: }
                   3678: 
1.47      www      3679: # ------------------------------------------------------ critical put interface
                   3680: 
                   3681: sub cput {
1.134     albertel 3682:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3683:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3684:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3685:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3686:    my $items='';
1.800     albertel 3687:    foreach my $item (keys(%$storehash)) {
                   3688:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3689:    }
1.47      www      3690:    $items=~s/\&$//;
1.134     albertel 3691:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3692: }
                   3693: 
                   3694: # -------------------------------------------------------------- eget interface
                   3695: 
                   3696: sub eget {
1.133     albertel 3697:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3698:    my $items='';
1.800     albertel 3699:    foreach my $item (@$storearr) {
                   3700:        $items.=&escape($item).'&';
1.191     harris41 3701:    }
1.12      www      3702:    $items=~s/\&$//;
1.620     albertel 3703:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3704:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3705:    my $uhome=&homeserver($uname,$udomain);
                   3706:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3707:    my @pairs=split(/\&/,$rep);
                   3708:    my %returnhash=();
1.42      www      3709:    my $i=0;
1.800     albertel 3710:    foreach my $item (@$storearr) {
                   3711:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3712:       $i++;
1.191     harris41 3713:    }
1.12      www      3714:    return %returnhash;
                   3715: }
                   3716: 
1.667     albertel 3717: # ------------------------------------------------------------ tmpput interface
                   3718: sub tmpput {
1.802     raeburn  3719:     my ($storehash,$server,$context)=@_;
1.667     albertel 3720:     my $items='';
1.800     albertel 3721:     foreach my $item (keys(%$storehash)) {
                   3722: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3723:     }
                   3724:     $items=~s/\&$//;
1.802     raeburn  3725:     if (defined($context)) {
                   3726:         $items .= ':'.&escape($context);
                   3727:     }
1.667     albertel 3728:     return &reply("tmpput:$items",$server);
                   3729: }
                   3730: 
                   3731: # ------------------------------------------------------------ tmpget interface
                   3732: sub tmpget {
1.688     albertel 3733:     my ($token,$server)=@_;
                   3734:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3735:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3736:     my %returnhash;
                   3737:     foreach my $item (split(/\&/,$rep)) {
                   3738: 	my ($key,$value)=split(/=/,$item);
                   3739: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3740:     }
                   3741:     return %returnhash;
                   3742: }
                   3743: 
1.688     albertel 3744: # ------------------------------------------------------------ tmpget interface
                   3745: sub tmpdel {
                   3746:     my ($token,$server)=@_;
                   3747:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3748:     return &reply("tmpdel:$token",$server);
                   3749: }
                   3750: 
1.765     albertel 3751: # -------------------------------------------------- portfolio access checking
                   3752: 
                   3753: sub portfolio_access {
1.766     albertel 3754:     my ($requrl) = @_;
1.765     albertel 3755:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3756:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3757:     if ($result) {
                   3758:         my %setters;
                   3759:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3760:             my ($startblock,$endblock) =
                   3761:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3762:             if ($startblock && $endblock) {
                   3763:                 return 'B';
                   3764:             }
                   3765:         } else {
                   3766:             my ($startblock,$endblock) =
                   3767:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3768:             if ($startblock && $endblock) {
                   3769:                 return 'B';
                   3770:             }
                   3771:         }
                   3772:     }
1.765     albertel 3773:     if ($result eq 'ok') {
1.766     albertel 3774:        return 'F';
1.765     albertel 3775:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3776:        return 'A';
1.765     albertel 3777:     }
1.766     albertel 3778:     return '';
1.765     albertel 3779: }
                   3780: 
                   3781: sub get_portfolio_access {
1.767     albertel 3782:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3783: 
                   3784:     if (!ref($access_hash)) {
                   3785: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3786: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3787: 						   $file_name);
                   3788: 	$access_hash = $access_controls{$file_name};
                   3789:     }
                   3790: 
1.765     albertel 3791:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3792:     my $now = time;
                   3793:     if (ref($access_hash) eq 'HASH') {
                   3794:         foreach my $key (keys(%{$access_hash})) {
                   3795:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3796:             if ($start > $now) {
                   3797:                 next;
                   3798:             }
                   3799:             if ($end && $end<$now) {
                   3800:                 next;
                   3801:             }
                   3802:             if ($scope eq 'public') {
                   3803:                 $public = $key;
                   3804:                 last;
                   3805:             } elsif ($scope eq 'guest') {
                   3806:                 $guest = $key;
                   3807:             } elsif ($scope eq 'domains') {
                   3808:                 push(@domains,$key);
                   3809:             } elsif ($scope eq 'users') {
                   3810:                 push(@users,$key);
                   3811:             } elsif ($scope eq 'course') {
                   3812:                 push(@courses,$key);
                   3813:             } elsif ($scope eq 'group') {
                   3814:                 push(@groups,$key);
                   3815:             }
                   3816:         }
                   3817:         if ($public) {
                   3818:             return 'ok';
                   3819:         }
                   3820:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3821:             if ($guest) {
                   3822:                 return $guest;
                   3823:             }
                   3824:         } else {
                   3825:             if (@domains > 0) {
                   3826:                 foreach my $domkey (@domains) {
                   3827:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3828:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3829:                             return 'ok';
                   3830:                         }
                   3831:                     }
                   3832:                 }
                   3833:             }
                   3834:             if (@users > 0) {
                   3835:                 foreach my $userkey (@users) {
1.865     raeburn  3836:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3837:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3838:                             if (ref($item) eq 'HASH') {
                   3839:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3840:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3841:                                     return 'ok';
                   3842:                                 }
                   3843:                             }
                   3844:                         }
                   3845:                     } 
1.765     albertel 3846:                 }
                   3847:             }
                   3848:             my %roleshash;
                   3849:             my @courses_and_groups = @courses;
                   3850:             push(@courses_and_groups,@groups); 
                   3851:             if (@courses_and_groups > 0) {
                   3852:                 my (%allgroups,%allroles); 
                   3853:                 my ($start,$end,$role,$sec,$group);
                   3854:                 foreach my $envkey (%env) {
1.811     albertel 3855:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3856:                         my $cid = $2.'_'.$3; 
                   3857:                         if ($1 eq 'gr') {
                   3858:                             $group = $4;
                   3859:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3860:                         } else {
                   3861:                             if ($4 eq '') {
                   3862:                                 $sec = 'none';
                   3863:                             } else {
                   3864:                                 $sec = $4;
                   3865:                             }
                   3866:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3867:                         }
1.811     albertel 3868:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3869:                         my $cid = $2.'_'.$3;
                   3870:                         if ($4 eq '') {
                   3871:                             $sec = 'none';
                   3872:                         } else {
                   3873:                             $sec = $4;
                   3874:                         }
                   3875:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3876:                     }
                   3877:                 }
                   3878:                 if (keys(%allroles) == 0) {
                   3879:                     return;
                   3880:                 }
                   3881:                 foreach my $key (@courses_and_groups) {
                   3882:                     my %content = %{$$access_hash{$key}};
                   3883:                     my $cnum = $content{'number'};
                   3884:                     my $cdom = $content{'domain'};
                   3885:                     my $cid = $cdom.'_'.$cnum;
                   3886:                     if (!exists($allroles{$cid})) {
                   3887:                         next;
                   3888:                     }    
                   3889:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3890:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3891:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3892:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3893:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3894:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3895:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3896:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3897:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3898:                                         if (grep/^all$/,@sections) {
                   3899:                                             return 'ok';
                   3900:                                         } else {
                   3901:                                             if (grep/^$sec$/,@sections) {
                   3902:                                                 return 'ok';
                   3903:                                             }
                   3904:                                         }
                   3905:                                     }
                   3906:                                 }
                   3907:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3908:                                     if (grep/^none$/,@groups) {
                   3909:                                         return 'ok';
                   3910:                                     }
                   3911:                                 } else {
                   3912:                                     if (grep/^all$/,@groups) {
                   3913:                                         return 'ok';
                   3914:                                     } 
                   3915:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3916:                                         if (grep/^$group$/,@groups) {
                   3917:                                             return 'ok';
                   3918:                                         }
                   3919:                                     }
                   3920:                                 } 
                   3921:                             }
                   3922:                         }
                   3923:                     }
                   3924:                 }
                   3925:             }
                   3926:             if ($guest) {
                   3927:                 return $guest;
                   3928:             }
                   3929:         }
                   3930:     }
                   3931:     return;
                   3932: }
                   3933: 
                   3934: sub course_group_datechecker {
                   3935:     my ($dates,$now,$status) = @_;
                   3936:     my ($start,$end) = split(/\./,$dates);
                   3937:     if (!$start && !$end) {
                   3938:         return 'ok';
                   3939:     }
                   3940:     if (grep/^active$/,@{$status}) {
                   3941:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3942:             return 'ok';
                   3943:         }
                   3944:     }
                   3945:     if (grep/^previous$/,@{$status}) {
                   3946:         if ($end > $now ) {
                   3947:             return 'ok';
                   3948:         }
                   3949:     }
                   3950:     if (grep/^future$/,@{$status}) {
                   3951:         if ($start > $now) {
                   3952:             return 'ok';
                   3953:         }
                   3954:     }
                   3955:     return; 
                   3956: }
                   3957: 
                   3958: sub parse_portfolio_url {
                   3959:     my ($url) = @_;
                   3960: 
                   3961:     my ($type,$udom,$unum,$group,$file_name);
                   3962:     
1.823     albertel 3963:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3964: 	$type = 1;
                   3965:         $udom = $1;
                   3966:         $unum = $2;
                   3967:         $file_name = $3;
1.823     albertel 3968:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3969: 	$type = 2;
                   3970:         $udom = $1;
                   3971:         $unum = $2;
                   3972:         $group = $3;
                   3973:         $file_name = $3.'/'.$4;
                   3974:     }
                   3975:     if (wantarray) {
                   3976: 	return ($type,$udom,$unum,$file_name,$group);
                   3977:     }
                   3978:     return $type;
                   3979: }
                   3980: 
                   3981: sub is_portfolio_url {
                   3982:     my ($url) = @_;
                   3983:     return scalar(&parse_portfolio_url($url));
                   3984: }
                   3985: 
1.798     raeburn  3986: sub is_portfolio_file {
                   3987:     my ($file) = @_;
1.820     raeburn  3988:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3989:         return 1;
                   3990:     }
                   3991:     return;
                   3992: }
                   3993: 
                   3994: 
1.341     www      3995: # ---------------------------------------------- Custom access rule evaluation
                   3996: 
                   3997: sub customaccess {
                   3998:     my ($priv,$uri)=@_;
1.807     albertel 3999:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4000:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4001:     $udom = &LONCAPA::clean_domain($udom);
                   4002:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4003:     my $access=0;
1.800     albertel 4004:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4005: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4006: 	if ($type eq 'user') {
                   4007: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4008: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4009: 		if ($tdom) {
                   4010: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4011: 		}
1.896     albertel 4012: 		if ($tuname) {
                   4013: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4014: 		}
                   4015: 		$access=($effect eq 'allow');
                   4016: 		last;
                   4017: 	    }
                   4018: 	} else {
                   4019: 	    if ($role) {
                   4020: 		if ($role ne $urole) { next; }
                   4021: 	    }
                   4022: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4023: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4024: 		if ($tdom) {
                   4025: 		    if ($tdom ne $udom) { next; }
                   4026: 		}
                   4027: 		if ($tcrs) {
                   4028: 		    if ($tcrs ne $ucrs) { next; }
                   4029: 		}
                   4030: 		if ($tsec) {
                   4031: 		    if ($tsec ne $usec) { next; }
                   4032: 		}
                   4033: 		$access=($effect eq 'allow');
                   4034: 		last;
                   4035: 	    }
                   4036: 	    if ($realm eq '' && $role eq '') {
                   4037: 		$access=($effect eq 'allow');
                   4038: 	    }
1.402     bowersj2 4039: 	}
1.341     www      4040:     }
                   4041:     return $access;
                   4042: }
                   4043: 
1.103     harris41 4044: # ------------------------------------------------- Check for a user privilege
1.12      www      4045: 
                   4046: sub allowed {
1.810     raeburn  4047:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4048:     my $ver_orguri=$uri;
1.439     www      4049:     $uri=&deversion($uri);
1.152     www      4050:     my $orguri=$uri;
1.52      www      4051:     $uri=&declutter($uri);
1.809     raeburn  4052: 
1.810     raeburn  4053:     if ($priv eq 'evb') {
                   4054: # Evade communication block restrictions for specified role in a course
                   4055:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4056:             return $1;
                   4057:         } else {
                   4058:             return;
                   4059:         }
                   4060:     }
                   4061: 
1.620     albertel 4062:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4063: # Free bre access to adm and meta resources
1.775     albertel 4064:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4065: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4066: 	&& ($priv eq 'bre')) {
1.14      www      4067: 	return 'F';
1.159     www      4068:     }
                   4069: 
1.545     banghart 4070: # Free bre access to user's own portfolio contents
1.714     raeburn  4071:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4072:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4073: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4074:         my %setters;
                   4075:         my ($startblock,$endblock) = 
                   4076:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4077:         if ($startblock && $endblock) {
                   4078:             return 'B';
                   4079:         } else {
                   4080:             return 'F';
                   4081:         }
1.545     banghart 4082:     }
                   4083: 
1.762     raeburn  4084: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4085:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4086:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4087:         if (exists($env{'request.course.id'})) {
                   4088:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4089:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4090:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4091:                 my $courseprivid=$env{'request.course.id'};
                   4092:                 $courseprivid=~s/\_/\//;
                   4093:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4094:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4095:                     return $1; 
1.762     raeburn  4096:                 } else {
                   4097:                     if ($env{'request.course.sec'}) {
                   4098:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4099:                     }
                   4100:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4101:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4102:                         return $2;
                   4103:                     }
1.714     raeburn  4104:                 }
                   4105:             }
                   4106:         }
                   4107:     }
                   4108: 
1.159     www      4109: # Free bre to public access
                   4110: 
                   4111:     if ($priv eq 'bre') {
1.238     www      4112:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4113: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4114:            return 'F'; 
                   4115:         }
1.238     www      4116:         if ($copyright eq 'priv') {
                   4117:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4118: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4119: 		return '';
                   4120:             }
                   4121:         }
                   4122:         if ($copyright eq 'domain') {
                   4123:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4124: 	    unless (($env{'user.domain'} eq $1) ||
                   4125:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4126: 		return '';
                   4127:             }
1.262     matthew  4128:         }
1.620     albertel 4129:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4130:             # Library role, so allow browsing of resources in this domain.
                   4131:             return 'F';
1.238     www      4132:         }
1.341     www      4133:         if ($copyright eq 'custom') {
                   4134: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4135:         }
1.14      www      4136:     }
1.264     matthew  4137:     # Domain coordinator is trying to create a course
1.620     albertel 4138:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4139:         # uri is the requested domain in this case.
                   4140:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4141:         # a role of dc for the domain in question.
1.620     albertel 4142:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4143:     }
1.29      www      4144: 
1.52      www      4145:     my $thisallowed='';
                   4146:     my $statecond=0;
                   4147:     my $courseprivid='';
                   4148: 
                   4149: # Course
                   4150: 
1.620     albertel 4151:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4152:        $thisallowed.=$1;
                   4153:     }
1.29      www      4154: 
1.52      www      4155: # Domain
                   4156: 
1.620     albertel 4157:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4158:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4159:        $thisallowed.=$1;
                   4160:     }
1.52      www      4161: 
                   4162: # Course: uri itself is a course
1.66      www      4163:     my $courseuri=$uri;
                   4164:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4165:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4166: 
1.620     albertel 4167:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4168:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4169:        $thisallowed.=$1;
                   4170:     }
1.29      www      4171: 
1.665     albertel 4172: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4173: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4174:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4175: 	$thisallowed='';
1.671     raeburn  4176:         my ($match)=&is_on_map($uri);
                   4177:         if ($match) {
                   4178:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4179:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4180:                 $thisallowed.=$1;
                   4181:             }
                   4182:         } else {
1.705     albertel 4183:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4184:             if ($refuri) {
                   4185:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4186:                     $thisallowed='F';
1.671     raeburn  4187:                 } else {
                   4188:                     $refuri=&declutter($refuri);
                   4189:                     my ($match) = &is_on_map($refuri);
                   4190:                     if ($match) {
                   4191:                         $thisallowed='F';
                   4192:                     }
1.669     raeburn  4193:                 }
1.671     raeburn  4194:             }
                   4195:         }
1.314     www      4196:     }
1.492     albertel 4197: 
1.766     albertel 4198:     if ($priv eq 'bre'
                   4199: 	&& $thisallowed ne 'F' 
                   4200: 	&& $thisallowed ne '2'
                   4201: 	&& &is_portfolio_url($uri)) {
                   4202: 	$thisallowed = &portfolio_access($uri);
                   4203:     }
                   4204:     
1.52      www      4205: # Full access at system, domain or course-wide level? Exit.
1.29      www      4206: 
                   4207:     if ($thisallowed=~/F/) {
                   4208: 	return 'F';
                   4209:     }
                   4210: 
1.52      www      4211: # If this is generating or modifying users, exit with special codes
1.29      www      4212: 
1.643     www      4213:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4214: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4215: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4216: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4217: 	    unless ($auname) { return $thisallowed; }
                   4218: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4219: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4220: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4221: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4222: 	}
1.52      www      4223: 	return $thisallowed;
                   4224:     }
                   4225: #
1.103     harris41 4226: # Gathered so far: system, domain and course wide privileges
1.52      www      4227: #
                   4228: # Course: See if uri or referer is an individual resource that is part of 
                   4229: # the course
                   4230: 
1.620     albertel 4231:     if ($env{'request.course.id'}) {
1.232     www      4232: 
1.620     albertel 4233:        $courseprivid=$env{'request.course.id'};
                   4234:        if ($env{'request.course.sec'}) {
                   4235:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4236:        }
                   4237:        $courseprivid=~s/\_/\//;
                   4238:        my $checkreferer=1;
1.232     www      4239:        my ($match,$cond)=&is_on_map($uri);
                   4240:        if ($match) {
                   4241:            $statecond=$cond;
1.620     albertel 4242:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4243:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4244:                $thisallowed.=$1;
                   4245:                $checkreferer=0;
                   4246:            }
1.29      www      4247:        }
1.83      www      4248:        
1.148     www      4249:        if ($checkreferer) {
1.620     albertel 4250: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4251:             unless ($refuri) {
1.800     albertel 4252:                 foreach my $key (keys(%env)) {
                   4253: 		    if ($key=~/^httpref\..*\*/) {
                   4254: 			my $pattern=$key;
1.156     www      4255:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4256:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4257:                         $pattern=~s/\//\\\//g;
1.152     www      4258:                         if ($orguri=~/$pattern/) {
1.800     albertel 4259: 			    $refuri=$env{$key};
1.148     www      4260:                         }
                   4261:                     }
1.191     harris41 4262:                 }
1.148     www      4263:             }
1.232     www      4264: 
1.148     www      4265:          if ($refuri) { 
1.152     www      4266: 	  $refuri=&declutter($refuri);
1.232     www      4267:           my ($match,$cond)=&is_on_map($refuri);
                   4268:             if ($match) {
                   4269:               my $refstatecond=$cond;
1.620     albertel 4270:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4271:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4272:                   $thisallowed.=$1;
1.53      www      4273:                   $uri=$refuri;
                   4274:                   $statecond=$refstatecond;
1.52      www      4275:               }
                   4276:           }
1.148     www      4277:         }
1.29      www      4278:        }
1.52      www      4279:    }
1.29      www      4280: 
1.52      www      4281: #
1.103     harris41 4282: # Gathered now: all privileges that could apply, and condition number
1.52      www      4283: # 
                   4284: #
                   4285: # Full or no access?
                   4286: #
1.29      www      4287: 
1.52      www      4288:     if ($thisallowed=~/F/) {
                   4289: 	return 'F';
                   4290:     }
1.29      www      4291: 
1.52      www      4292:     unless ($thisallowed) {
                   4293:         return '';
                   4294:     }
1.29      www      4295: 
1.52      www      4296: # Restrictions exist, deal with them
                   4297: #
                   4298: #   C:according to course preferences
                   4299: #   R:according to resource settings
                   4300: #   L:unless locked
                   4301: #   X:according to user session state
                   4302: #
                   4303: 
                   4304: # Possibly locked functionality, check all courses
1.54      www      4305: # Locks might take effect only after 10 minutes cache expiration for other
                   4306: # courses, and 2 minutes for current course
1.52      www      4307: 
                   4308:     my $envkey;
                   4309:     if ($thisallowed=~/L/) {
1.620     albertel 4310:         foreach $envkey (keys %env) {
1.54      www      4311:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4312:                my $courseid=$2;
                   4313:                my $roleid=$1.'.'.$2;
1.92      www      4314:                $courseid=~s/^\///;
1.54      www      4315:                my $expiretime=600;
1.620     albertel 4316:                if ($env{'request.role'} eq $roleid) {
1.54      www      4317: 		  $expiretime=120;
                   4318:                }
                   4319: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4320:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4321:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4322: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4323:                }
1.620     albertel 4324:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4325:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4326: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4327:                        &log($env{'user.domain'},$env{'user.name'},
                   4328:                             $env{'user.home'},
1.57      www      4329:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4330:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4331:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4332: 		       return '';
                   4333:                    }
                   4334:                }
1.620     albertel 4335:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4336:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4337: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4338:                        &log($env{'user.domain'},$env{'user.name'},
                   4339:                             $env{'user.home'},
1.57      www      4340:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4341:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4342:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4343: 		       return '';
                   4344:                    }
                   4345:                }
                   4346: 	   }
1.29      www      4347:        }
1.52      www      4348:     }
                   4349:    
                   4350: #
                   4351: # Rest of the restrictions depend on selected course
                   4352: #
                   4353: 
1.620     albertel 4354:     unless ($env{'request.course.id'}) {
1.766     albertel 4355: 	if ($thisallowed eq 'A') {
                   4356: 	    return 'A';
1.814     raeburn  4357:         } elsif ($thisallowed eq 'B') {
                   4358:             return 'B';
1.766     albertel 4359: 	} else {
                   4360: 	    return '1';
                   4361: 	}
1.52      www      4362:     }
1.29      www      4363: 
1.52      www      4364: #
                   4365: # Now user is definitely in a course
                   4366: #
1.53      www      4367: 
                   4368: 
                   4369: # Course preferences
                   4370: 
                   4371:    if ($thisallowed=~/C/) {
1.620     albertel 4372:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4373:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4374:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4375: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4376: 	   if ($priv ne 'pch') { 
                   4377: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4378: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4379: 			$env{'request.course.id'});
                   4380: 	   }
1.237     www      4381:            return '';
                   4382:        }
                   4383: 
1.620     albertel 4384:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4385: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4386: 	   if ($priv ne 'pch') { 
                   4387: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4388: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4389: 			$env{'request.course.id'});
                   4390: 	   }
1.54      www      4391:            return '';
                   4392:        }
1.53      www      4393:    }
                   4394: 
                   4395: # Resource preferences
                   4396: 
                   4397:    if ($thisallowed=~/R/) {
1.620     albertel 4398:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4399:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4400: 	   if ($priv ne 'pch') { 
                   4401: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4402: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4403: 	   }
                   4404: 	   return '';
1.54      www      4405:        }
1.53      www      4406:    }
1.30      www      4407: 
1.246     www      4408: # Restricted by state or randomout?
1.30      www      4409: 
1.52      www      4410:    if ($thisallowed=~/X/) {
1.620     albertel 4411:       if ($env{'acc.randomout'}) {
1.579     albertel 4412: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4413:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4414:             return ''; 
                   4415:          }
1.247     www      4416:       }
                   4417:       if (&condval($statecond)) {
1.52      www      4418: 	 return '2';
                   4419:       } else {
                   4420:          return '';
                   4421:       }
                   4422:    }
1.30      www      4423: 
1.766     albertel 4424:     if ($thisallowed eq 'A') {
                   4425: 	return 'A';
1.814     raeburn  4426:     } elsif ($thisallowed eq 'B') {
                   4427:         return 'B';
1.766     albertel 4428:     }
1.52      www      4429:    return 'F';
1.232     www      4430: }
                   4431: 
1.710     albertel 4432: sub split_uri_for_cond {
                   4433:     my $uri=&deversion(&declutter(shift));
                   4434:     my @uriparts=split(/\//,$uri);
                   4435:     my $filename=pop(@uriparts);
                   4436:     my $pathname=join('/',@uriparts);
                   4437:     return ($pathname,$filename);
                   4438: }
1.232     www      4439: # --------------------------------------------------- Is a resource on the map?
                   4440: 
                   4441: sub is_on_map {
1.710     albertel 4442:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4443:     #Trying to find the conditional for the file
1.620     albertel 4444:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4445: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4446:     if ($match) {
1.289     bowersj2 4447: 	return (1,$1);
                   4448:     } else {
1.434     www      4449: 	return (0,0);
1.289     bowersj2 4450:     }
1.12      www      4451: }
                   4452: 
1.427     www      4453: # --------------------------------------------------------- Get symb from alias
                   4454: 
                   4455: sub get_symb_from_alias {
                   4456:     my $symb=shift;
                   4457:     my ($map,$resid,$url)=&decode_symb($symb);
                   4458: # Already is a symb
                   4459:     if ($url) { return $symb; }
                   4460: # Must be an alias
                   4461:     my $aliassymb='';
                   4462:     my %bighash;
1.620     albertel 4463:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4464:                             &GDBM_READER(),0640)) {
                   4465:         my $rid=$bighash{'mapalias_'.$symb};
                   4466: 	if ($rid) {
                   4467: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4468: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4469: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4470: 	}
                   4471:         untie %bighash;
                   4472:     }
                   4473:     return $aliassymb;
                   4474: }
                   4475: 
1.12      www      4476: # ----------------------------------------------------------------- Define Role
                   4477: 
                   4478: sub definerole {
                   4479:   if (allowed('mcr','/')) {
                   4480:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4481:     foreach my $role (split(':',$sysrole)) {
                   4482: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4483:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4484:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4485: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4486:                return "refused:s:$crole&$cqual"; 
                   4487:             }
                   4488:         }
1.191     harris41 4489:     }
1.800     albertel 4490:     foreach my $role (split(':',$domrole)) {
                   4491: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4492:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4493:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4494: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4495:                return "refused:d:$crole&$cqual"; 
                   4496:             }
                   4497:         }
1.191     harris41 4498:     }
1.800     albertel 4499:     foreach my $role (split(':',$courole)) {
                   4500: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4501:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4502:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4503: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4504:                return "refused:c:$crole&$cqual"; 
                   4505:             }
                   4506:         }
1.191     harris41 4507:     }
1.620     albertel 4508:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4509:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4510: 	        "rolesdef_$rolename=".
                   4511:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4512:     return reply($command,$env{'user.home'});
1.12      www      4513:   } else {
                   4514:     return 'refused';
                   4515:   }
1.105     harris41 4516: }
                   4517: 
                   4518: # ---------------- Make a metadata query against the network of library servers
                   4519: 
                   4520: sub metadata_query {
1.244     matthew  4521:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4522:     my %rhash;
1.845     albertel 4523:     my %libserv = &all_library();
1.244     matthew  4524:     my @server_list = (defined($server_array) ? @$server_array
                   4525:                                               : keys(%libserv) );
                   4526:     for my $server (@server_list) {
1.118     harris41 4527: 	unless ($custom or $customshow) {
                   4528: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4529: 	    $rhash{$server}=$reply;
                   4530: 	}
                   4531: 	else {
                   4532: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4533: 			     &escape($custom).':'.&escape($customshow),
                   4534: 			     $server);
                   4535: 	    $rhash{$server}=$reply;
                   4536: 	}
1.112     harris41 4537:     }
1.118     harris41 4538:     return \%rhash;
1.240     www      4539: }
                   4540: 
                   4541: # ----------------------------------------- Send log queries and wait for reply
                   4542: 
                   4543: sub log_query {
                   4544:     my ($uname,$udom,$query,%filters)=@_;
                   4545:     my $uhome=&homeserver($uname,$udom);
                   4546:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4547:     my $uhost=&hostname($uhome);
1.800     albertel 4548:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4549:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4550:                        $uhome);
1.479     albertel 4551:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4552:     return get_query_reply($queryid);
                   4553: }
                   4554: 
1.818     raeburn  4555: # -------------------------- Update MySQL table for portfolio file
                   4556: 
                   4557: sub update_portfolio_table {
1.821     raeburn  4558:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4559:     my $homeserver = &homeserver($uname,$udom);
                   4560:     my $queryid=
1.821     raeburn  4561:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4562:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4563:     my $reply = &get_query_reply($queryid);
                   4564:     return $reply;
                   4565: }
                   4566: 
1.899     raeburn  4567: # -------------------------- Update MySQL allusers table
                   4568: 
                   4569: sub update_allusers_table {
                   4570:     my ($uname,$udom,$names) = @_;
                   4571:     my $homeserver = &homeserver($uname,$udom);
                   4572:     my $queryid=
                   4573:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4574:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4575:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4576:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4577:                'generation='.&escape($names->{'generation'}).'%%'.
                   4578:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4579:                'id='.&escape($names->{'id'}),$homeserver);
                   4580:     my $reply = &get_query_reply($queryid);
                   4581:     return $reply;
                   4582: }
                   4583: 
1.508     raeburn  4584: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4585: 
                   4586: sub fetch_enrollment_query {
1.511     raeburn  4587:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4588:     my $homeserver;
1.547     raeburn  4589:     my $maxtries = 1;
1.508     raeburn  4590:     if ($context eq 'automated') {
                   4591:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4592:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4593:     } else {
                   4594:         $homeserver = &homeserver($cnum,$dom);
                   4595:     }
1.838     albertel 4596:     my $host=&hostname($homeserver);
1.506     raeburn  4597:     my $cmd = '';
1.800     albertel 4598:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4599:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4600:     }
                   4601:     $cmd =~ s/%%$//;
                   4602:     $cmd = &escape($cmd);
                   4603:     my $query = 'fetchenrollment';
1.620     albertel 4604:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4605:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4606:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4607:         return 'error: '.$queryid;
                   4608:     }
1.506     raeburn  4609:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4610:     my $tries = 1;
                   4611:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4612:         $reply = &get_query_reply($queryid);
                   4613:         $tries ++;
                   4614:     }
1.526     raeburn  4615:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4616:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4617:     } else {
1.901     albertel 4618:         my @responses = split(/:/,$reply);
1.515     raeburn  4619:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4620:             foreach my $line (@responses) {
                   4621:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4622:                 $$replyref{$key} = $value;
                   4623:             }
                   4624:         } else {
1.506     raeburn  4625:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4626:             foreach my $line (@responses) {
                   4627:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4628:                 $$replyref{$key} = $value;
                   4629:                 if ($value > 0) {
1.800     albertel 4630:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4631:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4632:                         my $destname = $pathname.'/'.$filename;
                   4633:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4634:                         if ($xml_classlist =~ /^error/) {
                   4635:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4636:                         } else {
1.506     raeburn  4637:                             if ( open(FILE,">$destname") ) {
                   4638:                                 print FILE &unescape($xml_classlist);
                   4639:                                 close(FILE);
1.526     raeburn  4640:                             } else {
                   4641:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4642:                             }
                   4643:                         }
                   4644:                     }
                   4645:                 }
                   4646:             }
                   4647:         }
                   4648:         return 'ok';
                   4649:     }
                   4650:     return 'error';
                   4651: }
                   4652: 
1.242     www      4653: sub get_query_reply {
                   4654:     my $queryid=shift;
1.240     www      4655:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4656:     my $reply='';
                   4657:     for (1..100) {
                   4658: 	sleep 2;
                   4659:         if (-e $replyfile.'.end') {
1.448     albertel 4660: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4661: 		$reply = join('',<$fh>);
                   4662: 		close($fh);
1.240     www      4663: 	   } else { return 'error: reply_file_error'; }
1.242     www      4664:            return &unescape($reply);
                   4665: 	}
1.240     www      4666:     }
1.242     www      4667:     return 'timeout:'.$queryid;
1.240     www      4668: }
                   4669: 
                   4670: sub courselog_query {
1.241     www      4671: #
                   4672: # possible filters:
                   4673: # url: url or symb
                   4674: # username
                   4675: # domain
                   4676: # action: view, submit, grade
                   4677: # start: timestamp
                   4678: # end: timestamp
                   4679: #
1.240     www      4680:     my (%filters)=@_;
1.620     albertel 4681:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4682:     if ($filters{'url'}) {
                   4683: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4684:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4685:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4686:     }
1.620     albertel 4687:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4688:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4689:     return &log_query($cname,$cdom,'courselog',%filters);
                   4690: }
                   4691: 
                   4692: sub userlog_query {
1.858     raeburn  4693: #
                   4694: # possible filters:
                   4695: # action: log check role
                   4696: # start: timestamp
                   4697: # end: timestamp
                   4698: #
1.240     www      4699:     my ($uname,$udom,%filters)=@_;
                   4700:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4701: }
                   4702: 
1.506     raeburn  4703: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4704: 
                   4705: sub auto_run {
1.508     raeburn  4706:     my ($cnum,$cdom) = @_;
1.876     raeburn  4707:     my $response = 0;
                   4708:     my $settings;
                   4709:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4710:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4711:         $settings = $domconfig{'autoenroll'};
                   4712:         if ($settings->{'run'} eq '1') {
                   4713:             $response = 1;
                   4714:         }
                   4715:     } else {
                   4716:         my $homeserver = &homeserver($cnum,$cdom);
                   4717:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4718:     }
1.506     raeburn  4719:     return $response;
                   4720: }
1.776     albertel 4721: 
1.506     raeburn  4722: sub auto_get_sections {
1.508     raeburn  4723:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4724:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4725:     my @secs = ();
1.511     raeburn  4726:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4727:     unless ($response eq 'refused') {
1.901     albertel 4728:         @secs = split(/:/,$response);
1.506     raeburn  4729:     }
                   4730:     return @secs;
                   4731: }
1.776     albertel 4732: 
1.506     raeburn  4733: sub auto_new_course {
1.508     raeburn  4734:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4735:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4736:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4737:     return $response;
                   4738: }
1.776     albertel 4739: 
1.506     raeburn  4740: sub auto_validate_courseID {
1.508     raeburn  4741:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4742:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4743:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4744:     return $response;
                   4745: }
1.776     albertel 4746: 
1.506     raeburn  4747: sub auto_create_password {
1.873     raeburn  4748:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4749:     my ($homeserver,$response);
1.506     raeburn  4750:     my $create_passwd = 0;
                   4751:     my $authchk = '';
1.873     raeburn  4752:     if ($udom =~ /^$match_domain$/) {
                   4753:         $homeserver = &domain($udom,'primary');
                   4754:     }
                   4755:     if ($homeserver eq '') {
                   4756:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4757:             $homeserver = &homeserver($cnum,$cdom);
                   4758:         }
                   4759:     }
                   4760:     if ($homeserver eq '') {
                   4761:         $authchk = 'nodomain';
1.506     raeburn  4762:     } else {
1.873     raeburn  4763:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4764:         if ($response eq 'refused') {
                   4765:             $authchk = 'refused';
                   4766:         } else {
1.901     albertel 4767:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4768:         }
1.506     raeburn  4769:     }
                   4770:     return ($authparam,$create_passwd,$authchk);
                   4771: }
                   4772: 
1.706     raeburn  4773: sub auto_photo_permission {
                   4774:     my ($cnum,$cdom,$students) = @_;
                   4775:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4776:     my ($outcome,$perm_reqd,$conditions) = 
                   4777: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4778:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4779: 	return (undef,undef);
                   4780:     }
1.706     raeburn  4781:     return ($outcome,$perm_reqd,$conditions);
                   4782: }
                   4783: 
                   4784: sub auto_checkphotos {
                   4785:     my ($uname,$udom,$pid) = @_;
                   4786:     my $homeserver = &homeserver($uname,$udom);
                   4787:     my ($result,$resulttype);
                   4788:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4789: 				   &escape($uname).':'.&escape($pid),
                   4790: 				   $homeserver));
1.709     albertel 4791:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4792: 	return (undef,undef);
                   4793:     }
1.706     raeburn  4794:     if ($outcome) {
                   4795:         ($result,$resulttype) = split(/:/,$outcome);
                   4796:     } 
                   4797:     return ($result,$resulttype);
                   4798: }
                   4799: 
                   4800: sub auto_photochoice {
                   4801:     my ($cnum,$cdom) = @_;
                   4802:     my $homeserver = &homeserver($cnum,$cdom);
                   4803:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4804: 						       &escape($cdom),
                   4805: 						       $homeserver)));
1.709     albertel 4806:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4807: 	return (undef,undef);
                   4808:     }
1.706     raeburn  4809:     return ($update,$comment);
                   4810: }
                   4811: 
                   4812: sub auto_photoupdate {
                   4813:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4814:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4815:     my $host=&hostname($homeserver);
1.706     raeburn  4816:     my $cmd = '';
                   4817:     my $maxtries = 1;
1.800     albertel 4818:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4819:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4820:     }
                   4821:     $cmd =~ s/%%$//;
                   4822:     $cmd = &escape($cmd);
                   4823:     my $query = 'institutionalphotos';
                   4824:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4825:     unless ($queryid=~/^\Q$host\E\_/) {
                   4826:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4827:         return 'error: '.$queryid;
                   4828:     }
                   4829:     my $reply = &get_query_reply($queryid);
                   4830:     my $tries = 1;
                   4831:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4832:         $reply = &get_query_reply($queryid);
                   4833:         $tries ++;
                   4834:     }
                   4835:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4836:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4837:     } else {
                   4838:         my @responses = split(/:/,$reply);
                   4839:         my $outcome = shift(@responses); 
                   4840:         foreach my $item (@responses) {
                   4841:             my ($key,$value) = split(/=/,$item);
                   4842:             $$photo{$key} = $value;
                   4843:         }
                   4844:         return $outcome;
                   4845:     }
                   4846:     return 'error';
                   4847: }
                   4848: 
1.521     raeburn  4849: sub auto_instcode_format {
1.793     albertel 4850:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4851: 	$cat_order) = @_;
1.521     raeburn  4852:     my $courses = '';
1.772     raeburn  4853:     my @homeservers;
1.521     raeburn  4854:     if ($caller eq 'global') {
1.841     albertel 4855: 	my %servers = &get_servers($codedom,'library');
                   4856: 	foreach my $tryserver (keys(%servers)) {
                   4857: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4858: 		push(@homeservers,$tryserver);
                   4859: 	    }
1.584     raeburn  4860:         }
1.521     raeburn  4861:     } else {
1.772     raeburn  4862:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4863:     }
1.793     albertel 4864:     foreach my $code (keys(%{$instcodes})) {
                   4865:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4866:     }
                   4867:     chop($courses);
1.772     raeburn  4868:     my $ok_response = 0;
                   4869:     my $response;
                   4870:     while (@homeservers > 0 && $ok_response == 0) {
                   4871:         my $server = shift(@homeservers); 
                   4872:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4873:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4874:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4875: 		split(/:/,$response);
1.772     raeburn  4876:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4877:             push(@{$codetitles},&str2array($codetitles_str));
                   4878:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4879:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4880:             $ok_response = 1;
                   4881:         }
                   4882:     }
                   4883:     if ($ok_response) {
1.521     raeburn  4884:         return 'ok';
1.772     raeburn  4885:     } else {
                   4886:         return $response;
1.521     raeburn  4887:     }
                   4888: }
                   4889: 
1.792     raeburn  4890: sub auto_instcode_defaults {
                   4891:     my ($domain,$returnhash,$code_order) = @_;
                   4892:     my @homeservers;
1.841     albertel 4893: 
                   4894:     my %servers = &get_servers($domain,'library');
                   4895:     foreach my $tryserver (keys(%servers)) {
                   4896: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4897: 	    push(@homeservers,$tryserver);
                   4898: 	}
1.792     raeburn  4899:     }
1.841     albertel 4900: 
1.792     raeburn  4901:     my $response;
1.841     albertel 4902:     foreach my $server (@homeservers) {
1.792     raeburn  4903:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4904:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4905: 	
                   4906: 	foreach my $pair (split(/\&/,$response)) {
                   4907: 	    my ($name,$value)=split(/\=/,$pair);
                   4908: 	    if ($name eq 'code_order') {
                   4909: 		@{$code_order} = split(/\&/,&unescape($value));
                   4910: 	    } else {
                   4911: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4912: 	    }
                   4913: 	}
                   4914: 	return 'ok';
1.792     raeburn  4915:     }
1.841     albertel 4916: 
                   4917:     return $response;
1.792     raeburn  4918: } 
                   4919: 
1.777     albertel 4920: sub auto_validate_class_sec {
1.773     raeburn  4921:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4922:     my $homeserver = &homeserver($cnum,$cdom);
                   4923:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4924:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4925:     return $response;
                   4926: }
                   4927: 
1.679     raeburn  4928: # ------------------------------------------------------- Course Group routines
                   4929: 
                   4930: sub get_coursegroups {
1.809     raeburn  4931:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4932:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4933: }
                   4934: 
1.679     raeburn  4935: sub modify_coursegroup {
                   4936:     my ($cdom,$cnum,$groupsettings) = @_;
                   4937:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4938: }
                   4939: 
1.809     raeburn  4940: sub toggle_coursegroup_status {
                   4941:     my ($cdom,$cnum,$group,$action) = @_;
                   4942:     my ($from_namespace,$to_namespace);
                   4943:     if ($action eq 'delete') {
                   4944:         $from_namespace = 'coursegroups';
                   4945:         $to_namespace = 'deleted_groups';
                   4946:     } else {
                   4947:         $from_namespace = 'deleted_groups';
                   4948:         $to_namespace = 'coursegroups';
                   4949:     }
                   4950:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4951:     if (my $tmp = &error(%curr_group)) {
                   4952:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4953:         return ('read error',$tmp);
                   4954:     } else {
                   4955:         my %savedsettings = %curr_group; 
1.809     raeburn  4956:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4957:         my $deloutcome;
                   4958:         if ($result eq 'ok') {
1.809     raeburn  4959:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4960:         } else {
                   4961:             return ('write error',$result);
                   4962:         }
                   4963:         if ($deloutcome eq 'ok') {
                   4964:             return 'ok';
                   4965:         } else {
                   4966:             return ('delete error',$deloutcome);
                   4967:         }
                   4968:     }
                   4969: }
                   4970: 
1.679     raeburn  4971: sub modify_group_roles {
                   4972:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4973:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4974:     my $role = 'gr/'.&escape($userprivs);
                   4975:     my ($uname,$udom) = split(/:/,$user);
                   4976:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4977:     if ($result eq 'ok') {
                   4978:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4979:     }
1.679     raeburn  4980:     return $result;
                   4981: }
                   4982: 
                   4983: sub modify_coursegroup_membership {
                   4984:     my ($cdom,$cnum,$membership) = @_;
                   4985:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4986:     return $result;
                   4987: }
                   4988: 
1.682     raeburn  4989: sub get_active_groups {
                   4990:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4991:     my $now = time;
                   4992:     my %groups = ();
                   4993:     foreach my $key (keys(%env)) {
1.811     albertel 4994:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4995:             my ($start,$end) = split(/\./,$env{$key});
                   4996:             if (($end!=0) && ($end<$now)) { next; }
                   4997:             if (($start!=0) && ($start>$now)) { next; }
                   4998:             if ($1 eq $cdom && $2 eq $cnum) {
                   4999:                 $groups{$3} = $env{$key} ;
                   5000:             }
                   5001:         }
                   5002:     }
                   5003:     return %groups;
                   5004: }
                   5005: 
1.683     raeburn  5006: sub get_group_membership {
                   5007:     my ($cdom,$cnum,$group) = @_;
                   5008:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5009: }
                   5010: 
                   5011: sub get_users_groups {
                   5012:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5013:     my @usersgroups;
1.683     raeburn  5014:     my $cachetime=1800;
                   5015: 
                   5016:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5017:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5018:     if (defined($cached)) {
1.734     albertel 5019:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5020:     } else {  
                   5021:         $grouplist = '';
1.816     raeburn  5022:         my $courseurl = &courseid_to_courseurl($courseid);
                   5023:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5024:         my $access_end = $env{'course.'.$courseid.
                   5025:                               '.default_enrollment_end_date'};
                   5026:         my $now = time;
                   5027:         foreach my $key (keys(%roleshash)) {
                   5028:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5029:                 my $group = $1;
                   5030:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5031:                     my $start = $2;
                   5032:                     my $end = $1;
                   5033:                     if ($start == -1) { next; } # deleted from group
                   5034:                     if (($start!=0) && ($start>$now)) { next; }
                   5035:                     if (($end!=0) && ($end<$now)) {
                   5036:                         if ($access_end && $access_end < $now) {
                   5037:                             if ($access_end - $end < 86400) {
                   5038:                                 push(@usersgroups,$group);
1.733     raeburn  5039:                             }
                   5040:                         }
1.817     raeburn  5041:                         next;
1.733     raeburn  5042:                     }
1.817     raeburn  5043:                     push(@usersgroups,$group);
1.683     raeburn  5044:                 }
                   5045:             }
                   5046:         }
1.817     raeburn  5047:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5048:         $grouplist = join(':',@usersgroups);
                   5049:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5050:     }
1.733     raeburn  5051:     return @usersgroups;
1.683     raeburn  5052: }
                   5053: 
                   5054: sub devalidate_getgroups_cache {
                   5055:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5056:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5057: 
1.683     raeburn  5058:     my $hashid="$udom:$uname:$courseid";
                   5059:     &devalidate_cache_new('getgroups',$hashid);
                   5060: }
                   5061: 
1.12      www      5062: # ------------------------------------------------------------------ Plain Text
                   5063: 
                   5064: sub plaintext {
1.742     raeburn  5065:     my ($short,$type,$cid) = @_;
1.758     albertel 5066:     if ($short =~ /^cr/) {
                   5067: 	return (split('/',$short))[-1];
                   5068:     }
1.742     raeburn  5069:     if (!defined($cid)) {
                   5070:         $cid = $env{'request.course.id'};
                   5071:     }
                   5072:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5073:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5074:                                           '.plaintext'});
                   5075:     }
                   5076:     my %rolenames = (
                   5077:                       Course => 'std',
                   5078:                       Group => 'alt1',
                   5079:                     );
                   5080:     if (defined($type) && 
                   5081:          defined($rolenames{$type}) && 
                   5082:          defined($prp{$short}{$rolenames{$type}})) {
                   5083:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5084:     } else {
                   5085:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5086:     }
1.12      www      5087: }
                   5088: 
                   5089: # ----------------------------------------------------------------- Assign Role
                   5090: 
                   5091: sub assignrole {
1.357     www      5092:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5093:     my $mrole;
                   5094:     if ($role =~ /^cr\//) {
1.393     www      5095:         my $cwosec=$url;
1.811     albertel 5096:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5097: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5098:            &logthis('Refused custom assignrole: '.
                   5099:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5100: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5101:            return 'refused'; 
                   5102:         }
1.21      www      5103:         $mrole='cr';
1.678     raeburn  5104:     } elsif ($role =~ /^gr\//) {
                   5105:         my $cwogrp=$url;
1.811     albertel 5106:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5107:         unless (&allowed('mdg',$cwogrp)) {
                   5108:             &logthis('Refused group assignrole: '.
                   5109:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5110:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5111:             return 'refused';
                   5112:         }
                   5113:         $mrole='gr';
1.21      www      5114:     } else {
1.82      www      5115:         my $cwosec=$url;
1.811     albertel 5116:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5117:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5118:            &logthis('Refused assignrole: '.
                   5119:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5120: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5121:            return 'refused'; 
                   5122:         }
1.21      www      5123:         $mrole=$role;
                   5124:     }
1.620     albertel 5125:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5126:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5127:     if ($end) { $command.='_'.$end; }
1.21      www      5128:     if ($start) {
                   5129: 	if ($end) { 
1.81      www      5130:            $command.='_'.$start; 
1.21      www      5131:         } else {
1.81      www      5132:            $command.='_0_'.$start;
1.21      www      5133:         }
                   5134:     }
1.739     raeburn  5135:     my $origstart = $start;
                   5136:     my $origend = $end;
1.357     www      5137: # actually delete
                   5138:     if ($deleteflag) {
1.373     www      5139: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5140: # modify command to delete the role
1.620     albertel 5141:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5142:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5143: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5144: # set start and finish to negative values for userrolelog
                   5145:            $start=-1;
                   5146:            $end=-1;
                   5147:         }
                   5148:     }
                   5149: # send command
1.349     www      5150:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5151: # log new user role if status is ok
1.349     www      5152:     if ($answer eq 'ok') {
1.663     raeburn  5153: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5154: # for course roles, perform group memberships changes triggered by role change.
                   5155:         unless ($role =~ /^gr/) {
                   5156:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5157:                                              $origstart);
                   5158:         }
1.349     www      5159:     }
                   5160:     return $answer;
1.169     harris41 5161: }
                   5162: 
                   5163: # -------------------------------------------------- Modify user authentication
1.197     www      5164: # Overrides without validation
                   5165: 
1.169     harris41 5166: sub modifyuserauth {
                   5167:     my ($udom,$uname,$umode,$upass)=@_;
                   5168:     my $uhome=&homeserver($uname,$udom);
1.197     www      5169:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5170:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5171:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5172:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5173:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5174: 		     &escape($upass),$uhome);
1.620     albertel 5175:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5176:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5177:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5178:     &log($udom,,$uname,$uhome,
1.620     albertel 5179:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5180:                                      $env{'user.name'}.', '.$umode.
1.197     www      5181:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5182:     unless ($reply eq 'ok') {
1.197     www      5183:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5184: 	return 'error: '.$reply;
                   5185:     }   
1.170     harris41 5186:     return 'ok';
1.80      www      5187: }
                   5188: 
1.81      www      5189: # --------------------------------------------------------------- Modify a user
1.80      www      5190: 
1.81      www      5191: sub modifyuser {
1.206     matthew  5192:     my ($udom,    $uname, $uid,
                   5193:         $umode,   $upass, $first,
                   5194:         $middle,  $last,  $gene,
1.387     www      5195:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5196:     $udom= &LONCAPA::clean_domain($udom);
                   5197:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5198:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5199:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5200: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5201:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5202:                                      ' desiredhome not specified'). 
1.620     albertel 5203:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5204:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5205:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5206: # ----------------------------------------------------------------- Create User
1.406     albertel 5207:     if (($uhome eq 'no_host') && 
                   5208: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5209:         my $unhome='';
1.844     albertel 5210:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5211:             $unhome = $desiredhome;
1.620     albertel 5212: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5213: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5214:         } else { # load balancing routine for determining $unhome
1.81      www      5215:             my $loadm=10000000;
1.841     albertel 5216: 	    my %servers = &get_servers($udom,'library');
                   5217: 	    foreach my $tryserver (keys(%servers)) {
                   5218: 		my $answer=reply('load',$tryserver);
                   5219: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5220: 		    $loadm=$answer;
                   5221: 		    $unhome=$tryserver;
                   5222: 		}
1.80      www      5223: 	    }
                   5224:         }
                   5225:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5226: 	    return 'error: unable to find a home server for '.$uname.
                   5227:                    ' in domain '.$udom;
1.80      www      5228:         }
                   5229:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5230:                          &escape($upass),$unhome);
                   5231: 	unless ($reply eq 'ok') {
                   5232:             return 'error: '.$reply;
                   5233:         }   
1.230     stredwic 5234:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5235:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5236: 	    return 'error: unable verify users home machine.';
1.80      www      5237:         }
1.209     matthew  5238:     }   # End of creation of new user
1.80      www      5239: # ---------------------------------------------------------------------- Add ID
                   5240:     if ($uid) {
                   5241:        $uid=~tr/A-Z/a-z/;
                   5242:        my %uidhash=&idrget($udom,$uname);
1.196     www      5243:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5244:          && (!$forceid)) {
1.80      www      5245: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5246: 	      return 'error: user id "'.$uid.'" does not match '.
                   5247:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5248:           }
                   5249:        } else {
                   5250: 	  &idput($udom,($uname => $uid));
                   5251:        }
                   5252:     }
                   5253: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5254:     my @tmp=&get('environment',
1.899     raeburn  5255: 		   ['firstname','middlename','lastname','generation','id',
                   5256:                     'permanentemail'],
1.134     albertel 5257: 		   $udom,$uname);
1.313     matthew  5258:     my %names;
                   5259:     if ($tmp[0] =~ m/^error:.*/) { 
                   5260:         %names=(); 
                   5261:     } else {
                   5262:         %names = @tmp;
                   5263:     }
1.388     www      5264: #
                   5265: # Make sure to not trash student environment if instructor does not bother
                   5266: # to supply name and email information
                   5267: #
                   5268:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5269:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5270:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5271:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5272:     if ($email) {
                   5273:        $email=~s/[^\w\@\.\-\,]//gs;
                   5274:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5275: 			   $names{'critnotification'} = $email;
                   5276: 			   $names{'permanentemail'} = $email; }
                   5277:     }
1.899     raeburn  5278:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5279:     my $reply = &put('environment', \%names, $udom,$uname);
                   5280:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5281:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5282:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5283:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5284:              $umode.', '.$first.', '.$middle.', '.
                   5285: 	     $last.', '.$gene.' by '.
1.620     albertel 5286:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5287:     return 'ok';
1.80      www      5288: }
                   5289: 
1.81      www      5290: # -------------------------------------------------------------- Modify student
1.80      www      5291: 
1.81      www      5292: sub modifystudent {
                   5293:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5294:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5295:     if (!$cid) {
1.620     albertel 5296: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5297: 	    return 'not_in_class';
                   5298: 	}
1.80      www      5299:     }
                   5300: # --------------------------------------------------------------- Make the user
1.81      www      5301:     my $reply=&modifyuser
1.209     matthew  5302: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5303:          $desiredhome,$email);
1.80      www      5304:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5305:     # This will cause &modify_student_enrollment to get the uid from the
                   5306:     # students environment
                   5307:     $uid = undef if (!$forceid);
1.455     albertel 5308:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5309: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5310:     return $reply;
                   5311: }
                   5312: 
                   5313: sub modify_student_enrollment {
1.515     raeburn  5314:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5315:     my ($cdom,$cnum,$chome);
                   5316:     if (!$cid) {
1.620     albertel 5317: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5318: 	    return 'not_in_class';
                   5319: 	}
1.620     albertel 5320: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5321: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5322:     } else {
                   5323: 	($cdom,$cnum)=split(/_/,$cid);
                   5324:     }
1.620     albertel 5325:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5326:     if (!$chome) {
1.457     raeburn  5327: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5328:     }
1.455     albertel 5329:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5330:     # Make sure the user exists
1.81      www      5331:     my $uhome=&homeserver($uname,$udom);
                   5332:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5333: 	return 'error: no such user';
                   5334:     }
1.297     matthew  5335:     # Get student data if we were not given enough information
                   5336:     if (!defined($first)  || $first  eq '' || 
                   5337:         !defined($last)   || $last   eq '' || 
                   5338:         !defined($uid)    || $uid    eq '' || 
                   5339:         !defined($middle) || $middle eq '' || 
                   5340:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5341:         # They did not supply us with enough data to enroll the student, so
                   5342:         # we need to pick up more information.
1.297     matthew  5343:         my %tmp = &get('environment',
1.294     matthew  5344:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5345:                        ,$udom,$uname);
                   5346: 
1.800     albertel 5347:         #foreach my $key (keys(%tmp)) {
                   5348:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5349:         #}
1.294     matthew  5350:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5351:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5352:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5353:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5354:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5355:     }
1.556     albertel 5356:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5357:     my $reply=cput('classlist',
                   5358: 		   {"$uname:$udom" => 
1.515     raeburn  5359: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5360: 		   $cdom,$cnum);
1.81      www      5361:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5362: 	return 'error: '.$reply;
1.652     albertel 5363:     } else {
                   5364: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5365:     }
1.297     matthew  5366:     # Add student role to user
1.83      www      5367:     my $uurl='/'.$cid;
1.81      www      5368:     $uurl=~s/\_/\//g;
                   5369:     if ($usec) {
                   5370: 	$uurl.='/'.$usec;
                   5371:     }
                   5372:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5373: }
                   5374: 
1.556     albertel 5375: sub format_name {
                   5376:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5377:     my $name;
                   5378:     if ($first ne 'lastname') {
                   5379: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5380:     } else {
                   5381: 	if ($lastname=~/\S/) {
                   5382: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5383: 	    $name=~s/\s+,/,/;
                   5384: 	} else {
                   5385: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5386: 	}
                   5387:     }
                   5388:     $name=~s/^\s+//;
                   5389:     $name=~s/\s+$//;
                   5390:     $name=~s/\s+/ /g;
                   5391:     return $name;
                   5392: }
                   5393: 
1.84      www      5394: # ------------------------------------------------- Write to course preferences
                   5395: 
                   5396: sub writecoursepref {
                   5397:     my ($courseid,%prefs)=@_;
                   5398:     $courseid=~s/^\///;
                   5399:     $courseid=~s/\_/\//g;
                   5400:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5401:     my $chome=homeserver($cnum,$cdomain);
                   5402:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5403: 	return 'error: no such course';
                   5404:     }
                   5405:     my $cstring='';
1.800     albertel 5406:     foreach my $pref (keys(%prefs)) {
                   5407: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5408:     }
1.84      www      5409:     $cstring=~s/\&$//;
                   5410:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5411: }
                   5412: 
                   5413: # ---------------------------------------------------------- Make/modify course
                   5414: 
                   5415: sub createcourse {
1.741     raeburn  5416:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5417:         $course_owner,$crstype)=@_;
1.84      www      5418:     $url=&declutter($url);
                   5419:     my $cid='';
1.264     matthew  5420:     unless (&allowed('ccc',$udom)) {
1.84      www      5421:         return 'refused';
                   5422:     }
                   5423: # ------------------------------------------------------------------- Create ID
1.674     www      5424:    my $uname=int(1+rand(9)).
                   5425:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5426:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5427:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5428: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5429:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5430:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5431:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5432:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5433:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5434:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5435:            return 'error: unable to generate unique course-ID';
                   5436:        } 
                   5437:    }
1.264     matthew  5438: # ------------------------------------------------ Check supplied server name
1.620     albertel 5439:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5440:     if (! &is_library($course_server)) {
1.264     matthew  5441:         return 'error:bad server name '.$course_server;
                   5442:     }
1.84      www      5443: # ------------------------------------------------------------- Make the course
                   5444:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5445:                       $course_server);
1.84      www      5446:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5447:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5448:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5449: 	return 'error: no such course';
                   5450:     }
1.271     www      5451: # ----------------------------------------------------------------- Course made
1.516     raeburn  5452: # log existence
                   5453:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5454:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5455:                   &escape($crstype),$uhome);
1.358     www      5456:     &flushcourselogs();
                   5457: # set toplevel url
1.271     www      5458:     my $topurl=$url;
                   5459:     unless ($nonstandard) {
                   5460: # ------------------------------------------ For standard courses, make top url
                   5461:         my $mapurl=&clutter($url);
1.278     www      5462:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5463:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5464: <map>
                   5465: <resource id="1" type="start"></resource>
                   5466: <resource id="2" src="$mapurl"></resource>
                   5467: <resource id="3" type="finish"></resource>
                   5468: <link index="1" from="1" to="2"></link>
                   5469: <link index="2" from="2" to="3"></link>
                   5470: </map>
                   5471: ENDINITMAP
                   5472:         $topurl=&declutter(
1.638     albertel 5473:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5474:                           );
                   5475:     }
                   5476: # ----------------------------------------------------------- Write preferences
1.84      www      5477:     &writecoursepref($udom.'_'.$uname,
                   5478:                      ('description' => $description,
1.271     www      5479:                       'url'         => $topurl));
1.84      www      5480:     return '/'.$udom.'/'.$uname;
                   5481: }
                   5482: 
1.813     albertel 5483: sub is_course {
                   5484:     my ($cdom,$cnum) = @_;
                   5485:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5486: 				undef,'.');
                   5487:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5488:         return 1;
                   5489:     }
                   5490:     return 0;
                   5491: }
                   5492: 
1.21      www      5493: # ---------------------------------------------------------- Assign Custom Role
                   5494: 
                   5495: sub assigncustomrole {
1.357     www      5496:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5497:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5498:                        $end,$start,$deleteflag);
1.21      www      5499: }
                   5500: 
                   5501: # ----------------------------------------------------------------- Revoke Role
                   5502: 
                   5503: sub revokerole {
1.357     www      5504:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5505:     my $now=time;
1.357     www      5506:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5507: }
                   5508: 
                   5509: # ---------------------------------------------------------- Revoke Custom Role
                   5510: 
                   5511: sub revokecustomrole {
1.357     www      5512:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5513:     my $now=time;
1.357     www      5514:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5515:            $deleteflag);
1.17      www      5516: }
                   5517: 
1.533     banghart 5518: # ------------------------------------------------------------ Disk usage
1.535     albertel 5519: sub diskusage {
1.533     banghart 5520:     my ($udom,$uname,$directoryRoot)=@_;
                   5521:     $directoryRoot =~ s/\/$//;
1.535     albertel 5522:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5523:     return $listing;
1.512     banghart 5524: }
                   5525: 
1.566     banghart 5526: sub is_locked {
                   5527:     my ($file_name, $domain, $user) = @_;
                   5528:     my @check;
                   5529:     my $is_locked;
                   5530:     push @check, $file_name;
1.613     albertel 5531:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5532: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5533:     my ($tmp)=keys(%locked);
                   5534:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5535:     
1.566     banghart 5536:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5537:         $is_locked = 'false';
                   5538:         foreach my $entry (@{$locked{$file_name}}) {
                   5539:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5540:                $is_locked = 'true';
                   5541:                last;
1.745     raeburn  5542:            }
                   5543:        }
1.566     banghart 5544:     } else {
                   5545:         $is_locked = 'false';
                   5546:     }
                   5547: }
                   5548: 
1.759     albertel 5549: sub declutter_portfile {
                   5550:     my ($file) = @_;
1.833     albertel 5551:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5552:     return $file;
                   5553: }
                   5554: 
1.559     banghart 5555: # ------------------------------------------------------------- Mark as Read Only
                   5556: 
                   5557: sub mark_as_readonly {
                   5558:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5559:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5560:     my ($tmp)=keys(%current_permissions);
                   5561:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5562:     foreach my $file (@{$files}) {
1.759     albertel 5563: 	$file = &declutter_portfile($file);
1.561     banghart 5564:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5565:     }
1.613     albertel 5566:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5567:     return;
                   5568: }
                   5569: 
1.572     banghart 5570: # ------------------------------------------------------------Save Selected Files
                   5571: 
                   5572: sub save_selected_files {
                   5573:     my ($user, $path, @files) = @_;
                   5574:     my $filename = $user."savedfiles";
1.573     banghart 5575:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5576:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5577:     foreach my $file (@files) {
1.620     albertel 5578:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5579:     }
                   5580:     foreach my $file (@other_files) {
1.574     banghart 5581:         print (OUT $file."\n");
1.572     banghart 5582:     }
1.574     banghart 5583:     close (OUT);
1.572     banghart 5584:     return 'ok';
                   5585: }
                   5586: 
1.574     banghart 5587: sub clear_selected_files {
                   5588:     my ($user) = @_;
                   5589:     my $filename = $user."savedfiles";
                   5590:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5591:     print (OUT undef);
                   5592:     close (OUT);
                   5593:     return ("ok");    
                   5594: }
                   5595: 
1.572     banghart 5596: sub files_in_path {
                   5597:     my ($user, $path) = @_;
                   5598:     my $filename = $user."savedfiles";
                   5599:     my %return_files;
1.574     banghart 5600:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5601:     while (my $line_in = <IN>) {
1.574     banghart 5602:         chomp ($line_in);
                   5603:         my @paths_and_file = split (m!/!, $line_in);
                   5604:         my $file_part = pop (@paths_and_file);
                   5605:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5606:         $path_part.='/';
                   5607:         my $path_and_file = $path_part.$file_part;
                   5608:         if ($path_part eq $path) {
                   5609:             $return_files{$file_part}= 'selected';
                   5610:         }
                   5611:     }
1.574     banghart 5612:     close (IN);
                   5613:     return (\%return_files);
1.572     banghart 5614: }
                   5615: 
                   5616: # called in portfolio select mode, to show files selected NOT in current directory
                   5617: sub files_not_in_path {
                   5618:     my ($user, $path) = @_;
                   5619:     my $filename = $user."savedfiles";
                   5620:     my @return_files;
                   5621:     my $path_part;
1.800     albertel 5622:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5623:     while (my $line = <IN>) {
1.572     banghart 5624:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5625:         my @paths_and_file = split(m|/|, $line);
                   5626:         my $file_part = pop(@paths_and_file);
                   5627:         chomp($file_part);
                   5628:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5629:         $path_part .= '/';
                   5630:         my $path_and_file = $path_part.$file_part;
                   5631:         if ($path_part ne $path) {
1.800     albertel 5632:             push(@return_files, ($path_and_file));
1.572     banghart 5633:         }
                   5634:     }
1.800     albertel 5635:     close(OUT);
1.574     banghart 5636:     return (@return_files);
1.572     banghart 5637: }
                   5638: 
1.745     raeburn  5639: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5640: 
1.745     raeburn  5641: sub get_portfile_permissions {
                   5642:     my ($domain,$user) = @_;
1.613     albertel 5643:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5644:     my ($tmp)=keys(%current_permissions);
                   5645:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5646:     return \%current_permissions;
                   5647: }
                   5648: 
                   5649: #---------------------------------------------Get portfolio file access controls
                   5650: 
1.749     raeburn  5651: sub get_access_controls {
1.745     raeburn  5652:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5653:     my %access;
                   5654:     my $real_file = $file;
                   5655:     $file =~ s/\.meta$//;
1.745     raeburn  5656:     if (defined($file)) {
1.749     raeburn  5657:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5658:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5659:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5660:             }
                   5661:         }
1.745     raeburn  5662:     } else {
1.749     raeburn  5663:         foreach my $key (keys(%{$current_permissions})) {
                   5664:             if ($key =~ /\0accesscontrol$/) {
                   5665:                 if (defined($group)) {
                   5666:                     if ($key !~ m-^\Q$group\E/-) {
                   5667:                         next;
                   5668:                     }
                   5669:                 }
                   5670:                 my ($fullpath) = split(/\0/,$key);
                   5671:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5672:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5673:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5674:                     }
                   5675:                 }
                   5676:             }
                   5677:         }
                   5678:     }
                   5679:     return %access;
                   5680: }
                   5681: 
                   5682: sub modify_access_controls {
                   5683:     my ($file_name,$changes,$domain,$user)=@_;
                   5684:     my ($outcome,$deloutcome);
                   5685:     my %store_permissions;
                   5686:     my %new_values;
                   5687:     my %new_control;
                   5688:     my %translation;
                   5689:     my @deletions = ();
                   5690:     my $now = time;
                   5691:     if (exists($$changes{'activate'})) {
                   5692:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5693:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5694:             my $numnew = scalar(@newitems);
                   5695:             for (my $i=0; $i<$numnew; $i++) {
                   5696:                 my $newkey = $newitems[$i];
                   5697:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5698:                 if ($newkey =~ /^\d+:/) { 
                   5699:                     $newkey =~ s/^(\d+)/$newid/;
                   5700:                     $translation{$1} = $newid;
                   5701:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5702:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5703:                     $translation{$1} = $newid;
                   5704:                 }
1.749     raeburn  5705:                 $new_values{$file_name."\0".$newkey} = 
                   5706:                                           $$changes{'activate'}{$newitems[$i]};
                   5707:                 $new_control{$newkey} = $now;
                   5708:             }
                   5709:         }
                   5710:     }
                   5711:     my %todelete;
                   5712:     my %changed_items;
                   5713:     foreach my $action ('delete','update') {
                   5714:         if (exists($$changes{$action})) {
                   5715:             if (ref($$changes{$action}) eq 'HASH') {
                   5716:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5717:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5718:                     if ($action eq 'delete') { 
                   5719:                         $todelete{$itemnum} = 1;
                   5720:                     } else {
                   5721:                         $changed_items{$itemnum} = $key;
                   5722:                     }
                   5723:                 }
1.745     raeburn  5724:             }
                   5725:         }
1.749     raeburn  5726:     }
                   5727:     # get lock on access controls for file.
                   5728:     my $lockhash = {
                   5729:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5730:                                                        ':'.$env{'user.domain'},
                   5731:                    }; 
                   5732:     my $tries = 0;
                   5733:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5734:    
                   5735:     while (($gotlock ne 'ok') && $tries <3) {
                   5736:         $tries ++;
                   5737:         sleep 1;
                   5738:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5739:     }
                   5740:     if ($gotlock eq 'ok') {
                   5741:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5742:         my ($tmp)=keys(%curr_permissions);
                   5743:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5744:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5745:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5746:             if (ref($curr_controls) eq 'HASH') {
                   5747:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5748:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5749:                     if (defined($todelete{$itemnum})) {
                   5750:                         push(@deletions,$file_name."\0".$control_item);
                   5751:                     } else {
                   5752:                         if (defined($changed_items{$itemnum})) {
                   5753:                             $new_control{$changed_items{$itemnum}} = $now;
                   5754:                             push(@deletions,$file_name."\0".$control_item);
                   5755:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5756:                         } else {
                   5757:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5758:                         }
                   5759:                     }
1.745     raeburn  5760:                 }
                   5761:             }
                   5762:         }
1.749     raeburn  5763:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5764:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5765:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5766:         #  remove lock
                   5767:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5768:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5769:         my ($file,$group);
                   5770:         if (&is_course($domain,$user)) {
                   5771:             ($group,$file) = split(/\//,$file_name,2);
                   5772:         } else {
                   5773:             $file = $file_name;
                   5774:         }
                   5775:         my $sqlresult =
                   5776:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5777:                                     $group);
1.749     raeburn  5778:     } else {
                   5779:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5780:     }
1.749     raeburn  5781:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5782: }
                   5783: 
1.827     raeburn  5784: sub make_public_indefinitely {
                   5785:     my ($requrl) = @_;
                   5786:     my $now = time;
                   5787:     my $action = 'activate';
                   5788:     my $aclnum = 0;
                   5789:     if (&is_portfolio_url($requrl)) {
                   5790:         my (undef,$udom,$unum,$file_name,$group) =
                   5791:             &parse_portfolio_url($requrl);
                   5792:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5793:         my %access_controls = &get_access_controls($current_perms,
                   5794:                                                    $group,$file_name);
                   5795:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5796:             my ($num,$scope,$end,$start) = 
                   5797:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5798:             if ($scope eq 'public') {
                   5799:                 if ($start <= $now && $end == 0) {
                   5800:                     $action = 'none';
                   5801:                 } else {
                   5802:                     $action = 'update';
                   5803:                     $aclnum = $num;
                   5804:                 }
                   5805:                 last;
                   5806:             }
                   5807:         }
                   5808:         if ($action eq 'none') {
                   5809:              return 'ok';
                   5810:         } else {
                   5811:             my %changes;
                   5812:             my $newend = 0;
                   5813:             my $newstart = $now;
                   5814:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5815:             $changes{$action}{$newkey} = {
                   5816:                 type => 'public',
                   5817:                 time => {
                   5818:                     start => $newstart,
                   5819:                     end   => $newend,
                   5820:                 },
                   5821:             };
                   5822:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5823:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5824:             return $outcome;
                   5825:         }
                   5826:     } else {
                   5827:         return 'invalid';
                   5828:     }
                   5829: }
                   5830: 
1.745     raeburn  5831: #------------------------------------------------------Get Marked as Read Only
                   5832: 
                   5833: sub get_marked_as_readonly {
                   5834:     my ($domain,$user,$what,$group) = @_;
                   5835:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5836:     my @readonly_files;
1.629     banghart 5837:     my $cmp1=$what;
                   5838:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5839:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5840:         if (defined($group)) {
                   5841:             if ($file_name !~ m-^\Q$group\E/-) {
                   5842:                 next;
                   5843:             }
                   5844:         }
1.561     banghart 5845:         if (ref($value) eq "ARRAY"){
                   5846:             foreach my $stored_what (@{$value}) {
1.629     banghart 5847:                 my $cmp2=$stored_what;
1.759     albertel 5848:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5849:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5850:                 }
1.629     banghart 5851:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5852:                     push(@readonly_files, $file_name);
1.745     raeburn  5853:                     last;
1.563     banghart 5854:                 } elsif (!defined($what)) {
                   5855:                     push(@readonly_files, $file_name);
1.745     raeburn  5856:                     last;
1.561     banghart 5857:                 }
                   5858:             }
1.745     raeburn  5859:         }
1.561     banghart 5860:     }
                   5861:     return @readonly_files;
                   5862: }
1.577     banghart 5863: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5864: 
1.577     banghart 5865: sub get_marked_as_readonly_hash {
1.745     raeburn  5866:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5867:     my %readonly_files;
1.745     raeburn  5868:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5869:         if (defined($group)) {
                   5870:             if ($file_name !~ m-^\Q$group\E/-) {
                   5871:                 next;
                   5872:             }
                   5873:         }
1.577     banghart 5874:         if (ref($value) eq "ARRAY"){
                   5875:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5876:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5877:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5878:                         if ($lock_descriptor eq 'graded') {
                   5879:                             $readonly_files{$file_name} = 'graded';
                   5880:                         } elsif ($lock_descriptor eq 'handback') {
                   5881:                             $readonly_files{$file_name} = 'handback';
                   5882:                         } else {
                   5883:                             if (!exists($readonly_files{$file_name})) {
                   5884:                                 $readonly_files{$file_name} = 'locked';
                   5885:                             }
                   5886:                         }
1.745     raeburn  5887:                     }
1.750     banghart 5888:                 } 
1.577     banghart 5889:             }
                   5890:         } 
                   5891:     }
                   5892:     return %readonly_files;
                   5893: }
1.559     banghart 5894: # ------------------------------------------------------------ Unmark as Read Only
                   5895: 
                   5896: sub unmark_as_readonly {
1.629     banghart 5897:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5898:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5899:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5900:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5901:     my $symb_crs = $what;
                   5902:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5903:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5904:     my ($tmp)=keys(%current_permissions);
                   5905:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5906:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5907:     foreach my $file (@readonly_files) {
1.759     albertel 5908: 	my $clean_file = &declutter_portfile($file);
                   5909: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5910: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5911:         my @new_locks;
                   5912:         my @del_keys;
                   5913:         if (ref($current_locks) eq "ARRAY"){
                   5914:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5915:                 my $compare=$locker;
1.749     raeburn  5916:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5917:                     $compare=join('',@{$locker});
1.746     raeburn  5918:                     if ($compare ne $symb_crs) {
                   5919:                         push(@new_locks, $locker);
                   5920:                     }
1.563     banghart 5921:                 }
                   5922:             }
1.650     albertel 5923:             if (scalar(@new_locks) > 0) {
1.563     banghart 5924:                 $current_permissions{$file} = \@new_locks;
                   5925:             } else {
                   5926:                 push(@del_keys, $file);
1.613     albertel 5927:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5928:                 delete($current_permissions{$file});
1.563     banghart 5929:             }
                   5930:         }
1.561     banghart 5931:     }
1.613     albertel 5932:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5933:     return;
                   5934: }
1.512     banghart 5935: 
1.17      www      5936: # ------------------------------------------------------------ Directory lister
                   5937: 
                   5938: sub dirlist {
1.253     stredwic 5939:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5940: 
1.18      www      5941:     $uri=~s/^\///;
                   5942:     $uri=~s/\/$//;
1.253     stredwic 5943:     my ($udom, $uname);
                   5944:     (undef,$udom,$uname)=split(/\//,$uri);
                   5945:     if(defined($userdomain)) {
                   5946:         $udom = $userdomain;
                   5947:     }
                   5948:     if(defined($username)) {
                   5949:         $uname = $username;
                   5950:     }
                   5951: 
                   5952:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5953:     if(defined($alternateDirectoryRoot)) {
                   5954:         $dirRoot = $alternateDirectoryRoot;
                   5955:         $dirRoot =~ s/\/$//;
1.751     banghart 5956:     }
1.253     stredwic 5957: 
                   5958:     if($udom) {
                   5959:         if($uname) {
1.800     albertel 5960:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5961: 				 &homeserver($uname,$udom));
1.605     matthew  5962:             my @listing_results;
                   5963:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5964:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5965: 				  &homeserver($uname,$udom));
1.605     matthew  5966:                 @listing_results = split(/:/,$listing);
                   5967:             } else {
                   5968:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5969:             }
                   5970:             return @listing_results;
1.253     stredwic 5971:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5972:             my %allusers;
1.841     albertel 5973: 	    my %servers = &get_servers($udom,'library');
                   5974: 	    foreach my $tryserver (keys(%servers)) {
                   5975: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5976: 				     $udom, $tryserver);
                   5977: 		my @listing_results;
                   5978: 		if ($listing eq 'unknown_cmd') {
                   5979: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5980: 				      $udom, $tryserver);
                   5981: 		    @listing_results = split(/:/,$listing);
                   5982: 		} else {
                   5983: 		    @listing_results =
                   5984: 			map { &unescape($_); } split(/:/,$listing);
                   5985: 		}
                   5986: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5987: 		    $listing_results[0] ne 'empty'       &&
                   5988: 		    $listing_results[0] ne 'con_lost') {
                   5989: 		    foreach my $line (@listing_results) {
                   5990: 			my ($entry) = split(/&/,$line,2);
                   5991: 			$allusers{$entry} = 1;
                   5992: 		    }
                   5993: 		}
1.253     stredwic 5994:             }
                   5995:             my $alluserstr='';
1.800     albertel 5996:             foreach my $user (sort(keys(%allusers))) {
                   5997:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5998:             }
                   5999:             $alluserstr=~s/:$//;
                   6000:             return split(/:/,$alluserstr);
                   6001:         } else {
1.800     albertel 6002:             return ('missing user name');
1.253     stredwic 6003:         }
                   6004:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6005:         my @all_domains = sort(&all_domains());
                   6006:          foreach my $domain (@all_domains) {
                   6007:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6008:          }
                   6009:          return @all_domains;
                   6010:      } else {
1.800     albertel 6011:         return ('missing domain');
1.275     stredwic 6012:     }
                   6013: }
                   6014: 
                   6015: # --------------------------------------------- GetFileTimestamp
                   6016: # This function utilizes dirlist and returns the date stamp for
                   6017: # when it was last modified.  It will also return an error of -1
                   6018: # if an error occurs
                   6019: 
1.410     matthew  6020: ##
                   6021: ## FIXME: This subroutine assumes its caller knows something about the
                   6022: ## directory structure of the home server for the student ($root).
                   6023: ## Not a good assumption to make.  Since this is for looking up files
                   6024: ## in user directories, the full path should be constructed by lond, not
                   6025: ## whatever machine we request data from.
                   6026: ##
1.275     stredwic 6027: sub GetFileTimestamp {
                   6028:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6029:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6030:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6031:     my $subdir=$studentName.'__';
                   6032:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6033:     my $proname="$studentDomain/$subdir/$studentName";
                   6034:     $proname .= '/'.$filename;
1.375     matthew  6035:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6036:                                               $studentName, $root);
1.275     stredwic 6037:     my @stats = split('&', $fileStat);
                   6038:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6039:         # @stats contains first the filename, then the stat output
                   6040:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6041:     } else {
                   6042:         return -1;
1.253     stredwic 6043:     }
1.26      www      6044: }
                   6045: 
1.712     albertel 6046: sub stat_file {
                   6047:     my ($uri) = @_;
1.787     albertel 6048:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6049: 
1.712     albertel 6050:     my ($udom,$uname,$file,$dir);
                   6051:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6052: 	($udom,$uname,$file) =
1.811     albertel 6053: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6054: 	$file = 'userfiles/'.$file;
1.740     www      6055: 	$dir = &propath($udom,$uname);
1.712     albertel 6056:     }
                   6057:     if ($uri =~ m-^/res/-) {
                   6058: 	($udom,$uname) = 
1.807     albertel 6059: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6060: 	$file = $uri;
                   6061:     }
                   6062: 
                   6063:     if (!$udom || !$uname || !$file) {
                   6064: 	# unable to handle the uri
                   6065: 	return ();
                   6066:     }
                   6067: 
                   6068:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6069:     my @stats = split('&', $result);
1.721     banghart 6070:     
1.712     albertel 6071:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6072: 	shift(@stats); #filename is first
                   6073: 	return @stats;
                   6074:     }
                   6075:     return ();
                   6076: }
                   6077: 
1.26      www      6078: # -------------------------------------------------------- Value of a Condition
                   6079: 
1.713     albertel 6080: # gets the value of a specific preevaluated condition
                   6081: #    stored in the string  $env{user.state.<cid>}
                   6082: # or looks up a condition reference in the bighash and if if hasn't
                   6083: # already been evaluated recurses into docondval to get the value of
                   6084: # the condition, then memoizing it to 
                   6085: #   $env{user.state.<cid>.<condition>}
1.40      www      6086: sub directcondval {
                   6087:     my $number=shift;
1.620     albertel 6088:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6089: 	&Apache::lonuserstate::evalstate();
                   6090:     }
1.713     albertel 6091:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6092: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6093:     } elsif ($number =~ /^_/) {
                   6094: 	my $sub_condition;
                   6095: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6096: 		&GDBM_READER(),0640)) {
                   6097: 	    $sub_condition=$bighash{'conditions'.$number};
                   6098: 	    untie(%bighash);
                   6099: 	}
                   6100: 	my $value = &docondval($sub_condition);
                   6101: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6102: 	return $value;
                   6103:     }
1.620     albertel 6104:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6105:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6106:     } else {
                   6107:        return 2;
                   6108:     }
                   6109: }
                   6110: 
1.713     albertel 6111: # get the collection of conditions for this resource
1.26      www      6112: sub condval {
                   6113:     my $condidx=shift;
1.54      www      6114:     my $allpathcond='';
1.713     albertel 6115:     foreach my $cond (split(/\|/,$condidx)) {
                   6116: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6117: 	    $allpathcond.=
                   6118: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6119: 	}
1.191     harris41 6120:     }
1.54      www      6121:     $allpathcond=~s/\|$//;
1.713     albertel 6122:     return &docondval($allpathcond);
                   6123: }
                   6124: 
                   6125: #evaluates an expression of conditions
                   6126: sub docondval {
                   6127:     my ($allpathcond) = @_;
                   6128:     my $result=0;
                   6129:     if ($env{'request.course.id'}
                   6130: 	&& defined($allpathcond)) {
                   6131: 	my $operand='|';
                   6132: 	my @stack;
                   6133: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6134: 	    if ($chunk eq '(') {
                   6135: 		push @stack,($operand,$result);
                   6136: 	    } elsif ($chunk eq ')') {
                   6137: 		my $before=pop @stack;
                   6138: 		if (pop @stack eq '&') {
                   6139: 		    $result=$result>$before?$before:$result;
                   6140: 		} else {
                   6141: 		    $result=$result>$before?$result:$before;
                   6142: 		}
                   6143: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6144: 		$operand=$chunk;
                   6145: 	    } else {
                   6146: 		my $new=directcondval($chunk);
                   6147: 		if ($operand eq '&') {
                   6148: 		    $result=$result>$new?$new:$result;
                   6149: 		} else {
                   6150: 		    $result=$result>$new?$result:$new;
                   6151: 		}
                   6152: 	    }
                   6153: 	}
1.26      www      6154:     }
                   6155:     return $result;
1.421     albertel 6156: }
                   6157: 
                   6158: # ---------------------------------------------------- Devalidate courseresdata
                   6159: 
                   6160: sub devalidatecourseresdata {
                   6161:     my ($coursenum,$coursedomain)=@_;
                   6162:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6163:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6164: }
                   6165: 
1.763     www      6166: 
1.200     www      6167: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6168: #
                   6169: #  Parameters:
                   6170: #      $coursenum    - Number of the course.
                   6171: #      $coursedomain - Domain at which the course was created.
                   6172: #  Returns:
                   6173: #     A hash of the course parameters along (I think) with timestamps
                   6174: #     and version info.
1.877     foxr     6175: 
1.624     albertel 6176: sub get_courseresdata {
                   6177:     my ($coursenum,$coursedomain)=@_;
1.200     www      6178:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6179:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6180:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6181:     my %dumpreply;
1.417     albertel 6182:     unless (defined($cached)) {
1.624     albertel 6183: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6184: 	$result=\%dumpreply;
1.251     albertel 6185: 	my ($tmp) = keys(%dumpreply);
                   6186: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6187: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6188: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6189: 	    return $tmp;
1.416     albertel 6190: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6191: 	    $result=undef;
1.599     albertel 6192: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6193: 	}
                   6194:     }
1.624     albertel 6195:     return $result;
                   6196: }
                   6197: 
1.633     albertel 6198: sub devalidateuserresdata {
                   6199:     my ($uname,$udom)=@_;
                   6200:     my $hashid="$udom:$uname";
                   6201:     &devalidate_cache_new('userres',$hashid);
                   6202: }
                   6203: 
1.624     albertel 6204: sub get_userresdata {
                   6205:     my ($uname,$udom)=@_;
                   6206:     #most student don\'t have any data set, check if there is some data
                   6207:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6208: 
                   6209:     my $hashid="$udom:$uname";
                   6210:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6211:     if (!defined($cached)) {
                   6212: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6213: 	$result=\%resourcedata;
                   6214: 	&do_cache_new('userres',$hashid,$result,600);
                   6215:     }
                   6216:     my ($tmp)=keys(%$result);
                   6217:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6218: 	return $result;
                   6219:     }
                   6220:     #error 2 occurs when the .db doesn't exist
                   6221:     if ($tmp!~/error: 2 /) {
1.672     albertel 6222: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6223: 		 " Trying to get resource data for ".
                   6224: 		 $uname." at ".$udom.": ".
                   6225: 		 $tmp."</font>");
                   6226:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6227: 	#&EXT_cache_set($udom,$uname);
                   6228: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6229: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6230:     }
                   6231:     return $tmp;
                   6232: }
1.879     foxr     6233: #----------------------------------------------- resdata - return resource data
                   6234: #  Purpose:
                   6235: #    Return resource data for either users or for a course.
                   6236: #  Parameters:
                   6237: #     $name      - Course/user name.
                   6238: #     $domain    - Name of the domain the user/course is registered on.
                   6239: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6240: #     @which     - Array of names of resources desired.
                   6241: #  Returns:
                   6242: #     The value of the first reasource in @which that is found in the
                   6243: #     resource hash.
                   6244: #  Exceptional Conditions:
                   6245: #     If the $type passed in is not valid (not the string 'course' or 
                   6246: #     'user', an undefined  reference is returned.
                   6247: #     If none of the resources are found, an undef is returned
1.624     albertel 6248: sub resdata {
                   6249:     my ($name,$domain,$type,@which)=@_;
                   6250:     my $result;
                   6251:     if ($type eq 'course') {
                   6252: 	$result=&get_courseresdata($name,$domain);
                   6253:     } elsif ($type eq 'user') {
                   6254: 	$result=&get_userresdata($name,$domain);
                   6255:     }
                   6256:     if (!ref($result)) { return $result; }    
1.251     albertel 6257:     foreach my $item (@which) {
1.417     albertel 6258: 	if (defined($result->{$item})) {
                   6259: 	    return $result->{$item};
1.251     albertel 6260: 	}
1.250     albertel 6261:     }
1.291     albertel 6262:     return undef;
1.200     www      6263: }
                   6264: 
1.379     matthew  6265: #
                   6266: # EXT resource caching routines
                   6267: #
                   6268: 
                   6269: sub clear_EXT_cache_status {
1.383     albertel 6270:     &delenv('cache.EXT.');
1.379     matthew  6271: }
                   6272: 
                   6273: sub EXT_cache_status {
                   6274:     my ($target_domain,$target_user) = @_;
1.383     albertel 6275:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6276:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6277:         # We know already the user has no data
                   6278:         return 1;
                   6279:     } else {
                   6280:         return 0;
                   6281:     }
                   6282: }
                   6283: 
                   6284: sub EXT_cache_set {
                   6285:     my ($target_domain,$target_user) = @_;
1.383     albertel 6286:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6287:     #&appenv($cachename => time);
1.379     matthew  6288: }
                   6289: 
1.28      www      6290: # --------------------------------------------------------- Value of a Variable
1.58      www      6291: sub EXT {
1.715     albertel 6292: 
1.395     albertel 6293:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6294:     unless ($varname) { return ''; }
1.218     albertel 6295:     #get real user name/domain, courseid and symb
                   6296:     my $courseid;
1.359     albertel 6297:     my $publicuser;
1.427     www      6298:     if ($symbparm) {
                   6299: 	$symbparm=&get_symb_from_alias($symbparm);
                   6300:     }
1.218     albertel 6301:     if (!($uname && $udom)) {
1.790     albertel 6302:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6303:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6304:     } else {
1.620     albertel 6305: 	$courseid=$env{'request.course.id'};
1.218     albertel 6306:     }
1.48      www      6307:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6308:     my $rest;
1.320     albertel 6309:     if (defined($therest[0])) {
1.48      www      6310:        $rest=join('.',@therest);
                   6311:     } else {
                   6312:        $rest='';
                   6313:     }
1.320     albertel 6314: 
1.57      www      6315:     my $qualifierrest=$qualifier;
                   6316:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6317:     my $spacequalifierrest=$space;
                   6318:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6319:     if ($realm eq 'user') {
1.48      www      6320: # --------------------------------------------------------------- user.resource
                   6321: 	if ($space eq 'resource') {
1.651     albertel 6322: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6323: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6324: 		 &&
1.744     albertel 6325: 		 ($symbparm eq &symbread()) ) {	
                   6326: 		# if we are in the middle of processing the resource the
                   6327: 		# get the value we are planning on committing
                   6328:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6329:                     return $Apache::lonhomework::results{$qualifierrest};
                   6330:                 } else {
                   6331:                     return $Apache::lonhomework::history{$qualifierrest};
                   6332:                 }
1.335     albertel 6333: 	    } else {
1.359     albertel 6334: 		my %restored;
1.620     albertel 6335: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6336: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6337: 		} else {
                   6338: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6339: 		}
1.335     albertel 6340: 		return $restored{$qualifierrest};
                   6341: 	    }
1.48      www      6342: # ----------------------------------------------------------------- user.access
                   6343:         } elsif ($space eq 'access') {
1.218     albertel 6344: 	    # FIXME - not supporting calls for a specific user
1.48      www      6345:             return &allowed($qualifier,$rest);
                   6346: # ------------------------------------------ user.preferences, user.environment
                   6347:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6348: 	    if (($uname eq $env{'user.name'}) &&
                   6349: 		($udom eq $env{'user.domain'})) {
                   6350: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6351: 	    } else {
1.359     albertel 6352: 		my %returnhash;
                   6353: 		if (!$publicuser) {
                   6354: 		    %returnhash=&userenvironment($udom,$uname,
                   6355: 						 $qualifierrest);
                   6356: 		}
1.218     albertel 6357: 		return $returnhash{$qualifierrest};
                   6358: 	    }
1.48      www      6359: # ----------------------------------------------------------------- user.course
                   6360:         } elsif ($space eq 'course') {
1.218     albertel 6361: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6362:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6363: # ------------------------------------------------------------------- user.role
                   6364:         } elsif ($space eq 'role') {
1.218     albertel 6365: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6366:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6367:             if ($qualifier eq 'value') {
                   6368: 		return $role;
                   6369:             } elsif ($qualifier eq 'extent') {
                   6370:                 return $where;
                   6371:             }
                   6372: # ----------------------------------------------------------------- user.domain
                   6373:         } elsif ($space eq 'domain') {
1.218     albertel 6374:             return $udom;
1.48      www      6375: # ------------------------------------------------------------------- user.name
                   6376:         } elsif ($space eq 'name') {
1.218     albertel 6377:             return $uname;
1.48      www      6378: # ---------------------------------------------------- Any other user namespace
1.29      www      6379:         } else {
1.359     albertel 6380: 	    my %reply;
                   6381: 	    if (!$publicuser) {
                   6382: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6383: 	    }
                   6384: 	    return $reply{$qualifierrest};
1.48      www      6385:         }
1.236     www      6386:     } elsif ($realm eq 'query') {
                   6387: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6388:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6389: 						[$spacequalifierrest]);
1.620     albertel 6390: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6391:    } elsif ($realm eq 'request') {
1.48      www      6392: # ------------------------------------------------------------- request.browser
                   6393:         if ($space eq 'browser') {
1.430     www      6394: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6395: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6396: 		    return 1;
                   6397: 		} else {
                   6398: 		    return 0;
                   6399: 		}
                   6400: 	    } else {
1.620     albertel 6401: 		return $env{'browser.'.$qualifier};
1.430     www      6402: 	    }
1.57      www      6403: # ------------------------------------------------------------ request.filename
                   6404:         } else {
1.620     albertel 6405:             return $env{'request.'.$spacequalifierrest};
1.29      www      6406:         }
1.28      www      6407:     } elsif ($realm eq 'course') {
1.48      www      6408: # ---------------------------------------------------------- course.description
1.620     albertel 6409:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6410:     } elsif ($realm eq 'resource') {
1.165     www      6411: 
1.620     albertel 6412: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6413: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6414: 	}
1.693     albertel 6415: 
                   6416: 	if ($space eq 'title') {
                   6417: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6418: 	    return &gettitle($symbparm);
                   6419: 	}
                   6420: 	
                   6421: 	if ($space eq 'map') {
                   6422: 	    my ($map) = &decode_symb($symbparm);
                   6423: 	    return &symbread($map);
                   6424: 	}
1.905     albertel 6425: 	if ($space eq 'filename') {
                   6426: 	    if ($symbparm) {
                   6427: 		return &clutter((&decode_symb($symbparm))[2]);
                   6428: 	    }
                   6429: 	    return &hreflocation('',$env{'request.filename'});
                   6430: 	}
1.693     albertel 6431: 
                   6432: 	my ($section, $group, @groups);
1.593     albertel 6433: 	my ($courselevelm,$courselevel);
1.539     albertel 6434: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6435: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6436: 
1.218     albertel 6437: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6438: 
1.60      www      6439: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6440: 	    my $symbp=$symbparm;
1.735     albertel 6441: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6442: 
                   6443: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6444: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6445: 
1.620     albertel 6446: 	    if (($env{'user.name'} eq $uname) &&
                   6447: 		($env{'user.domain'} eq $udom)) {
                   6448: 		$section=$env{'request.course.sec'};
1.733     raeburn  6449:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6450:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6451: 	    } else {
1.539     albertel 6452: 		if (! defined($usection)) {
1.551     albertel 6453: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6454: 		} else {
                   6455: 		    $section = $usection;
                   6456: 		}
1.733     raeburn  6457:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6458: 	    }
                   6459: 
                   6460: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6461: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6462: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6463: 
1.593     albertel 6464: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6465: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6466: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6467: 
1.60      www      6468: # ----------------------------------------------------------- first, check user
1.624     albertel 6469: 
                   6470: 	    my $userreply=&resdata($uname,$udom,'user',
                   6471: 				       ($courselevelr,$courselevelm,
                   6472: 					$courselevel));
                   6473: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6474: 
1.594     albertel 6475: # ------------------------------------------------ second, check some of course
1.684     raeburn  6476:             my $coursereply;
1.691     raeburn  6477:             if (@groups > 0) {
                   6478:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6479:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6480:                 if (defined($coursereply)) { return $coursereply; }
                   6481:             }
1.96      www      6482: 
1.684     raeburn  6483: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6484: 				     $env{'course.'.$courseid.'.domain'},
                   6485: 				     'course',
                   6486: 				     ($seclevelr,$seclevelm,$seclevel,
                   6487: 				      $courselevelr));
1.287     albertel 6488: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6489: 
1.60      www      6490: # ------------------------------------------------------ third, check map parms
1.218     albertel 6491: 	    my %parmhash=();
                   6492: 	    my $thisparm='';
                   6493: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6494: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6495: 		    &GDBM_READER(),0640)) {
1.218     albertel 6496: 		$thisparm=$parmhash{$symbparm};
                   6497: 		untie(%parmhash);
                   6498: 	    }
                   6499: 	    if ($thisparm) { return $thisparm; }
                   6500: 	}
1.594     albertel 6501: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6502: 
1.218     albertel 6503: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6504: 	my $filename;
                   6505: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6506: 	if ($symbparm) {
1.409     www      6507: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6508: 	} else {
1.620     albertel 6509: 	    $filename=$env{'request.filename'};
1.282     albertel 6510: 	}
                   6511: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6512: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6513: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6514: 	if (defined($metadata)) { return $metadata; }
1.142     www      6515: 
1.594     albertel 6516: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6517: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6518: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6519: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6520: 				     $env{'course.'.$courseid.'.domain'},
                   6521: 				     'course',
                   6522: 				     ($courselevelm,$courselevel));
1.593     albertel 6523: 	    if (defined($coursereply)) { return $coursereply; }
                   6524: 	}
1.145     www      6525: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6526: 	unless ($space eq '0') {
1.336     albertel 6527: 	    my @parts=split(/_/,$space);
                   6528: 	    my $id=pop(@parts);
                   6529: 	    my $part=join('_',@parts);
                   6530: 	    if ($part eq '') { $part='0'; }
                   6531: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6532: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6533: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6534: 	}
1.395     albertel 6535: 	if ($recurse) { return undef; }
                   6536: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6537: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6538: 
1.48      www      6539: # ---------------------------------------------------- Any other user namespace
                   6540:     } elsif ($realm eq 'environment') {
                   6541: # ----------------------------------------------------------------- environment
1.620     albertel 6542: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6543: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6544: 	} else {
1.770     albertel 6545: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6546: 		return '';
                   6547: 	    }
1.219     albertel 6548: 	    my %returnhash=&userenvironment($udom,$uname,
                   6549: 					    $spacequalifierrest);
                   6550: 	    return $returnhash{$spacequalifierrest};
                   6551: 	}
1.28      www      6552:     } elsif ($realm eq 'system') {
1.48      www      6553: # ----------------------------------------------------------------- system.time
                   6554: 	if ($space eq 'time') {
                   6555: 	    return time;
                   6556:         }
1.696     albertel 6557:     } elsif ($realm eq 'server') {
                   6558: # ----------------------------------------------------------------- system.time
                   6559: 	if ($space eq 'name') {
                   6560: 	    return $ENV{'SERVER_NAME'};
                   6561:         }
1.28      www      6562:     }
1.48      www      6563:     return '';
1.61      www      6564: }
                   6565: 
1.691     raeburn  6566: sub check_group_parms {
                   6567:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6568:     my @groupitems = ();
                   6569:     my $resultitem;
                   6570:     my @levels = ($symbparm,$mapparm,$what);
                   6571:     foreach my $group (@{$groups}) {
                   6572:         foreach my $level (@levels) {
                   6573:              my $item = $courseid.'.['.$group.'].'.$level;
                   6574:              push(@groupitems,$item);
                   6575:         }
                   6576:     }
                   6577:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6578:                             $env{'course.'.$courseid.'.domain'},
                   6579:                                      'course',@groupitems);
                   6580:     return $coursereply;
                   6581: }
                   6582: 
                   6583: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6584:     my ($courseid,@groups) = @_;
                   6585:     @groups = sort(@groups);
1.691     raeburn  6586:     return @groups;
                   6587: }
                   6588: 
1.395     albertel 6589: sub packages_tab_default {
                   6590:     my ($uri,$varname)=@_;
                   6591:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6592: 
                   6593:     my (@extension,@specifics,$do_default);
                   6594:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6595: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6596: 	if ($pack_type eq 'default') {
                   6597: 	    $do_default=1;
                   6598: 	} elsif ($pack_type eq 'extension') {
                   6599: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6600: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6601: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6602: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6603: 	}
                   6604:     }
                   6605:     # first look for a package that matches the requested part id
                   6606:     foreach my $package (@specifics) {
                   6607: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6608: 	next if ($pack_part ne $part);
                   6609: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6610: 	    return $packagetab{"$pack_type&$name&default"};
                   6611: 	}
                   6612:     }
                   6613:     # look for any possible matching non extension_ package
                   6614:     foreach my $package (@specifics) {
                   6615: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6616: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6617: 	    return $packagetab{"$pack_type&$name&default"};
                   6618: 	}
1.585     albertel 6619: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6620: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6621: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6622: 	}
                   6623:     }
1.738     albertel 6624:     # look for any posible extension_ match
                   6625:     foreach my $package (@extension) {
                   6626: 	my ($package,$pack_type)=@{$package};
                   6627: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6628: 	    return $packagetab{"$pack_type&$name&default"};
                   6629: 	}
                   6630: 	if (defined($packagetab{$package."&$name&default"})) {
                   6631: 	    return $packagetab{$package."&$name&default"};
                   6632: 	}
                   6633:     }
                   6634:     # look for a global default setting
                   6635:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6636: 	return $packagetab{"default&$name&default"};
                   6637:     }
1.395     albertel 6638:     return undef;
                   6639: }
                   6640: 
1.334     albertel 6641: sub add_prefix_and_part {
                   6642:     my ($prefix,$part)=@_;
                   6643:     my $keyroot;
                   6644:     if (defined($prefix) && $prefix !~ /^__/) {
                   6645: 	# prefix that has a part already
                   6646: 	$keyroot=$prefix;
                   6647:     } elsif (defined($prefix)) {
                   6648: 	# prefix that is missing a part
                   6649: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6650:     } else {
                   6651: 	# no prefix at all
                   6652: 	if (defined($part)) { $keyroot='_'.$part; }
                   6653:     }
                   6654:     return $keyroot;
                   6655: }
                   6656: 
1.71      www      6657: # ---------------------------------------------------------------- Get metadata
                   6658: 
1.599     albertel 6659: my %metaentry;
1.71      www      6660: sub metadata {
1.176     www      6661:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6662:     $uri=&declutter($uri);
1.288     albertel 6663:     # if it is a non metadata possible uri return quickly
1.529     albertel 6664:     if (($uri eq '') || 
                   6665: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6666: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6667:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6668: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6669: 	return undef;
1.288     albertel 6670:     }
1.73      www      6671:     my $filename=$uri;
                   6672:     $uri=~s/\.meta$//;
1.172     www      6673: #
                   6674: # Is the metadata already cached?
1.177     www      6675: # Look at timestamp of caching
1.172     www      6676: # Everything is cached by the main uri, libraries are never directly cached
                   6677: #
1.428     albertel 6678:     if (!defined($liburi)) {
1.599     albertel 6679: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6680: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6681:     }
                   6682:     {
1.172     www      6683: #
                   6684: # Is this a recursive call for a library?
                   6685: #
1.599     albertel 6686: #	if (! exists($metacache{$uri})) {
                   6687: #	    $metacache{$uri}={};
                   6688: #	}
1.171     www      6689:         if ($liburi) {
                   6690: 	    $liburi=&declutter($liburi);
                   6691:             $filename=$liburi;
1.401     bowersj2 6692:         } else {
1.599     albertel 6693: 	    &devalidate_cache_new('meta',$uri);
                   6694: 	    undef(%metaentry);
1.401     bowersj2 6695: 	}
1.140     www      6696:         my %metathesekeys=();
1.73      www      6697:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6698: 	my $metastring;
1.768     albertel 6699: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6700: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6701: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6702: 	    $metastring=&getfile($file);
1.489     albertel 6703: 	}
1.208     albertel 6704:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6705:         my $token;
1.140     www      6706:         undef %metathesekeys;
1.71      www      6707:         while ($token=$parser->get_token) {
1.339     albertel 6708: 	    if ($token->[0] eq 'S') {
                   6709: 		if (defined($token->[2]->{'package'})) {
1.172     www      6710: #
                   6711: # This is a package - get package info
                   6712: #
1.339     albertel 6713: 		    my $package=$token->[2]->{'package'};
                   6714: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6715: 		    if (defined($token->[2]->{'id'})) { 
                   6716: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6717: 		    }
1.599     albertel 6718: 		    if ($metaentry{':packages'}) {
                   6719: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6720: 		    } else {
1.599     albertel 6721: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6722: 		    }
1.736     albertel 6723: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6724: 			my $part=$keyroot;
                   6725: 			$part=~s/^\_//;
1.736     albertel 6726: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6727: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6728: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6729: 			    # ignore package.tab specified default values
                   6730:                             # here &package_tab_default() will fetch those
                   6731: 			    if ($subp eq 'default') { next; }
1.736     albertel 6732: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6733: 			    my $unikey;
                   6734: 			    if ($pack =~ /_0$/) {
                   6735: 				$unikey='parameter_0_'.$name;
                   6736: 				$part=0;
                   6737: 			    } else {
                   6738: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6739: 			    }
1.339     albertel 6740: 			    if ($subp eq 'display') {
                   6741: 				$value.=' [Part: '.$part.']';
                   6742: 			    }
1.599     albertel 6743: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6744: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6745: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6746: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6747: 			    }
1.599     albertel 6748: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6749: 				$metaentry{':'.$unikey}=
                   6750: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6751: 			    }
1.339     albertel 6752: 			}
                   6753: 		    }
                   6754: 		} else {
1.172     www      6755: #
                   6756: # This is not a package - some other kind of start tag
1.339     albertel 6757: #
                   6758: 		    my $entry=$token->[1];
                   6759: 		    my $unikey;
                   6760: 		    if ($entry eq 'import') {
                   6761: 			$unikey='';
                   6762: 		    } else {
                   6763: 			$unikey=$entry;
                   6764: 		    }
                   6765: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6766: 
                   6767: 		    if (defined($token->[2]->{'id'})) { 
                   6768: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6769: 		    }
1.175     www      6770: 
1.339     albertel 6771: 		    if ($entry eq 'import') {
1.175     www      6772: #
                   6773: # Importing a library here
1.339     albertel 6774: #
                   6775: 			if ($depthcount<20) {
                   6776: 			    my $location=$parser->get_text('/import');
                   6777: 			    my $dir=$filename;
                   6778: 			    $dir=~s|[^/]*$||;
                   6779: 			    $location=&filelocation($dir,$location);
1.736     albertel 6780: 			    my $metadata = 
                   6781: 				&metadata($uri,'keys', $location,$unikey,
                   6782: 					  $depthcount+1);
                   6783: 			    foreach my $meta (split(',',$metadata)) {
                   6784: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6785: 				$metathesekeys{$meta}=1;
1.339     albertel 6786: 			    }
                   6787: 			}
                   6788: 		    } else { 
                   6789: 			
                   6790: 			if (defined($token->[2]->{'name'})) { 
                   6791: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6792: 			}
                   6793: 			$metathesekeys{$unikey}=1;
1.736     albertel 6794: 			foreach my $param (@{$token->[3]}) {
                   6795: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6796: 				$token->[2]->{$param};
1.339     albertel 6797: 			}
                   6798: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6799: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6800: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6801: 		 # only ws inside the tag, and not in default, so use default
                   6802: 		 # as value
1.599     albertel 6803: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6804: 			} elsif ( $internaltext =~ /\S/ ) {
                   6805: 		  # something interesting inside the tag
                   6806: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6807: 			} else {
1.908     albertel 6808: 		  # no interesting values, don't set a default
1.339     albertel 6809: 			}
1.172     www      6810: # end of not-a-package not-a-library import
1.339     albertel 6811: 		    }
1.172     www      6812: # end of not-a-package start tag
1.339     albertel 6813: 		}
1.172     www      6814: # the next is the end of "start tag"
1.339     albertel 6815: 	    }
                   6816: 	}
1.483     albertel 6817: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6818: 	$extension = lc($extension);
                   6819: 	if ($extension eq 'htm') { $extension='html'; }
                   6820: 
1.737     albertel 6821: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6822: 	    #no specific packages #how's our extension
                   6823: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6824: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6825: 					 \%metathesekeys);
                   6826: 	}
1.883     albertel 6827: 
                   6828: 	if (!exists($metaentry{':packages'})
                   6829: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6830: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6831: 		#no specific packages well let's get default then
                   6832: 		if ($key!~/^default&/) { next; }
1.488     albertel 6833: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6834: 					     \%metathesekeys);
                   6835: 	    }
                   6836: 	}
1.338     www      6837: # are there custom rights to evaluate
1.599     albertel 6838: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6839: 
1.338     www      6840:     #
                   6841:     # Importing a rights file here
1.339     albertel 6842:     #
                   6843: 	    unless ($depthcount) {
1.599     albertel 6844: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6845: 		my $dir=$filename;
                   6846: 		$dir=~s|[^/]*$||;
                   6847: 		$location=&filelocation($dir,$location);
1.736     albertel 6848: 		my $rights_metadata =
                   6849: 		    &metadata($uri,'keys',$location,'_rights',
                   6850: 			      $depthcount+1);
                   6851: 		foreach my $rights (split(',',$rights_metadata)) {
                   6852: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6853: 		    $metathesekeys{$rights}=1;
1.339     albertel 6854: 		}
                   6855: 	    }
                   6856: 	}
1.737     albertel 6857: 	# uniqifiy package listing
                   6858: 	my %seen;
                   6859: 	my @uniq_packages =
                   6860: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6861: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6862: 
                   6863: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6864: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6865: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6866: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6867: # this is the end of "was not already recently cached
1.71      www      6868:     }
1.599     albertel 6869:     return $metaentry{':'.$what};
1.261     albertel 6870: }
                   6871: 
1.488     albertel 6872: sub metadata_create_package_def {
1.483     albertel 6873:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6874:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6875:     if ($subp eq 'default') { next; }
                   6876:     
1.599     albertel 6877:     if (defined($metaentry{':packages'})) {
                   6878: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6879:     } else {
1.599     albertel 6880: 	$metaentry{':packages'}=$package;
1.483     albertel 6881:     }
                   6882:     my $value=$packagetab{$key};
                   6883:     my $unikey;
                   6884:     $unikey='parameter_0_'.$name;
1.599     albertel 6885:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6886:     $$metathesekeys{$unikey}=1;
1.599     albertel 6887:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6888: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6889:     }
1.599     albertel 6890:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6891: 	$metaentry{':'.$unikey}=
                   6892: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6893:     }
                   6894: }
                   6895: 
1.261     albertel 6896: sub metadata_generate_part0 {
                   6897:     my ($metadata,$metacache,$uri) = @_;
                   6898:     my %allnames;
1.737     albertel 6899:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6900: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6901: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6902: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6903: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6904: 	    $allnames{$name}=$part;
                   6905: 	  }
                   6906: 	}
                   6907:     }
                   6908:     foreach my $name (keys(%allnames)) {
                   6909:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6910:       my $key=":parameter_0_$name";
1.261     albertel 6911:       $$metacache{"$key.part"}='0';
                   6912:       $$metacache{"$key.name"}=$name;
1.428     albertel 6913:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6914: 					   $allnames{$name}.'_'.$name.
                   6915: 					   '.type'};
1.428     albertel 6916:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6917: 			     '.display'};
1.644     www      6918:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6919:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6920:       $$metacache{"$key.display"}=$olddis;
                   6921:     }
1.71      www      6922: }
                   6923: 
1.764     albertel 6924: # ------------------------------------------------------ Devalidate title cache
                   6925: 
                   6926: sub devalidate_title_cache {
                   6927:     my ($url)=@_;
                   6928:     if (!$env{'request.course.id'}) { return; }
                   6929:     my $symb=&symbread($url);
                   6930:     if (!$symb) { return; }
                   6931:     my $key=$env{'request.course.id'}."\0".$symb;
                   6932:     &devalidate_cache_new('title',$key);
                   6933: }
                   6934: 
1.301     www      6935: # ------------------------------------------------- Get the title of a resource
                   6936: 
                   6937: sub gettitle {
                   6938:     my $urlsymb=shift;
                   6939:     my $symb=&symbread($urlsymb);
1.534     albertel 6940:     if ($symb) {
1.620     albertel 6941: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6942: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6943: 	if (defined($cached)) { 
                   6944: 	    return $result;
                   6945: 	}
1.534     albertel 6946: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6947: 	my $title='';
1.907     albertel 6948: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   6949: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   6950: 	} else {
                   6951: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6952: 		    &GDBM_READER(),0640)) {
                   6953: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6954: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   6955: 		untie(%bighash);
                   6956: 	    }
1.534     albertel 6957: 	}
                   6958: 	$title=~s/\&colon\;/\:/gs;
                   6959: 	if ($title) {
1.599     albertel 6960: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6961: 	}
                   6962: 	$urlsymb=$url;
                   6963:     }
                   6964:     my $title=&metadata($urlsymb,'title');
                   6965:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6966:     return $title;
1.301     www      6967: }
1.613     albertel 6968: 
1.614     albertel 6969: sub get_slot {
                   6970:     my ($which,$cnum,$cdom)=@_;
                   6971:     if (!$cnum || !$cdom) {
1.790     albertel 6972: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6973: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6974: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6975:     }
1.703     albertel 6976:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6977:     my %slotinfo;
                   6978:     if (exists($remembered{$key})) {
                   6979: 	$slotinfo{$which} = $remembered{$key};
                   6980:     } else {
                   6981: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6982: 	&Apache::lonhomework::showhash(%slotinfo);
                   6983: 	my ($tmp)=keys(%slotinfo);
                   6984: 	if ($tmp=~/^error:/) { return (); }
                   6985: 	$remembered{$key} = $slotinfo{$which};
                   6986:     }
1.616     albertel 6987:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6988: 	return %{$slotinfo{$which}};
                   6989:     }
                   6990:     return $slotinfo{$which};
1.614     albertel 6991: }
1.31      www      6992: # ------------------------------------------------- Update symbolic store links
                   6993: 
                   6994: sub symblist {
                   6995:     my ($mapname,%newhash)=@_;
1.438     www      6996:     $mapname=&deversion(&declutter($mapname));
1.31      www      6997:     my %hash;
1.620     albertel 6998:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6999:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7000:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7001: 	    foreach my $url (keys %newhash) {
                   7002: 		next if ($url eq 'last_known'
                   7003: 			 && $env{'form.no_update_last_known'});
                   7004: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7005: 						    $newhash{$url}->[1],
                   7006: 						    $newhash{$url}->[0]);
1.191     harris41 7007:             }
1.31      www      7008:             if (untie(%hash)) {
                   7009: 		return 'ok';
                   7010:             }
                   7011:         }
                   7012:     }
                   7013:     return 'error';
1.212     www      7014: }
                   7015: 
                   7016: # --------------------------------------------------------------- Verify a symb
                   7017: 
                   7018: sub symbverify {
1.510     www      7019:     my ($symb,$thisurl)=@_;
                   7020:     my $thisfn=$thisurl;
1.439     www      7021:     $thisfn=&declutter($thisfn);
1.215     www      7022: # direct jump to resource in page or to a sequence - will construct own symbs
                   7023:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7024: # check URL part
1.409     www      7025:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7026: 
1.431     www      7027:     unless ($url eq $thisfn) { return 0; }
1.213     www      7028: 
1.216     www      7029:     $symb=&symbclean($symb);
1.510     www      7030:     $thisurl=&deversion($thisurl);
1.439     www      7031:     $thisfn=&deversion($thisfn);
1.213     www      7032: 
                   7033:     my %bighash;
                   7034:     my $okay=0;
1.431     www      7035: 
1.620     albertel 7036:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7037:                             &GDBM_READER(),0640)) {
1.510     www      7038:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7039:         unless ($ids) { 
1.510     www      7040:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7041:         }
                   7042:         if ($ids) {
                   7043: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7044: 	    foreach my $id (split(/\,/,$ids)) {
                   7045: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7046:                if (
                   7047:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7048:    eq $symb) { 
1.620     albertel 7049: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7050: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7051: 		       $okay=1; 
                   7052: 		   }
                   7053: 	       }
1.216     www      7054: 	   }
                   7055:         }
1.213     www      7056: 	untie(%bighash);
                   7057:     }
                   7058:     return $okay;
1.31      www      7059: }
                   7060: 
1.210     www      7061: # --------------------------------------------------------------- Clean-up symb
                   7062: 
                   7063: sub symbclean {
                   7064:     my $symb=shift;
1.568     albertel 7065:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7066: # remove version from map
                   7067:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7068: 
1.210     www      7069: # remove version from URL
                   7070:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7071: 
1.507     www      7072: # remove wrapper
                   7073: 
1.510     www      7074:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7075:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7076:     return $symb;
1.409     www      7077: }
                   7078: 
                   7079: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7080: 
                   7081: sub encode_symb {
                   7082:     my ($map,$resid,$url)=@_;
                   7083:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7084: }
1.409     www      7085: 
                   7086: sub decode_symb {
1.568     albertel 7087:     my $symb=shift;
                   7088:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7089:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7090:     return (&fixversion($map),$resid,&fixversion($url));
                   7091: }
                   7092: 
                   7093: sub fixversion {
                   7094:     my $fn=shift;
1.609     banghart 7095:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7096:     my %bighash;
                   7097:     my $uri=&clutter($fn);
1.620     albertel 7098:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7099: # is this cached?
1.599     albertel 7100:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7101:     if (defined($cached)) { return $result; }
                   7102: # unfortunately not cached, or expired
1.620     albertel 7103:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7104: 	    &GDBM_READER(),0640)) {
                   7105:  	if ($bighash{'version_'.$uri}) {
                   7106:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7107:  	    unless (($version eq 'mostrecent') || 
                   7108: 		    ($version==&getversion($uri))) {
1.440     www      7109:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7110:  	    }
                   7111:  	}
                   7112:  	untie %bighash;
1.413     www      7113:     }
1.599     albertel 7114:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7115: }
                   7116: 
                   7117: sub deversion {
                   7118:     my $url=shift;
                   7119:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7120:     return $url;
1.210     www      7121: }
                   7122: 
1.31      www      7123: # ------------------------------------------------------ Return symb list entry
                   7124: 
                   7125: sub symbread {
1.249     www      7126:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7127:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7128:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7129: # no filename provided? try from environment
1.44      www      7130:     unless ($thisfn) {
1.620     albertel 7131:         if ($env{'request.symb'}) {
                   7132: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7133: 	}
1.620     albertel 7134: 	$thisfn=$env{'request.filename'};
1.44      www      7135:     }
1.569     albertel 7136:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7137: # is that filename actually a symb? Verify, clean, and return
                   7138:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7139: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7140: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7141: 	}
1.242     www      7142:     }
1.44      www      7143:     $thisfn=declutter($thisfn);
1.31      www      7144:     my %hash;
1.37      www      7145:     my %bighash;
                   7146:     my $syval='';
1.620     albertel 7147:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7148:         my $targetfn = $thisfn;
1.609     banghart 7149:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7150:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7151:         }
1.687     albertel 7152: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7153: 	    $targetfn=$1;
                   7154: 	}
1.620     albertel 7155:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7156:                       &GDBM_READER(),0640)) {
1.481     raeburn  7157: 	    $syval=$hash{$targetfn};
1.37      www      7158:             untie(%hash);
                   7159:         }
                   7160: # ---------------------------------------------------------- There was an entry
                   7161:         if ($syval) {
1.601     albertel 7162: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7163: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7164: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7165: 		    #return $env{$cache_str}='';
1.601     albertel 7166: 		#}    
                   7167: 		#$syval.=$1;
                   7168: 	    #}
1.37      www      7169:         } else {
                   7170: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7171:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7172:                             &GDBM_READER(),0640)) {
1.37      www      7173: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7174:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7175:               unless ($ids) { 
                   7176:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7177:               }
                   7178:               unless ($ids) {
                   7179: # alias?
                   7180: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7181:               }
1.37      www      7182:               if ($ids) {
                   7183: # ------------------------------------------------------------------- Has ID(s)
                   7184:                  my @possibilities=split(/\,/,$ids);
1.39      www      7185:                  if ($#possibilities==0) {
                   7186: # ----------------------------------------------- There is only one possibility
1.37      www      7187: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7188: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7189: 						    $resid,$thisfn);
1.249     www      7190:                  } elsif (!$donotrecurse) {
1.39      www      7191: # ------------------------------------------ There is more than one possibility
                   7192:                      my $realpossible=0;
1.800     albertel 7193:                      foreach my $id (@possibilities) {
                   7194: 			 my $file=$bighash{'src_'.$id};
1.39      www      7195:                          if (&allowed('bre',$file)) {
1.800     albertel 7196:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7197:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7198: 				$realpossible++;
1.626     albertel 7199:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7200: 						    $resid,$thisfn);
1.39      www      7201:                             }
                   7202: 			 }
1.191     harris41 7203:                      }
1.39      www      7204: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7205:                  } else {
                   7206:                      $syval='';
1.37      www      7207:                  }
                   7208: 	      }
                   7209:               untie(%bighash)
1.481     raeburn  7210:            }
1.31      www      7211:         }
1.62      www      7212:         if ($syval) {
1.620     albertel 7213: 	    return $env{$cache_str}=$syval;
1.62      www      7214:         }
1.31      www      7215:     }
1.44      www      7216:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7217:     return $env{$cache_str}='';
1.31      www      7218: }
                   7219: 
                   7220: # ---------------------------------------------------------- Return random seed
                   7221: 
1.32      www      7222: sub numval {
                   7223:     my $txt=shift;
                   7224:     $txt=~tr/A-J/0-9/;
                   7225:     $txt=~tr/a-j/0-9/;
                   7226:     $txt=~tr/K-T/0-9/;
                   7227:     $txt=~tr/k-t/0-9/;
                   7228:     $txt=~tr/U-Z/0-5/;
                   7229:     $txt=~tr/u-z/0-5/;
                   7230:     $txt=~s/\D//g;
1.564     albertel 7231:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7232:     return int($txt);
1.368     albertel 7233: }
                   7234: 
1.484     albertel 7235: sub numval2 {
                   7236:     my $txt=shift;
                   7237:     $txt=~tr/A-J/0-9/;
                   7238:     $txt=~tr/a-j/0-9/;
                   7239:     $txt=~tr/K-T/0-9/;
                   7240:     $txt=~tr/k-t/0-9/;
                   7241:     $txt=~tr/U-Z/0-5/;
                   7242:     $txt=~tr/u-z/0-5/;
                   7243:     $txt=~s/\D//g;
                   7244:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7245:     my $total;
                   7246:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7247:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7248:     return int($total);
                   7249: }
                   7250: 
1.575     albertel 7251: sub numval3 {
                   7252:     use integer;
                   7253:     my $txt=shift;
                   7254:     $txt=~tr/A-J/0-9/;
                   7255:     $txt=~tr/a-j/0-9/;
                   7256:     $txt=~tr/K-T/0-9/;
                   7257:     $txt=~tr/k-t/0-9/;
                   7258:     $txt=~tr/U-Z/0-5/;
                   7259:     $txt=~tr/u-z/0-5/;
                   7260:     $txt=~s/\D//g;
                   7261:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7262:     my $total;
                   7263:     foreach my $val (@txts) { $total+=$val; }
                   7264:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7265:     return $total;
                   7266: }
                   7267: 
1.675     albertel 7268: sub digest {
                   7269:     my ($data)=@_;
                   7270:     my $digest=&Digest::MD5::md5($data);
                   7271:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7272:     my ($e,$f);
                   7273:     {
                   7274:         use integer;
                   7275:         $e=($a+$b);
                   7276:         $f=($c+$d);
                   7277:         if ($_64bit) {
                   7278:             $e=(($e<<32)>>32);
                   7279:             $f=(($f<<32)>>32);
                   7280:         }
                   7281:     }
                   7282:     if (wantarray) {
                   7283: 	return ($e,$f);
                   7284:     } else {
                   7285: 	my $g;
                   7286: 	{
                   7287: 	    use integer;
                   7288: 	    $g=($e+$f);
                   7289: 	    if ($_64bit) {
                   7290: 		$g=(($g<<32)>>32);
                   7291: 	    }
                   7292: 	}
                   7293: 	return $g;
                   7294:     }
                   7295: }
                   7296: 
1.368     albertel 7297: sub latest_rnd_algorithm_id {
1.675     albertel 7298:     return '64bit5';
1.366     albertel 7299: }
1.32      www      7300: 
1.503     albertel 7301: sub get_rand_alg {
                   7302:     my ($courseid)=@_;
1.790     albertel 7303:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7304:     if ($courseid) {
1.620     albertel 7305: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7306:     }
                   7307:     return &latest_rnd_algorithm_id();
                   7308: }
                   7309: 
1.562     albertel 7310: sub validCODE {
                   7311:     my ($CODE)=@_;
                   7312:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7313:     return 0;
                   7314: }
                   7315: 
1.491     albertel 7316: sub getCODE {
1.620     albertel 7317:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7318:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7319: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7320: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7321: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7322:     }
                   7323:     return undef;
                   7324: }
                   7325: 
1.31      www      7326: sub rndseed {
1.155     albertel 7327:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7328:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7329:     if (!defined($symb)) {
1.366     albertel 7330: 	unless ($symb=$wsymb) { return time; }
                   7331:     }
                   7332:     if (!$courseid) { $courseid=$wcourseid; }
                   7333:     if (!$domain) { $domain=$wdomain; }
                   7334:     if (!$username) { $username=$wusername }
1.503     albertel 7335:     my $which=&get_rand_alg();
1.803     albertel 7336: 
1.491     albertel 7337:     if (defined(&getCODE())) {
1.675     albertel 7338: 	if ($which eq '64bit5') {
                   7339: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7340: 	} elsif ($which eq '64bit4') {
1.575     albertel 7341: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7342: 	} else {
                   7343: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7344: 	}
1.675     albertel 7345:     } elsif ($which eq '64bit5') {
                   7346: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7347:     } elsif ($which eq '64bit4') {
                   7348: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7349:     } elsif ($which eq '64bit3') {
                   7350: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7351:     } elsif ($which eq '64bit2') {
                   7352: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7353:     } elsif ($which eq '64bit') {
                   7354: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7355:     }
                   7356:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7357: }
                   7358: 
                   7359: sub rndseed_32bit {
                   7360:     my ($symb,$courseid,$domain,$username)=@_;
                   7361:     {
                   7362: 	use integer;
                   7363: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7364: 	my $symbseed=numval($symb) << 22;
                   7365: 	my $namechck=unpack("%32C*",$username) << 17;
                   7366: 	my $nameseed=numval($username) << 12;
                   7367: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7368: 	my $courseseed=unpack("%32C*",$courseid);
                   7369: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7370: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7371: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7372: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7373: 	return $num;
                   7374:     }
                   7375: }
                   7376: 
                   7377: sub rndseed_64bit {
                   7378:     my ($symb,$courseid,$domain,$username)=@_;
                   7379:     {
                   7380: 	use integer;
                   7381: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7382: 	my $symbseed=numval($symb) << 10;
                   7383: 	my $namechck=unpack("%32S*",$username);
                   7384: 	
                   7385: 	my $nameseed=numval($username) << 21;
                   7386: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7387: 	my $courseseed=unpack("%32S*",$courseid);
                   7388: 	
                   7389: 	my $num1=$symbchck+$symbseed+$namechck;
                   7390: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7391: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7392: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7393: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7394: 	return "$num1,$num2";
1.155     albertel 7395:     }
1.366     albertel 7396: }
                   7397: 
1.443     albertel 7398: sub rndseed_64bit2 {
                   7399:     my ($symb,$courseid,$domain,$username)=@_;
                   7400:     {
                   7401: 	use integer;
                   7402: 	# strings need to be an even # of cahracters long, it it is odd the
                   7403:         # last characters gets thrown away
                   7404: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7405: 	my $symbseed=numval($symb) << 10;
                   7406: 	my $namechck=unpack("%32S*",$username.' ');
                   7407: 	
                   7408: 	my $nameseed=numval($username) << 21;
1.501     albertel 7409: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7410: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7411: 	
                   7412: 	my $num1=$symbchck+$symbseed+$namechck;
                   7413: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7414: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7415: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7416: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7417: 	return "$num1,$num2";
                   7418:     }
                   7419: }
                   7420: 
                   7421: sub rndseed_64bit3 {
                   7422:     my ($symb,$courseid,$domain,$username)=@_;
                   7423:     {
                   7424: 	use integer;
                   7425: 	# strings need to be an even # of cahracters long, it it is odd the
                   7426:         # last characters gets thrown away
                   7427: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7428: 	my $symbseed=numval2($symb) << 10;
                   7429: 	my $namechck=unpack("%32S*",$username.' ');
                   7430: 	
                   7431: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7432: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7433: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7434: 	
                   7435: 	my $num1=$symbchck+$symbseed+$namechck;
                   7436: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7437: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7438: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7439: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7440: 	
1.503     albertel 7441: 	return "$num1:$num2";
1.443     albertel 7442:     }
                   7443: }
                   7444: 
1.575     albertel 7445: sub rndseed_64bit4 {
                   7446:     my ($symb,$courseid,$domain,$username)=@_;
                   7447:     {
                   7448: 	use integer;
                   7449: 	# strings need to be an even # of cahracters long, it it is odd the
                   7450:         # last characters gets thrown away
                   7451: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7452: 	my $symbseed=numval3($symb) << 10;
                   7453: 	my $namechck=unpack("%32S*",$username.' ');
                   7454: 	
                   7455: 	my $nameseed=numval3($username) << 21;
                   7456: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7457: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7458: 	
                   7459: 	my $num1=$symbchck+$symbseed+$namechck;
                   7460: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7461: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7462: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7463: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7464: 	
                   7465: 	return "$num1:$num2";
                   7466:     }
                   7467: }
                   7468: 
1.675     albertel 7469: sub rndseed_64bit5 {
                   7470:     my ($symb,$courseid,$domain,$username)=@_;
                   7471:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7472:     return "$num1:$num2";
                   7473: }
                   7474: 
1.366     albertel 7475: sub rndseed_CODE_64bit {
                   7476:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7477:     {
1.366     albertel 7478: 	use integer;
1.443     albertel 7479: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7480: 	my $symbseed=numval2($symb);
1.491     albertel 7481: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7482: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7483: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7484: 	my $num1=$symbseed+$CODEchck;
                   7485: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7486: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7487: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7488: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7489: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7490: 	return "$num1:$num2";
1.366     albertel 7491:     }
                   7492: }
                   7493: 
1.575     albertel 7494: sub rndseed_CODE_64bit4 {
                   7495:     my ($symb,$courseid,$domain,$username)=@_;
                   7496:     {
                   7497: 	use integer;
                   7498: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7499: 	my $symbseed=numval3($symb);
                   7500: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7501: 	my $CODEseed=numval3(&getCODE());
                   7502: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7503: 	my $num1=$symbseed+$CODEchck;
                   7504: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7505: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7506: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7507: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7508: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7509: 	return "$num1:$num2";
                   7510:     }
                   7511: }
                   7512: 
1.675     albertel 7513: sub rndseed_CODE_64bit5 {
                   7514:     my ($symb,$courseid,$domain,$username)=@_;
                   7515:     my $code = &getCODE();
                   7516:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7517:     return "$num1:$num2";
                   7518: }
                   7519: 
1.366     albertel 7520: sub setup_random_from_rndseed {
                   7521:     my ($rndseed)=@_;
1.503     albertel 7522:     if ($rndseed =~/([,:])/) {
                   7523: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7524: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7525:     } else {
                   7526: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7527:     }
1.36      albertel 7528: }
                   7529: 
1.474     albertel 7530: sub latest_receipt_algorithm_id {
1.835     albertel 7531:     return 'receipt3';
1.474     albertel 7532: }
                   7533: 
1.480     www      7534: sub recunique {
                   7535:     my $fucourseid=shift;
                   7536:     my $unique;
1.835     albertel 7537:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7538: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7539: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7540:     } else {
                   7541: 	$unique=$perlvar{'lonReceipt'};
                   7542:     }
                   7543:     return unpack("%32C*",$unique);
                   7544: }
                   7545: 
                   7546: sub recprefix {
                   7547:     my $fucourseid=shift;
                   7548:     my $prefix;
1.835     albertel 7549:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7550: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7551: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7552:     } else {
                   7553: 	$prefix=$perlvar{'lonHostID'};
                   7554:     }
                   7555:     return unpack("%32C*",$prefix);
                   7556: }
                   7557: 
1.76      www      7558: sub ireceipt {
1.474     albertel 7559:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7560: 
                   7561:     my $return =&recprefix($fucourseid).'-';
                   7562: 
                   7563:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7564: 	$env{'request.state'} eq 'construct') {
                   7565: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7566: 	return $return;
                   7567:     }
                   7568: 
1.76      www      7569:     my $cuname=unpack("%32C*",$funame);
                   7570:     my $cudom=unpack("%32C*",$fudom);
                   7571:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7572:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7573:     my $cunique=&recunique($fucourseid);
1.474     albertel 7574:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7575:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7576: 
1.790     albertel 7577: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7578: 			       
                   7579: 	$return.= ($cunique%$cuname+
                   7580: 		   $cunique%$cudom+
                   7581: 		   $cusymb%$cuname+
                   7582: 		   $cusymb%$cudom+
                   7583: 		   $cucourseid%$cuname+
                   7584: 		   $cucourseid%$cudom+
                   7585: 		   $cpart%$cuname+
                   7586: 		   $cpart%$cudom);
                   7587:     } else {
                   7588: 	$return.= ($cunique%$cuname+
                   7589: 		   $cunique%$cudom+
                   7590: 		   $cusymb%$cuname+
                   7591: 		   $cusymb%$cudom+
                   7592: 		   $cucourseid%$cuname+
                   7593: 		   $cucourseid%$cudom);
                   7594:     }
                   7595:     return $return;
1.76      www      7596: }
                   7597: 
                   7598: sub receipt {
1.474     albertel 7599:     my ($part)=@_;
1.790     albertel 7600:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7601:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7602: }
1.260     ng       7603: 
1.790     albertel 7604: sub whichuser {
                   7605:     my ($passedsymb)=@_;
                   7606:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7607:     if (defined($env{'form.grade_symb'})) {
                   7608: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7609: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7610: 	if (!$allowed &&
                   7611: 	    exists($env{'request.course.sec'}) &&
                   7612: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7613: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7614: 			      '/'.$env{'request.course.sec'});
                   7615: 	}
                   7616: 	if ($allowed) {
                   7617: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7618: 	    $courseid=$tmp_courseid;
                   7619: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7620: 	    ($name)=&get_env_multiple('form.grade_username');
                   7621: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7622: 	}
                   7623:     }
                   7624:     if (!$passedsymb) {
                   7625: 	$symb=&symbread();
                   7626:     } else {
                   7627: 	$symb=$passedsymb;
                   7628:     }
                   7629:     $courseid=$env{'request.course.id'};
                   7630:     $domain=$env{'user.domain'};
                   7631:     $name=$env{'user.name'};
                   7632:     if ($name eq 'public' && $domain eq 'public') {
                   7633: 	if (!defined($env{'form.username'})) {
                   7634: 	    $env{'form.username'}.=time.rand(10000000);
                   7635: 	}
                   7636: 	$name.=$env{'form.username'};
                   7637:     }
                   7638:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7639: 
                   7640: }
                   7641: 
1.36      albertel 7642: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7643: # returns either the contents of the file or 
                   7644: # -1 if the file doesn't exist
1.481     raeburn  7645: #
                   7646: # if the target is a file that was uploaded via DOCS, 
                   7647: # a check will be made to see if a current copy exists on the local server,
                   7648: # if it does this will be served, otherwise a copy will be retrieved from
                   7649: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7650: # the local server.   
1.472     albertel 7651: 
1.36      albertel 7652: sub getfile {
1.538     albertel 7653:     my ($file) = @_;
1.609     banghart 7654:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7655:     &repcopy($file);
                   7656:     return &readfile($file);
                   7657: }
                   7658: 
                   7659: sub repcopy_userfile {
                   7660:     my ($file)=@_;
1.609     banghart 7661:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7662:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7663:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7664: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7665:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7666:     if (-e "$file") {
1.828     www      7667: # we already have a local copy, check it out
1.538     albertel 7668: 	my @fileinfo = stat($file);
1.828     www      7669: 	my $rtncode;
                   7670: 	my $info;
1.538     albertel 7671: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7672: 	if ($lwpresp ne 'ok') {
1.828     www      7673: # there is no such file anymore, even though we had a local copy
1.482     albertel 7674: 	    if ($rtncode eq '404') {
1.538     albertel 7675: 		unlink($file);
1.482     albertel 7676: 	    }
                   7677: 	    return -1;
                   7678: 	}
                   7679: 	if ($info < $fileinfo[9]) {
1.828     www      7680: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7681: 	    return 'ok';
1.828     www      7682: 	} else {
                   7683: # the file is outdated, get rid of it
                   7684: 	    unlink($file);
1.482     albertel 7685: 	}
1.828     www      7686:     }
                   7687: # one way or the other, at this point, we don't have the file
                   7688: # construct the correct path for the file
                   7689:     my @parts = ($cdom,$cnum); 
                   7690:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7691: 	push @parts, split(/\//,$1);
                   7692:     }
                   7693:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7694:     foreach my $part (@parts) {
                   7695: 	$path .= '/'.$part;
                   7696: 	if (!-e $path) {
                   7697: 	    mkdir($path,0770);
1.482     albertel 7698: 	}
                   7699:     }
1.828     www      7700: # now the path exists for sure
                   7701: # get a user agent
                   7702:     my $ua=new LWP::UserAgent;
                   7703:     my $transferfile=$file.'.in.transfer';
                   7704: # FIXME: this should flock
                   7705:     if (-e $transferfile) { return 'ok'; }
                   7706:     my $request;
                   7707:     $uri=~s/^\///;
1.838     albertel 7708:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7709:     my $response=$ua->request($request,$transferfile);
                   7710: # did it work?
                   7711:     if ($response->is_error()) {
                   7712: 	unlink($transferfile);
                   7713: 	&logthis("Userfile repcopy failed for $uri");
                   7714: 	return -1;
                   7715:     }
                   7716: # worked, rename the transfer file
                   7717:     rename($transferfile,$file);
1.607     raeburn  7718:     return 'ok';
1.481     raeburn  7719: }
                   7720: 
1.517     albertel 7721: sub tokenwrapper {
                   7722:     my $uri=shift;
1.552     albertel 7723:     $uri=~s|^http\://([^/]+)||;
                   7724:     $uri=~s|^/||;
1.620     albertel 7725:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7726:     my $token=$1;
1.552     albertel 7727:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7728:     if ($udom && $uname && $file) {
                   7729: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7730:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7731:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7732:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7733:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7734:     } else {
                   7735:         return '/adm/notfound.html';
                   7736:     }
                   7737: }
                   7738: 
1.828     www      7739: # call with reqtype HEAD: get last modification time
                   7740: # call with reqtype GET: get the file contents
                   7741: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7742: #
1.481     raeburn  7743: sub getuploaded {
                   7744:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7745:     $uri=~s/^\///;
1.838     albertel 7746:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7747:     my $ua=new LWP::UserAgent;
                   7748:     my $request=new HTTP::Request($reqtype,$uri);
                   7749:     my $response=$ua->request($request);
                   7750:     $$rtncode = $response->code;
1.482     albertel 7751:     if (! $response->is_success()) {
                   7752: 	return 'failed';
                   7753:     }      
                   7754:     if ($reqtype eq 'HEAD') {
1.486     www      7755: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7756:     } elsif ($reqtype eq 'GET') {
                   7757: 	$$info = $response->content;
1.472     albertel 7758:     }
1.482     albertel 7759:     return 'ok';
1.36      albertel 7760: }
                   7761: 
1.481     raeburn  7762: sub readfile {
                   7763:     my $file = shift;
                   7764:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7765:     my $fh;
                   7766:     open($fh,"<$file");
                   7767:     my $a='';
1.800     albertel 7768:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7769:     return $a;
                   7770: }
                   7771: 
1.36      albertel 7772: sub filelocation {
1.590     banghart 7773:     my ($dir,$file) = @_;
                   7774:     my $location;
                   7775:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7776: 
                   7777:     if ($file =~ m-^/adm/-) {
                   7778: 	$file=~s-^/adm/wrapper/-/-;
                   7779: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7780:     }
1.882     albertel 7781: 
1.590     banghart 7782:     if ($file=~m:^/~:) { # is a contruction space reference
                   7783:         $location = $file;
                   7784:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7785:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7786: 	# is a correct contruction space reference
                   7787:         $location = $file;
1.609     banghart 7788:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7789:         my ($udom,$uname,$filename)=
1.811     albertel 7790:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7791:         my $home=&homeserver($uname,$udom);
                   7792:         my $is_me=0;
                   7793:         my @ids=&current_machine_ids();
                   7794:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7795:         if ($is_me) {
1.740     www      7796:   	    $location=&propath($udom,$uname).
1.590     banghart 7797:   	      '/userfiles/'.$filename;
                   7798:         } else {
                   7799:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7800:   	      $udom.'/'.$uname.'/'.$filename;
                   7801:         }
1.882     albertel 7802:     } elsif ($file =~ m-^/adm/-) {
                   7803: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7804:     } else {
                   7805:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7806:         $file=~s:^/res/:/:;
                   7807:         if ( !( $file =~ m:^/:) ) {
                   7808:             $location = $dir. '/'.$file;
                   7809:         } else {
                   7810:             $location = '/home/httpd/html/res'.$file;
                   7811:         }
1.59      albertel 7812:     }
1.590     banghart 7813:     $location=~s://+:/:g; # remove duplicate /
                   7814:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7815:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7816:     return $location;
1.46      www      7817: }
1.36      albertel 7818: 
1.46      www      7819: sub hreflocation {
                   7820:     my ($dir,$file)=@_;
1.460     albertel 7821:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7822: 	$file=filelocation($dir,$file);
1.700     albertel 7823:     } elsif ($file=~m-^/adm/-) {
                   7824: 	$file=~s-^/adm/wrapper/-/-;
                   7825: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7826:     }
                   7827:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7828: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7829:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7830: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7831:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7832: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7833: 	    -/uploaded/$1/$2/-x;
1.46      www      7834:     }
1.462     albertel 7835:     return $file;
1.465     albertel 7836: }
                   7837: 
                   7838: sub current_machine_domains {
1.853     albertel 7839:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7840: }
                   7841: 
                   7842: sub machine_domains {
                   7843:     my ($hostname) = @_;
1.465     albertel 7844:     my @domains;
1.838     albertel 7845:     my %hostname = &all_hostnames();
1.465     albertel 7846:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7847: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7848: 	if ($hostname eq $name) {
1.844     albertel 7849: 	    push(@domains,&host_domain($id));
1.465     albertel 7850: 	}
                   7851:     }
                   7852:     return @domains;
                   7853: }
                   7854: 
                   7855: sub current_machine_ids {
1.853     albertel 7856:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7857: }
                   7858: 
                   7859: sub machine_ids {
                   7860:     my ($hostname) = @_;
                   7861:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7862:     my @ids;
1.888     albertel 7863:     my %name_to_host = &all_names();
1.889     albertel 7864:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7865: 	return @{ $name_to_host{$hostname} };
                   7866:     }
                   7867:     return;
1.31      www      7868: }
                   7869: 
1.824     raeburn  7870: sub additional_machine_domains {
                   7871:     my @domains;
                   7872:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7873:     while( my $line = <$fh>) {
                   7874:         $line =~ s/\s//g;
                   7875:         push(@domains,$line);
                   7876:     }
                   7877:     return @domains;
                   7878: }
                   7879: 
                   7880: sub default_login_domain {
                   7881:     my $domain = $perlvar{'lonDefDomain'};
                   7882:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7883:     foreach my $posdom (&current_machine_domains(),
                   7884:                         &additional_machine_domains()) {
                   7885:         if (lc($posdom) eq lc($testdomain)) {
                   7886:             $domain=$posdom;
                   7887:             last;
                   7888:         }
                   7889:     }
                   7890:     return $domain;
                   7891: }
                   7892: 
1.31      www      7893: # ------------------------------------------------------------- Declutters URLs
                   7894: 
                   7895: sub declutter {
                   7896:     my $thisfn=shift;
1.569     albertel 7897:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7898:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7899:     $thisfn=~s/^\///;
1.697     albertel 7900:     $thisfn=~s|^adm/wrapper/||;
                   7901:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7902:     $thisfn=~s/^res\///;
1.235     www      7903:     $thisfn=~s/\?.+$//;
1.268     www      7904:     return $thisfn;
                   7905: }
                   7906: 
                   7907: # ------------------------------------------------------------- Clutter up URLs
                   7908: 
                   7909: sub clutter {
                   7910:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7911:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7912: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7913:        $thisfn='/res'.$thisfn; 
                   7914:     }
1.694     albertel 7915:     if ($thisfn !~m|/adm|) {
1.695     albertel 7916: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7917: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7918: 	} else {
                   7919: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7920: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7921: 	    if ($embstyle eq 'ssi'
                   7922: 		|| ($embstyle eq 'hdn')
                   7923: 		|| ($embstyle eq 'rat')
                   7924: 		|| ($embstyle eq 'prv')
                   7925: 		|| ($embstyle eq 'ign')) {
                   7926: 		#do nothing with these
                   7927: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7928: 		|| ($embstyle eq 'emb')
                   7929: 		|| ($embstyle eq 'wrp')) {
                   7930: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7931: 	    } elsif ($embstyle eq 'unk'
                   7932: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7933: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7934: 	    } else {
1.718     www      7935: #		&logthis("Got a blank emb style");
1.695     albertel 7936: 	    }
1.694     albertel 7937: 	}
                   7938:     }
1.31      www      7939:     return $thisfn;
1.12      www      7940: }
                   7941: 
1.787     albertel 7942: sub clutter_with_no_wrapper {
                   7943:     my $uri = &clutter(shift);
                   7944:     if ($uri =~ m-^/adm/-) {
                   7945: 	$uri =~ s-^/adm/wrapper/-/-;
                   7946: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7947:     }
                   7948:     return $uri;
                   7949: }
                   7950: 
1.557     albertel 7951: sub freeze_escape {
                   7952:     my ($value)=@_;
                   7953:     if (ref($value)) {
                   7954: 	$value=&nfreeze($value);
                   7955: 	return '__FROZEN__'.&escape($value);
                   7956:     }
                   7957:     return &escape($value);
                   7958: }
                   7959: 
1.11      www      7960: 
1.557     albertel 7961: sub thaw_unescape {
                   7962:     my ($value)=@_;
                   7963:     if ($value =~ /^__FROZEN__/) {
                   7964: 	substr($value,0,10,undef);
                   7965: 	$value=&unescape($value);
                   7966: 	return &thaw($value);
                   7967:     }
                   7968:     return &unescape($value);
                   7969: }
                   7970: 
1.436     albertel 7971: sub correct_line_ends {
                   7972:     my ($result)=@_;
                   7973:     $$result =~s/\r\n/\n/mg;
                   7974:     $$result =~s/\r/\n/mg;
1.415     albertel 7975: }
1.1       albertel 7976: # ================================================================ Main Program
                   7977: 
1.184     www      7978: sub goodbye {
1.204     albertel 7979:    &logthis("Starting Shut down");
1.443     albertel 7980: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7981:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7982: #converted
1.599     albertel 7983: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7984:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7985: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7986: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7987: #1.1 only
1.870     albertel 7988: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7989: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7990: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7991: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7992:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7993:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7994:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7995:    &flushcourselogs();
                   7996:    &logthis("Shutting down");
                   7997: }
                   7998: 
1.852     albertel 7999: sub get_dns {
1.869     albertel 8000:     my ($url,$func,$ignore_cache) = @_;
                   8001:     if (!$ignore_cache) {
                   8002: 	my ($content,$cached)=
                   8003: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8004: 	if ($cached) {
                   8005: 	    &$func($content);
                   8006: 	    return;
                   8007: 	}
                   8008:     }
                   8009: 
                   8010:     my %alldns;
1.852     albertel 8011:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8012:     foreach my $dns (<$config>) {
                   8013: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8014: 	$alldns{$1} = 1;
                   8015:     }
                   8016:     while (%alldns) {
                   8017: 	my ($dns) = keys(%alldns);
                   8018: 	delete($alldns{$dns});
1.852     albertel 8019: 	my $ua=new LWP::UserAgent;
                   8020: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8021: 	my $response=$ua->request($request);
                   8022: 	next if ($response->is_error());
                   8023: 	my @content = split("\n",$response->content);
1.869     albertel 8024: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8025: 	&$func(\@content);
1.869     albertel 8026: 	return;
1.852     albertel 8027:     }
                   8028:     close($config);
1.871     albertel 8029:     my $which = (split('/',$url))[3];
                   8030:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8031:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8032:     my @content = <$config>;
                   8033:     &$func(\@content);
                   8034:     return;
1.852     albertel 8035: }
1.327     albertel 8036: # ------------------------------------------------------------ Read domain file
                   8037: {
1.852     albertel 8038:     my $loaded;
1.846     albertel 8039:     my %domain;
                   8040: 
1.852     albertel 8041:     sub parse_domain_tab {
                   8042: 	my ($lines) = @_;
                   8043: 	foreach my $line (@$lines) {
                   8044: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8045: 
1.846     albertel 8046: 	    chomp($line);
1.852     albertel 8047: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8048: 	    my %this_domain;
                   8049: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8050: 			       'lang_def', 'city', 'longi', 'lati',
                   8051: 			       'primary') {
                   8052: 		$this_domain{$field} = shift(@elements);
                   8053: 	    }
                   8054: 	    $domain{$name} = \%this_domain;
1.852     albertel 8055: 	}
                   8056:     }
1.864     albertel 8057: 
                   8058:     sub reset_domain_info {
                   8059: 	undef($loaded);
                   8060: 	undef(%domain);
                   8061:     }
                   8062: 
1.852     albertel 8063:     sub load_domain_tab {
1.869     albertel 8064: 	my ($ignore_cache) = @_;
                   8065: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8066: 	my $fh;
                   8067: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8068: 	    my @lines = <$fh>;
                   8069: 	    &parse_domain_tab(\@lines);
1.448     albertel 8070: 	}
1.852     albertel 8071: 	close($fh);
                   8072: 	$loaded = 1;
1.327     albertel 8073:     }
1.846     albertel 8074: 
                   8075:     sub domain {
1.852     albertel 8076: 	&load_domain_tab() if (!$loaded);
                   8077: 
1.846     albertel 8078: 	my ($name,$what) = @_;
                   8079: 	return if ( !exists($domain{$name}) );
                   8080: 
                   8081: 	if (!$what) {
                   8082: 	    return $domain{$name}{'description'};
                   8083: 	}
                   8084: 	return $domain{$name}{$what};
                   8085:     }
1.327     albertel 8086: }
                   8087: 
                   8088: 
1.1       albertel 8089: # ------------------------------------------------------------- Read hosts file
                   8090: {
1.838     albertel 8091:     my %hostname;
1.844     albertel 8092:     my %hostdom;
1.845     albertel 8093:     my %libserv;
1.852     albertel 8094:     my $loaded;
1.888     albertel 8095:     my %name_to_host;
1.852     albertel 8096: 
                   8097:     sub parse_hosts_tab {
                   8098: 	my ($file) = @_;
                   8099: 	foreach my $configline (@$file) {
                   8100: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8101: 	    next if ($configline =~ /^\^/);
                   8102: 	    chomp($configline);
                   8103: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8104: 	    $name=~s/\s//g;
                   8105: 	    if ($id && $domain && $role && $name) {
                   8106: 		$hostname{$id}=$name;
1.888     albertel 8107: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8108: 		$hostdom{$id}=$domain;
                   8109: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8110: 	    }
                   8111: 	}
                   8112:     }
1.864     albertel 8113:     
                   8114:     sub reset_hosts_info {
1.897     albertel 8115: 	&purge_remembered();
1.864     albertel 8116: 	&reset_domain_info();
                   8117: 	&reset_hosts_ip_info();
1.892     albertel 8118: 	undef(%name_to_host);
1.864     albertel 8119: 	undef(%hostname);
                   8120: 	undef(%hostdom);
                   8121: 	undef(%libserv);
                   8122: 	undef($loaded);
                   8123:     }
1.1       albertel 8124: 
1.852     albertel 8125:     sub load_hosts_tab {
1.869     albertel 8126: 	my ($ignore_cache) = @_;
                   8127: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8128: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8129: 	my @config = <$config>;
                   8130: 	&parse_hosts_tab(\@config);
                   8131: 	close($config);
                   8132: 	$loaded=1;
1.1       albertel 8133:     }
1.852     albertel 8134: 
1.838     albertel 8135:     sub hostname {
1.852     albertel 8136: 	&load_hosts_tab() if (!$loaded);
                   8137: 
1.838     albertel 8138: 	my ($lonid) = @_;
                   8139: 	return $hostname{$lonid};
                   8140:     }
1.845     albertel 8141: 
1.838     albertel 8142:     sub all_hostnames {
1.852     albertel 8143: 	&load_hosts_tab() if (!$loaded);
                   8144: 
1.838     albertel 8145: 	return %hostname;
                   8146:     }
1.845     albertel 8147: 
1.888     albertel 8148:     sub all_names {
                   8149: 	&load_hosts_tab() if (!$loaded);
                   8150: 
                   8151: 	return %name_to_host;
                   8152:     }
                   8153: 
1.845     albertel 8154:     sub is_library {
1.852     albertel 8155: 	&load_hosts_tab() if (!$loaded);
                   8156: 
1.845     albertel 8157: 	return exists($libserv{$_[0]});
                   8158:     }
                   8159: 
                   8160:     sub all_library {
1.852     albertel 8161: 	&load_hosts_tab() if (!$loaded);
                   8162: 
1.845     albertel 8163: 	return %libserv;
                   8164:     }
                   8165: 
1.841     albertel 8166:     sub get_servers {
1.852     albertel 8167: 	&load_hosts_tab() if (!$loaded);
                   8168: 
1.841     albertel 8169: 	my ($domain,$type) = @_;
                   8170: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8171: 	                                          : %hostname;
                   8172: 	my %result;
1.842     albertel 8173: 	if (ref($domain) eq 'ARRAY') {
                   8174: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8175: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8176: 		    $result{$host} = $hostname;
                   8177: 		}
                   8178: 	    }
                   8179: 	} else {
                   8180: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8181: 		if ($hostdom{$host} eq $domain) {
                   8182: 		    $result{$host} = $hostname;
                   8183: 		}
1.841     albertel 8184: 	    }
                   8185: 	}
                   8186: 	return %result;
                   8187:     }
1.845     albertel 8188: 
1.844     albertel 8189:     sub host_domain {
1.852     albertel 8190: 	&load_hosts_tab() if (!$loaded);
                   8191: 
1.844     albertel 8192: 	my ($lonid) = @_;
                   8193: 	return $hostdom{$lonid};
                   8194:     }
                   8195: 
1.841     albertel 8196:     sub all_domains {
1.852     albertel 8197: 	&load_hosts_tab() if (!$loaded);
                   8198: 
1.841     albertel 8199: 	my %seen;
                   8200: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8201: 	return @uniq;
                   8202:     }
1.1       albertel 8203: }
                   8204: 
1.847     albertel 8205: { 
                   8206:     my %iphost;
1.856     albertel 8207:     my %name_to_ip;
                   8208:     my %lonid_to_ip;
1.869     albertel 8209: 
1.847     albertel 8210:     sub get_hosts_from_ip {
                   8211: 	my ($ip) = @_;
                   8212: 	my %iphosts = &get_iphost();
                   8213: 	if (ref($iphosts{$ip})) {
                   8214: 	    return @{$iphosts{$ip}};
                   8215: 	}
                   8216: 	return;
1.839     albertel 8217:     }
1.864     albertel 8218:     
                   8219:     sub reset_hosts_ip_info {
                   8220: 	undef(%iphost);
                   8221: 	undef(%name_to_ip);
                   8222: 	undef(%lonid_to_ip);
                   8223:     }
1.856     albertel 8224: 
                   8225:     sub get_host_ip {
                   8226: 	my ($lonid) = @_;
                   8227: 	if (exists($lonid_to_ip{$lonid})) {
                   8228: 	    return $lonid_to_ip{$lonid};
                   8229: 	}
                   8230: 	my $name=&hostname($lonid);
                   8231:    	my $ip = gethostbyname($name);
                   8232: 	return if (!$ip || length($ip) ne 4);
                   8233: 	$ip=inet_ntoa($ip);
                   8234: 	$name_to_ip{$name}   = $ip;
                   8235: 	$lonid_to_ip{$lonid} = $ip;
                   8236: 	return $ip;
                   8237:     }
1.847     albertel 8238:     
                   8239:     sub get_iphost {
1.869     albertel 8240: 	my ($ignore_cache) = @_;
1.894     albertel 8241: 
1.869     albertel 8242: 	if (!$ignore_cache) {
                   8243: 	    if (%iphost) {
                   8244: 		return %iphost;
                   8245: 	    }
                   8246: 	    my ($ip_info,$cached)=
                   8247: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8248: 	    if ($cached) {
                   8249: 		%iphost      = %{$ip_info->[0]};
                   8250: 		%name_to_ip  = %{$ip_info->[1]};
                   8251: 		%lonid_to_ip = %{$ip_info->[2]};
                   8252: 		return %iphost;
                   8253: 	    }
                   8254: 	}
1.894     albertel 8255: 
                   8256: 	# get yesterday's info for fallback
                   8257: 	my %old_name_to_ip;
                   8258: 	my ($ip_info,$cached)=
                   8259: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8260: 	if ($cached) {
                   8261: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8262: 	}
                   8263: 
1.888     albertel 8264: 	my %name_to_host = &all_names();
                   8265: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8266: 	    my $ip;
                   8267: 	    if (!exists($name_to_ip{$name})) {
                   8268: 		$ip = gethostbyname($name);
                   8269: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8270: 		    if (defined($old_name_to_ip{$name})) {
                   8271: 			$ip = $old_name_to_ip{$name};
                   8272: 			&logthis("Can't find $name defaulting to old $ip");
                   8273: 		    } else {
                   8274: 			&logthis("Name $name no IP found");
                   8275: 			next;
                   8276: 		    }
                   8277: 		} else {
                   8278: 		    $ip=inet_ntoa($ip);
1.847     albertel 8279: 		}
                   8280: 		$name_to_ip{$name} = $ip;
                   8281: 	    } else {
                   8282: 		$ip = $name_to_ip{$name};
1.653     albertel 8283: 	    }
1.888     albertel 8284: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8285: 		$lonid_to_ip{$id} = $ip;
                   8286: 	    }
                   8287: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8288: 	}
1.869     albertel 8289: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8290: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8291: 				      48*60*60);
1.869     albertel 8292: 
1.847     albertel 8293: 	return %iphost;
1.598     albertel 8294:     }
                   8295: }
                   8296: 
1.862     albertel 8297: BEGIN {
                   8298: 
                   8299: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8300:     unless ($readit) {
                   8301: {
                   8302:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8303:     %perlvar = (%perlvar,%{$configvars});
                   8304: }
                   8305: 
                   8306: 
1.1       albertel 8307: # ------------------------------------------------------ Read spare server file
                   8308: {
1.448     albertel 8309:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8310: 
                   8311:     while (my $configline=<$config>) {
                   8312:        chomp($configline);
1.284     matthew  8313:        if ($configline) {
1.784     albertel 8314: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8315: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8316: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8317:        }
                   8318:     }
1.448     albertel 8319:     close($config);
1.1       albertel 8320: }
1.11      www      8321: # ------------------------------------------------------------ Read permissions
                   8322: {
1.448     albertel 8323:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8324: 
                   8325:     while (my $configline=<$config>) {
1.448     albertel 8326: 	chomp($configline);
                   8327: 	if ($configline) {
                   8328: 	    my ($role,$perm)=split(/ /,$configline);
                   8329: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8330: 	}
1.11      www      8331:     }
1.448     albertel 8332:     close($config);
1.11      www      8333: }
                   8334: 
                   8335: # -------------------------------------------- Read plain texts for permissions
                   8336: {
1.448     albertel 8337:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8338: 
                   8339:     while (my $configline=<$config>) {
1.448     albertel 8340: 	chomp($configline);
                   8341: 	if ($configline) {
1.742     raeburn  8342: 	    my ($short,@plain)=split(/:/,$configline);
                   8343:             %{$prp{$short}} = ();
                   8344: 	    if (@plain > 0) {
                   8345:                 $prp{$short}{'std'} = $plain[0];
                   8346:                 for (my $i=1; $i<@plain; $i++) {
                   8347:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8348:                 }
                   8349:             }
1.448     albertel 8350: 	}
1.135     www      8351:     }
1.448     albertel 8352:     close($config);
1.135     www      8353: }
                   8354: 
                   8355: # ---------------------------------------------------------- Read package table
                   8356: {
1.448     albertel 8357:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8358: 
                   8359:     while (my $configline=<$config>) {
1.483     albertel 8360: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8361: 	chomp($configline);
                   8362: 	my ($short,$plain)=split(/:/,$configline);
                   8363: 	my ($pack,$name)=split(/\&/,$short);
                   8364: 	if ($plain ne '') {
                   8365: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8366: 	    $packagetab{$short}=$plain; 
                   8367: 	}
1.11      www      8368:     }
1.448     albertel 8369:     close($config);
1.329     matthew  8370: }
                   8371: 
                   8372: # ------------- set up temporary directory
                   8373: {
                   8374:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8375: 
1.11      www      8376: }
                   8377: 
1.794     albertel 8378: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8379: 				'compress_threshold'=> 20_000,
                   8380:  			        });
1.185     www      8381: 
1.281     www      8382: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8383: $dumpcount=0;
1.22      www      8384: 
1.163     harris41 8385: &logtouch();
1.672     albertel 8386: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8387: $readit=1;
1.564     albertel 8388:     {
                   8389: 	use integer;
                   8390: 	my $test=(2**32)+1;
1.568     albertel 8391: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8392: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8393:     }
1.195     www      8394: }
1.1       albertel 8395: }
1.179     www      8396: 
1.1       albertel 8397: 1;
1.191     harris41 8398: __END__
                   8399: 
1.243     albertel 8400: =pod
                   8401: 
1.191     harris41 8402: =head1 NAME
                   8403: 
1.243     albertel 8404: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8405: 
                   8406: =head1 SYNOPSIS
                   8407: 
1.243     albertel 8408: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8409: 
                   8410:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8411: 
1.243     albertel 8412: Common parameters:
                   8413: 
                   8414: =over 4
                   8415: 
                   8416: =item *
                   8417: 
                   8418: $uname : an internal username (if $cname expecting a course Id specifically)
                   8419: 
                   8420: =item *
                   8421: 
                   8422: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8423: 
                   8424: =item *
                   8425: 
                   8426: $symb : a resource instance identifier
                   8427: 
                   8428: =item *
                   8429: 
                   8430: $namespace : the name of a .db file that contains the data needed or
                   8431: being set.
                   8432: 
                   8433: =back
                   8434: 
1.394     bowersj2 8435: =head1 OVERVIEW
1.191     harris41 8436: 
1.394     bowersj2 8437: lonnet provides subroutines which interact with the
                   8438: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8439: about classes, users, and resources.
1.243     albertel 8440: 
                   8441: For many of these objects you can also use this to store data about
                   8442: them or modify them in various ways.
1.191     harris41 8443: 
1.394     bowersj2 8444: =head2 Symbs
1.191     harris41 8445: 
1.394     bowersj2 8446: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8447: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8448: map, the resource number of the resource in the map, and the URL of
                   8449: the resource itself. The latter is somewhat redundant, but might help
                   8450: if maps change.
                   8451: 
                   8452: An example is
                   8453: 
                   8454:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8455: 
                   8456: The respective map entry is
                   8457: 
                   8458:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8459:   title="Problem 2">
                   8460:  </resource>
                   8461: 
                   8462: Symbs are used by the random number generator, as well as to store and
                   8463: restore data specific to a certain instance of for example a problem.
                   8464: 
                   8465: =head2 Storing And Retrieving Data
                   8466: 
                   8467: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8468: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8469: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8470: is is the non-critical message twin of cstore. These functions are for
                   8471: handlers to store a perl hash to a user's permanent data space in an
                   8472: easy manner, and to retrieve it again on another call. It is expected
                   8473: that a handler would use this once at the beginning to retrieve data,
                   8474: and then again once at the end to send only the new data back.
                   8475: 
                   8476: The data is stored in the user's data directory on the user's
                   8477: homeserver under the ID of the course.
                   8478: 
                   8479: The hash that is returned by restore will have all of the previous
                   8480: value for all of the elements of the hash.
                   8481: 
                   8482: Example:
                   8483: 
                   8484:  #creating a hash
                   8485:  my %hash;
                   8486:  $hash{'foo'}='bar';
                   8487: 
                   8488:  #storing it
                   8489:  &Apache::lonnet::cstore(\%hash);
                   8490: 
                   8491:  #changing a value
                   8492:  $hash{'foo'}='notbar';
                   8493: 
                   8494:  #adding a new value
                   8495:  $hash{'bar'}='foo';
                   8496:  &Apache::lonnet::cstore(\%hash);
                   8497: 
                   8498:  #retrieving the hash
                   8499:  my %history=&Apache::lonnet::restore();
                   8500: 
                   8501:  #print the hash
                   8502:  foreach my $key (sort(keys(%history))) {
                   8503:    print("\%history{$key} = $history{$key}");
                   8504:  }
                   8505: 
                   8506: Will print out:
1.191     harris41 8507: 
1.394     bowersj2 8508:  %history{1:foo} = bar
                   8509:  %history{1:keys} = foo:timestamp
                   8510:  %history{1:timestamp} = 990455579
                   8511:  %history{2:bar} = foo
                   8512:  %history{2:foo} = notbar
                   8513:  %history{2:keys} = foo:bar:timestamp
                   8514:  %history{2:timestamp} = 990455580
                   8515:  %history{bar} = foo
                   8516:  %history{foo} = notbar
                   8517:  %history{timestamp} = 990455580
                   8518:  %history{version} = 2
                   8519: 
                   8520: Note that the special hash entries C<keys>, C<version> and
                   8521: C<timestamp> were added to the hash. C<version> will be equal to the
                   8522: total number of versions of the data that have been stored. The
                   8523: C<timestamp> attribute will be the UNIX time the hash was
                   8524: stored. C<keys> is available in every historical section to list which
                   8525: keys were added or changed at a specific historical revision of a
                   8526: hash.
                   8527: 
                   8528: B<Warning>: do not store the hash that restore returns directly. This
                   8529: will cause a mess since it will restore the historical keys as if the
                   8530: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8531: 
1.394     bowersj2 8532: Calling convention:
1.191     harris41 8533: 
1.394     bowersj2 8534:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8535:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8536: 
1.394     bowersj2 8537: For more detailed information, see lonnet specific documentation.
1.191     harris41 8538: 
1.394     bowersj2 8539: =head1 RETURN MESSAGES
1.191     harris41 8540: 
1.394     bowersj2 8541: =over 4
1.191     harris41 8542: 
1.394     bowersj2 8543: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8544: 
1.394     bowersj2 8545: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8546: when the connection is brought back up
1.191     harris41 8547: 
1.394     bowersj2 8548: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8549: for later delivery
1.191     harris41 8550: 
1.394     bowersj2 8551: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8552: 
1.394     bowersj2 8553: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8554: that was requested
1.191     harris41 8555: 
1.243     albertel 8556: =back
1.191     harris41 8557: 
1.243     albertel 8558: =head1 PUBLIC SUBROUTINES
1.191     harris41 8559: 
1.243     albertel 8560: =head2 Session Environment Functions
1.191     harris41 8561: 
1.243     albertel 8562: =over 4
1.191     harris41 8563: 
1.394     bowersj2 8564: =item * 
                   8565: X<appenv()>
                   8566: B<appenv(%hash)>: the value of %hash is written to
                   8567: the user envirnoment file, and will be restored for each access this
1.620     albertel 8568: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8569: process
1.191     harris41 8570: 
                   8571: =item *
1.394     bowersj2 8572: X<delenv()>
                   8573: B<delenv($regexp)>: removes all items from the session
                   8574: environment file that matches the regular expression in $regexp. The
1.620     albertel 8575: values are also delted from the current processes %env.
1.191     harris41 8576: 
1.795     albertel 8577: =item * get_env_multiple($name) 
                   8578: 
                   8579: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8580: values may be defined and end up as an array ref.
                   8581: 
                   8582: returns an array of values
                   8583: 
1.243     albertel 8584: =back
                   8585: 
                   8586: =head2 User Information
1.191     harris41 8587: 
1.243     albertel 8588: =over 4
1.191     harris41 8589: 
                   8590: =item *
1.394     bowersj2 8591: X<queryauthenticate()>
                   8592: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8593: authentication scheme
                   8594: 
                   8595: =item *
1.394     bowersj2 8596: X<authenticate()>
                   8597: B<authenticate($uname,$upass,$udom)>: try to
                   8598: authenticate user from domain's lib servers (first use the current
                   8599: one). C<$upass> should be the users password.
1.191     harris41 8600: 
                   8601: =item *
1.394     bowersj2 8602: X<homeserver()>
                   8603: B<homeserver($uname,$udom)>: find the server which has
                   8604: the user's directory and files (there must be only one), this caches
                   8605: the answer, and also caches if there is a borken connection.
1.191     harris41 8606: 
                   8607: =item *
1.394     bowersj2 8608: X<idget()>
                   8609: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8610: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8611: username, and only 1 username per ID in a specific domain) (returns
                   8612: hash: id=>name,id=>name)
1.191     harris41 8613: 
                   8614: =item *
1.394     bowersj2 8615: X<idrget()>
                   8616: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8617: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8618: 
                   8619: =item *
1.394     bowersj2 8620: X<idput()>
                   8621: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8622: 
                   8623: =item *
1.394     bowersj2 8624: X<rolesinit()>
                   8625: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8626: 
                   8627: =item *
1.551     albertel 8628: X<getsection()>
                   8629: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8630: course $cname, return section name/number or '' for "not in course"
                   8631: and '-1' for "no section"
                   8632: 
                   8633: =item *
1.394     bowersj2 8634: X<userenvironment()>
                   8635: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8636: passed in @what from the requested user's environment, returns a hash
                   8637: 
1.858     raeburn  8638: =item * 
                   8639: X<userlog_query()>
1.859     albertel 8640: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8641: activity.log file. %filters defines filters applied when parsing the
                   8642: log file. These can be start or end timestamps, or the type of action
                   8643: - log to look for Login or Logout events, check for Checkin or
                   8644: Checkout, role for role selection. The response is in the form
                   8645: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8646: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8647: 
1.243     albertel 8648: =back
                   8649: 
                   8650: =head2 User Roles
                   8651: 
                   8652: =over 4
                   8653: 
                   8654: =item *
                   8655: 
1.810     raeburn  8656: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8657:  F: full access
                   8658:  U,I,K: authentication modes (cxx only)
                   8659:  '': forbidden
                   8660:  1: user needs to choose course
                   8661:  2: browse allowed
1.766     albertel 8662:  A: passphrase authentication needed
1.243     albertel 8663: 
                   8664: =item *
                   8665: 
                   8666: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8667: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8668: and course level
                   8669: 
                   8670: =item *
                   8671: 
                   8672: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8673: explanation of a user role term
                   8674: 
1.832     raeburn  8675: =item *
                   8676: 
1.858     raeburn  8677: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8678: All arguments are optional. Returns a hash of a roles, either for
                   8679: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8680: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8681: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8682: and value is set to colon-separated start and end times for the role.
                   8683: If no username and domain are specified, will default to current
                   8684: user/domain. Types, roles, and roledoms are references to arrays,
                   8685: of role statuses (active, future or previous), roles 
                   8686: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8687: to restrict the list of roles reported. If no array ref is 
                   8688: provided for types, will default to return only active roles.
1.834     albertel 8689: 
1.243     albertel 8690: =back
                   8691: 
                   8692: =head2 User Modification
                   8693: 
                   8694: =over 4
                   8695: 
                   8696: =item *
                   8697: 
                   8698: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8699: user for the level given by URL.  Optional start and end dates (leave empty
                   8700: string or zero for "no date")
1.191     harris41 8701: 
                   8702: =item *
                   8703: 
1.243     albertel 8704: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8705: change a users, password, possible return values are: ok,
                   8706: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8707: refused
1.191     harris41 8708: 
                   8709: =item *
                   8710: 
1.243     albertel 8711: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8712: 
                   8713: =item *
                   8714: 
1.243     albertel 8715: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8716: modify user
1.191     harris41 8717: 
                   8718: =item *
                   8719: 
1.286     matthew  8720: modifystudent
                   8721: 
                   8722: modify a students enrollment and identification information.
                   8723: The course id is resolved based on the current users environment.  
                   8724: This means the envoking user must be a course coordinator or otherwise
                   8725: associated with a course.
                   8726: 
1.297     matthew  8727: This call is essentially a wrapper for lonnet::modifyuser and
                   8728: lonnet::modify_student_enrollment
1.286     matthew  8729: 
                   8730: Inputs: 
                   8731: 
                   8732: =over 4
                   8733: 
                   8734: =item B<$udom> Students loncapa domain
                   8735: 
                   8736: =item B<$uname> Students loncapa login name
                   8737: 
                   8738: =item B<$uid> Students id/student number
                   8739: 
                   8740: =item B<$umode> Students authentication mode
                   8741: 
                   8742: =item B<$upass> Students password
                   8743: 
                   8744: =item B<$first> Students first name
                   8745: 
                   8746: =item B<$middle> Students middle name
                   8747: 
                   8748: =item B<$last> Students last name
                   8749: 
                   8750: =item B<$gene> Students generation
                   8751: 
                   8752: =item B<$usec> Students section in course
                   8753: 
                   8754: =item B<$end> Unix time of the roles expiration
                   8755: 
                   8756: =item B<$start> Unix time of the roles start date
                   8757: 
                   8758: =item B<$forceid> If defined, allow $uid to be changed
                   8759: 
                   8760: =item B<$desiredhome> server to use as home server for student
                   8761: 
                   8762: =back
1.297     matthew  8763: 
                   8764: =item *
                   8765: 
                   8766: modify_student_enrollment
                   8767: 
                   8768: Change a students enrollment status in a class.  The environment variable
                   8769: 'role.request.course' must be defined for this function to proceed.
                   8770: 
                   8771: Inputs:
                   8772: 
                   8773: =over 4
                   8774: 
                   8775: =item $udom, students domain
                   8776: 
                   8777: =item $uname, students name
                   8778: 
                   8779: =item $uid, students user id
                   8780: 
                   8781: =item $first, students first name
                   8782: 
                   8783: =item $middle
                   8784: 
                   8785: =item $last
                   8786: 
                   8787: =item $gene
                   8788: 
                   8789: =item $usec
                   8790: 
                   8791: =item $end
                   8792: 
                   8793: =item $start
                   8794: 
                   8795: =back
                   8796: 
1.191     harris41 8797: 
                   8798: =item *
                   8799: 
1.243     albertel 8800: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8801: custom role; give a custom role to a user for the level given by URL.  Specify
                   8802: name and domain of role author, and role name
1.191     harris41 8803: 
                   8804: =item *
                   8805: 
1.243     albertel 8806: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8807: 
                   8808: =item *
                   8809: 
1.243     albertel 8810: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8811: 
                   8812: =back
                   8813: 
                   8814: =head2 Course Infomation
                   8815: 
                   8816: =over 4
1.191     harris41 8817: 
                   8818: =item *
                   8819: 
1.631     albertel 8820: coursedescription($courseid) : returns a hash of information about the
                   8821: specified course id, including all environment settings for the
                   8822: course, the description of the course will be in the hash under the
                   8823: key 'description'
1.191     harris41 8824: 
                   8825: =item *
                   8826: 
1.624     albertel 8827: resdata($name,$domain,$type,@which) : request for current parameter
                   8828: setting for a specific $type, where $type is either 'course' or 'user',
                   8829: @what should be a list of parameters to ask about. This routine caches
                   8830: answers for 5 minutes.
1.243     albertel 8831: 
1.877     foxr     8832: =item *
                   8833: 
                   8834: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8835: data base, returning a hash that is keyed by the resource name and has
                   8836: values that are the resource value.  I believe that the timestamps and
                   8837: versions are also returned.
                   8838: 
                   8839: 
1.243     albertel 8840: =back
                   8841: 
                   8842: =head2 Course Modification
                   8843: 
                   8844: =over 4
1.191     harris41 8845: 
                   8846: =item *
                   8847: 
1.243     albertel 8848: writecoursepref($courseid,%prefs) : write preferences (environment
                   8849: database) for a course
1.191     harris41 8850: 
                   8851: =item *
                   8852: 
1.243     albertel 8853: createcourse($udom,$description,$url) : make/modify course
                   8854: 
                   8855: =back
                   8856: 
                   8857: =head2 Resource Subroutines
                   8858: 
                   8859: =over 4
1.191     harris41 8860: 
                   8861: =item *
                   8862: 
1.243     albertel 8863: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8864: 
                   8865: =item *
                   8866: 
1.243     albertel 8867: repcopy($filename) : subscribes to the requested file, and attempts to
                   8868: replicate from the owning library server, Might return
1.607     raeburn  8869: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8870: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8871: resource. Expects the local filesystem pathname
                   8872: (/home/httpd/html/res/....)
                   8873: 
                   8874: =back
                   8875: 
                   8876: =head2 Resource Information
                   8877: 
                   8878: =over 4
1.191     harris41 8879: 
                   8880: =item *
                   8881: 
1.243     albertel 8882: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8883: a vairety of different possible values, $varname should be a request
                   8884: string, and the other parameters can be used to specify who and what
                   8885: one is asking about.
                   8886: 
                   8887: Possible values for $varname are environment.lastname (or other item
                   8888: from the envirnment hash), user.name (or someother aspect about the
                   8889: user), resource.0.maxtries (or some other part and parameter of a
                   8890: resource)
1.204     albertel 8891: 
                   8892: =item *
                   8893: 
1.243     albertel 8894: directcondval($number) : get current value of a condition; reads from a state
                   8895: string
1.204     albertel 8896: 
                   8897: =item *
                   8898: 
1.243     albertel 8899: condval($condidx) : value of condition index based on state
1.204     albertel 8900: 
                   8901: =item *
                   8902: 
1.243     albertel 8903: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8904: resource's metadata, $what should be either a specific key, or either
                   8905: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8906: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8907: 
                   8908: this function automatically caches all requests
1.191     harris41 8909: 
                   8910: =item *
                   8911: 
1.243     albertel 8912: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8913: network of library servers; returns file handle of where SQL and regex results
                   8914: will be stored for query
1.191     harris41 8915: 
                   8916: =item *
                   8917: 
1.243     albertel 8918: symbread($filename) : return symbolic list entry (filename argument optional);
                   8919: returns the data handle
1.191     harris41 8920: 
                   8921: =item *
                   8922: 
1.243     albertel 8923: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8924: a possible symb for the URL in $thisfn, and if is an encryypted
                   8925: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8926: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8927: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8928: 
1.191     harris41 8929: 
                   8930: =item *
                   8931: 
1.243     albertel 8932: symbclean($symb) : removes versions numbers from a symb, returns the
                   8933: cleaned symb
1.191     harris41 8934: 
                   8935: =item *
                   8936: 
1.243     albertel 8937: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8938: course map, user must be in a course for it to work.
1.191     harris41 8939: 
                   8940: =item *
                   8941: 
1.243     albertel 8942: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8943: 
                   8944: =item *
                   8945: 
1.243     albertel 8946: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8947: a random seed, all arguments are optional, if they aren't sent it uses the
                   8948: environment to derive them. Note: if symb isn't sent and it can't get one
                   8949: from &symbread it will use the current time as its return value
1.191     harris41 8950: 
                   8951: =item *
                   8952: 
1.243     albertel 8953: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8954: unfakeable, receipt
1.191     harris41 8955: 
                   8956: =item *
                   8957: 
1.620     albertel 8958: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8959: 
                   8960: =item *
                   8961: 
1.243     albertel 8962: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8963: 
                   8964: =item *
                   8965: 
1.243     albertel 8966: 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 8967: 
                   8968: =item *
                   8969: 
1.243     albertel 8970: 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 8971: 
                   8972: =item *
                   8973: 
1.243     albertel 8974: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8975: 
                   8976: =item *
                   8977: 
1.243     albertel 8978: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8979: forcing spreadsheet to reevaluate the resource scores next time.
                   8980: 
                   8981: =back
                   8982: 
                   8983: =head2 Storing/Retreiving Data
                   8984: 
                   8985: =over 4
1.191     harris41 8986: 
                   8987: =item *
                   8988: 
1.243     albertel 8989: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8990: for this url; hashref needs to be given and should be a \%hashname; the
                   8991: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8992: be derived from the env
1.191     harris41 8993: 
                   8994: =item *
                   8995: 
1.243     albertel 8996: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8997: uses critical subroutine
1.191     harris41 8998: 
                   8999: =item *
                   9000: 
1.243     albertel 9001: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9002: all args are optional
1.191     harris41 9003: 
                   9004: =item *
                   9005: 
1.717     albertel 9006: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9007: dumps the complete (or key matching regexp) namespace into a hash
                   9008: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9009: normally &store()ed into
                   9010: 
                   9011: $range should be either an integer '100' (give me the first 100
                   9012:                                            matching records)
                   9013:               or be  two integers sperated by a - with no spaces
                   9014:                  '30-50' (give me the 30th through the 50th matching
                   9015:                           records)
                   9016: 
                   9017: 
                   9018: =item *
                   9019: 
                   9020: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9021: replaces a &store() version of data with a replacement set of data
                   9022: for a particular resource in a namespace passed in the $storehash hash 
                   9023: reference
                   9024: 
                   9025: =item *
                   9026: 
1.243     albertel 9027: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9028: works very similar to store/cstore, but all data is stored in a
                   9029: temporary location and can be reset using tmpreset, $storehash should
                   9030: be a hash reference, returns nothing on success
1.191     harris41 9031: 
                   9032: =item *
                   9033: 
1.243     albertel 9034: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9035: similar to restore, but all data is stored in a temporary location and
                   9036: can be reset using tmpreset. Returns a hash of values on success,
                   9037: error string otherwise.
1.191     harris41 9038: 
                   9039: =item *
                   9040: 
1.243     albertel 9041: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9042: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9043: 
                   9044: =item *
                   9045: 
1.243     albertel 9046: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9047: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9048: 
                   9049: =item *
                   9050: 
1.243     albertel 9051: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9052: namesp ($udom and $uname are optional)
1.191     harris41 9053: 
                   9054: =item *
                   9055: 
1.702     albertel 9056: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9057: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9058: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9059: 
1.702     albertel 9060: $range should be either an integer '100' (give me the first 100
                   9061:                                            matching records)
                   9062:               or be  two integers sperated by a - with no spaces
                   9063:                  '30-50' (give me the 30th through the 50th matching
                   9064:                           records)
1.449     matthew  9065: =item *
                   9066: 
                   9067: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9068: $store can be a scalar, an array reference, or if the amount to be 
                   9069: incremented is > 1, a hash reference.
                   9070: 
                   9071: ($udom and $uname are optional)
1.191     harris41 9072: 
                   9073: =item *
                   9074: 
1.243     albertel 9075: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9076: ($udom and $uname are optional)
1.191     harris41 9077: 
                   9078: =item *
                   9079: 
1.243     albertel 9080: cput($namespace,$storehash,$udom,$uname) : critical put
                   9081: ($udom and $uname are optional)
1.191     harris41 9082: 
                   9083: =item *
                   9084: 
1.748     albertel 9085: newput($namespace,$storehash,$udom,$uname) :
                   9086: 
                   9087: Attempts to store the items in the $storehash, but only if they don't
                   9088: currently exist, if this succeeds you can be certain that you have 
                   9089: successfully created a new key value pair in the $namespace db.
                   9090: 
                   9091: 
                   9092: Args:
                   9093:  $namespace: name of database to store values to
                   9094:  $storehash: hashref to store to the db
                   9095:  $udom: (optional) domain of user containing the db
                   9096:  $uname: (optional) name of user caontaining the db
                   9097: 
                   9098: Returns:
                   9099:  'ok' -> succeeded in storing all keys of $storehash
                   9100:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9101:                         least <key> already existed in the db (other
                   9102:                         requested keys may also already exist)
                   9103:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9104:  'con_lost' -> unable to contact request server
                   9105:  'refused' -> action was not allowed by remote machine
                   9106: 
                   9107: 
                   9108: =item *
                   9109: 
1.243     albertel 9110: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9111: reference filled in from namesp (encrypts the return communication)
                   9112: ($udom and $uname are optional)
1.191     harris41 9113: 
                   9114: =item *
                   9115: 
1.243     albertel 9116: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9117: critical subroutine
                   9118: 
1.806     raeburn  9119: =item *
                   9120: 
1.860     raeburn  9121: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9122: array reference filled in from namespace found in domain level on either
                   9123: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9124: 
                   9125: =item *
                   9126: 
1.860     raeburn  9127: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9128: domain level either on specified domain server ($uhome) or primary domain 
                   9129: server ($udom and $uhome are optional)
1.806     raeburn  9130: 
1.243     albertel 9131: =back
                   9132: 
                   9133: =head2 Network Status Functions
                   9134: 
                   9135: =over 4
1.191     harris41 9136: 
                   9137: =item *
                   9138: 
                   9139: dirlist($uri) : return directory list based on URI
                   9140: 
                   9141: =item *
                   9142: 
1.243     albertel 9143: spareserver() : find server with least workload from spare.tab
                   9144: 
                   9145: =back
                   9146: 
                   9147: =head2 Apache Request
                   9148: 
                   9149: =over 4
1.191     harris41 9150: 
                   9151: =item *
                   9152: 
1.243     albertel 9153: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9154: localhost, posts hash
                   9155: 
                   9156: =back
                   9157: 
                   9158: =head2 Data to String to Data
                   9159: 
                   9160: =over 4
1.191     harris41 9161: 
                   9162: =item *
                   9163: 
1.243     albertel 9164: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9165: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9166: 
                   9167: =item *
                   9168: 
1.243     albertel 9169: hashref2str($hashref) : convert a hashref into a string complete with
                   9170: escaping and '=' and '&' separators, supports elements that are
                   9171: arrayrefs and hashrefs
1.191     harris41 9172: 
                   9173: =item *
                   9174: 
1.243     albertel 9175: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9176: with escaping and '&' separators, supports elements that are arrayrefs
                   9177: and hashrefs
1.191     harris41 9178: 
                   9179: =item *
                   9180: 
1.243     albertel 9181: str2hash($string) : convert string to hash using unescaping and
                   9182: splitting on '=' and '&', supports elements that are arrayrefs and
                   9183: hashrefs
1.191     harris41 9184: 
                   9185: =item *
                   9186: 
1.243     albertel 9187: str2array($string) : convert string to hash using unescaping and
                   9188: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9189: 
                   9190: =back
                   9191: 
                   9192: =head2 Logging Routines
                   9193: 
                   9194: =over 4
                   9195: 
                   9196: These routines allow one to make log messages in the lonnet.log and
                   9197: lonnet.perm logfiles.
1.191     harris41 9198: 
                   9199: =item *
                   9200: 
1.243     albertel 9201: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9202: 
                   9203: =item *
                   9204: 
1.243     albertel 9205: logthis() : append message to the normal lonnet.log file, it gets
                   9206: preiodically rolled over and deleted.
1.191     harris41 9207: 
                   9208: =item *
                   9209: 
1.243     albertel 9210: logperm() : append a permanent message to lonnet.perm.log, this log
                   9211: file never gets deleted by any automated portion of the system, only
                   9212: messages of critical importance should go in here.
                   9213: 
                   9214: =back
                   9215: 
                   9216: =head2 General File Helper Routines
                   9217: 
                   9218: =over 4
1.191     harris41 9219: 
                   9220: =item *
                   9221: 
1.481     raeburn  9222: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9223: (a) files in /uploaded
                   9224:   (i) If a local copy of the file exists - 
                   9225:       compares modification date of local copy with last-modified date for 
                   9226:       definitive version stored on home server for course. If local copy is 
                   9227:       stale, requests a new version from the home server and stores it. 
                   9228:       If the original has been removed from the home server, then local copy 
                   9229:       is unlinked.
                   9230:   (ii) If local copy does not exist -
                   9231:       requests the file from the home server and stores it. 
                   9232:   
                   9233:   If $caller is 'uploadrep':  
                   9234:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9235:     for request for files originally uploaded via DOCS. 
                   9236:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9237:   
                   9238:   Otherwise:
                   9239:      This indicates a call from the content generation phase of the request.
                   9240:      -  returns the entire contents of the file or -1.
                   9241:      
                   9242: (b) files in /res
                   9243:    - returns the entire contents of a file or -1; 
                   9244:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9245: 
1.712     albertel 9246: 
                   9247: =item *
                   9248: 
                   9249: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9250:                   reference
                   9251: 
                   9252: returns either a stat() list of data about the file or an empty list
                   9253: if the file doesn't exist or couldn't find out about it (connection
                   9254: problems or user unknown)
                   9255: 
1.191     harris41 9256: =item *
                   9257: 
1.243     albertel 9258: filelocation($dir,$file) : returns file system location of a file
                   9259: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9260: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9261: and a file of ../bob will become /a/bob)
1.191     harris41 9262: 
                   9263: =item *
                   9264: 
                   9265: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9266: filelocation except for hrefs
                   9267: 
                   9268: =item *
                   9269: 
                   9270: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9271: 
1.243     albertel 9272: =back
                   9273: 
1.608     albertel 9274: =head2 Usererfile file routines (/uploaded*)
                   9275: 
                   9276: =over 4
                   9277: 
                   9278: =item *
                   9279: 
                   9280: userfileupload(): main rotine for putting a file in a user or course's
                   9281:                   filespace, arguments are,
                   9282: 
1.620     albertel 9283:  formname - required - this is the name of the element in $env where the
1.608     albertel 9284:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9285:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9286:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9287:  coursedoc - if true, store the file in the course of the active role
                   9288:              of the current user
                   9289:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9290:          if undefined, it will be placed in "unknown"
                   9291: 
                   9292:  (This routine calls clean_filename() to remove any dangerous
                   9293:  characters from the filename, and then calls finuserfileupload() to
                   9294:  complete the transaction)
                   9295: 
                   9296:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9297:  and /adm/notfound.html if unsuccessful
                   9298: 
                   9299: =item *
                   9300: 
                   9301: clean_filename(): routine for cleaing a filename up for storage in
                   9302:                  userfile space, argument is:
                   9303: 
                   9304:  filename - proposed filename
                   9305: 
                   9306: returns: the new clean filename
                   9307: 
                   9308: =item *
                   9309: 
                   9310: finishuserfileupload(): routine that creaes and sends the file to
                   9311: userspace, probably shouldn't be called directly
                   9312: 
                   9313:   docuname: username or courseid of destination for the file
                   9314:   docudom: domain of user/course of destination for the file
                   9315:   formname: same as for userfileupload()
                   9316:   fname: filename (inculding subdirectories) for the file
                   9317: 
                   9318:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9319:  and /adm/notfound.html if unsuccessful
                   9320: 
                   9321: =item *
                   9322: 
                   9323: renameuserfile(): renames an existing userfile to a new name
                   9324: 
                   9325:   Args:
                   9326:    docuname: username or courseid of destination for the file
                   9327:    docudom: domain of user/course of destination for the file
                   9328:    old: current file name (including any subdirs under userfiles)
                   9329:    new: desired file name (including any subdirs under userfiles)
                   9330: 
                   9331: =item *
                   9332: 
                   9333: mkdiruserfile(): creates a directory is a userfiles dir
                   9334: 
                   9335:   Args:
                   9336:    docuname: username or courseid of destination for the file
                   9337:    docudom: domain of user/course of destination for the file
                   9338:    dir: dir to create (including any subdirs under userfiles)
                   9339: 
                   9340: =item *
                   9341: 
                   9342: removeuserfile(): removes a file that exists in userfiles
                   9343: 
                   9344:   Args:
                   9345:    docuname: username or courseid of destination for the file
                   9346:    docudom: domain of user/course of destination for the file
                   9347:    fname: filname to delete (including any subdirs under userfiles)
                   9348: 
                   9349: =item *
                   9350: 
                   9351: removeuploadedurl(): convience function for removeuserfile()
                   9352: 
                   9353:   Args:
                   9354:    url:  a full /uploaded/... url to delete
                   9355: 
1.747     albertel 9356: =item * 
                   9357: 
                   9358: get_portfile_permissions():
                   9359:   Args:
                   9360:     domain: domain of user or course contain the portfolio files
                   9361:     user: name of user or num of course contain the portfolio files
                   9362:   Returns:
                   9363:     hashref of a dump of the proper file_permissions.db
                   9364:    
                   9365: 
                   9366: =item * 
                   9367: 
                   9368: get_access_controls():
                   9369: 
                   9370: Args:
                   9371:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9372:   group: (optional) the group you want the files associated with
                   9373:   file: (optional) the file you want access info on
                   9374: 
                   9375: Returns:
1.749     raeburn  9376:     a hash (keys are file names) of hashes containing
                   9377:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9378:         values are XML containing access control settings (see below) 
1.747     albertel 9379: 
                   9380: Internal notes:
                   9381: 
1.749     raeburn  9382:  access controls are stored in file_permissions.db as key=value pairs.
                   9383:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9384:         where scope -> public,guest,course,group,domains or users.
                   9385:               end -> UNIX time for end of access (0 -> no end date)
                   9386:               start -> UNIX time for start of access
                   9387: 
                   9388:     value -> XML description of access control
                   9389:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9390:             <start></start>
                   9391:             <end></end>
                   9392: 
                   9393:             <password></password>  for scope type = guest
                   9394: 
                   9395:             <domain></domain>     for scope type = course or group
                   9396:             <number></number>
                   9397:             <roles id="">
                   9398:              <role></role>
                   9399:              <access></access>
                   9400:              <section></section>
                   9401:              <group></group>
                   9402:             </roles>
                   9403: 
                   9404:             <dom></dom>         for scope type = domains
                   9405: 
                   9406:             <users>             for scope type = users
                   9407:              <user>
                   9408:               <uname></uname>
                   9409:               <udom></udom>
                   9410:              </user>
                   9411:             </users>
                   9412:            </scope> 
                   9413:               
                   9414:  Access data is also aggregated for each file in an additional key=value pair:
                   9415:  key -> path to file/file_name\0accesscontrol 
                   9416:  value -> reference to hash
                   9417:           hash contains key = value pairs
                   9418:           where key = uniqueID:scope_end_start
                   9419:                 value = UNIX time record was last updated
                   9420: 
                   9421:           Used to improve speed of look-ups of access controls for each file.  
                   9422:  
                   9423:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9424: 
                   9425: modify_access_controls():
                   9426: 
                   9427: Modifies access controls for a portfolio file
                   9428: Args
                   9429: 1. file name
                   9430: 2. reference to hash of required changes,
                   9431: 3. domain
                   9432: 4. username
                   9433:   where domain,username are the domain of the portfolio owner 
                   9434:   (either a user or a course) 
                   9435: 
                   9436: Returns:
                   9437: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9438: 2. result of deletions ('ok' or 'error', with error message).
                   9439: 3. reference to hash of any new or updated access controls.
                   9440: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9441:    key = integer (inbound ID)
                   9442:    value = uniqueID  
1.747     albertel 9443: 
1.608     albertel 9444: =back
                   9445: 
1.243     albertel 9446: =head2 HTTP Helper Routines
                   9447: 
                   9448: =over 4
                   9449: 
1.191     harris41 9450: =item *
                   9451: 
                   9452: escape() : unpack non-word characters into CGI-compatible hex codes
                   9453: 
                   9454: =item *
                   9455: 
                   9456: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9457: 
1.243     albertel 9458: =back
                   9459: 
                   9460: =head1 PRIVATE SUBROUTINES
                   9461: 
                   9462: =head2 Underlying communication routines (Shouldn't call)
                   9463: 
                   9464: =over 4
                   9465: 
                   9466: =item *
                   9467: 
                   9468: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9469: 
                   9470: =item *
                   9471: 
                   9472: reply() : uses subreply to send a message to remote machine, logs all failures
                   9473: 
                   9474: =item *
                   9475: 
                   9476: critical() : passes a critical message to another server; if cannot
                   9477: get through then place message in connection buffer directory and
                   9478: returns con_delayed, if incapable of saving message, returns
                   9479: con_failed
                   9480: 
                   9481: =item *
                   9482: 
                   9483: reconlonc() : tries to reconnect lonc client processes.
                   9484: 
                   9485: =back
                   9486: 
                   9487: =head2 Resource Access Logging
                   9488: 
                   9489: =over 4
                   9490: 
                   9491: =item *
                   9492: 
                   9493: flushcourselogs() : flush (save) buffer logs and access logs
                   9494: 
                   9495: =item *
                   9496: 
                   9497: courselog($what) : save message for course in hash
                   9498: 
                   9499: =item *
                   9500: 
                   9501: courseacclog($what) : save message for course using &courselog().  Perform
                   9502: special processing for specific resource types (problems, exams, quizzes, etc).
                   9503: 
1.191     harris41 9504: =item *
                   9505: 
                   9506: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9507: as a PerlChildExitHandler
1.243     albertel 9508: 
                   9509: =back
                   9510: 
                   9511: =head2 Other
                   9512: 
                   9513: =over 4
                   9514: 
                   9515: =item *
                   9516: 
                   9517: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9518: 
                   9519: =back
                   9520: 
                   9521: =cut
1.877     foxr     9522: 

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