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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.821   ! raeburn     4: # $Id: lonnet.pm,v 1.820 2007/01/03 01:50:10 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.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.807     albertel   56: use LONCAPA qw(:DEFAULT :match);
1.740     www        57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.783     albertel  295: sub convert_and_load_session_env {
                    296:     my ($lonidsdir,$handle)=@_;
                    297:     my @profile;
                    298:     {
                    299: 	open(my $idf,"$lonidsdir/$handle.id");
                    300: 	flock($idf,LOCK_SH);
                    301: 	@profile=<$idf>;
                    302: 	close($idf);
                    303:     }
                    304:     my %temp_env;
                    305:     foreach my $line (@profile) {
1.786     albertel  306: 	if ($line !~ m/=/) {
                    307: 	    return 0;
                    308: 	}
1.783     albertel  309: 	chomp($line);
                    310: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    311: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    312:     }
                    313:     unlink("$lonidsdir/$handle.id");
                    314:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    315: 	    0640)) {
                    316: 	%disk_env = %temp_env;
                    317: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    318: 	untie(%disk_env);
                    319:     }
1.786     albertel  320:     return 1;
1.783     albertel  321: }
                    322: 
1.374     www       323: # ------------------------------------------- Transfer profile into environment
1.780     albertel  324: my $env_loaded;
                    325: sub transfer_profile_to_env {
1.788     albertel  326:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    327:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       328: 
1.720     albertel  329:     if (!defined($lonidsdir)) {
                    330: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    331:     }
                    332:     if (!defined($handle)) {
                    333:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    334:     }
                    335: 
1.786     albertel  336:     my $convert;
                    337:     {
                    338:     	open(my $idf,"$lonidsdir/$handle.id");
                    339: 	flock($idf,LOCK_SH);
                    340: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    341: 		&GDBM_READER(),0640)) {
                    342: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    343: 	    untie(%disk_env);
                    344: 	} else {
                    345: 	    $convert = 1;
                    346: 	}
                    347:     }
                    348:     if ($convert) {
                    349: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    350: 	    &logthis("Failed to load session, or convert session.");
                    351: 	}
1.374     www       352:     }
1.783     albertel  353: 
1.786     albertel  354:     my %remove;
1.783     albertel  355:     while ( my $envname = each(%env) ) {
1.433     matthew   356:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    357:             if ($time < time-300) {
1.783     albertel  358:                 $remove{$key}++;
1.433     matthew   359:             }
                    360:         }
                    361:     }
1.783     albertel  362: 
1.619     albertel  363:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  364:     $env_loaded=1;
1.783     albertel  365:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   366:         &delenv($expired_key);
1.374     www       367:     }
1.1       albertel  368: }
                    369: 
1.5       www       370: # ---------------------------------------------------------- Append Environment
                    371: 
                    372: sub appenv {
1.6       www       373:     my %newenv=@_;
1.692     albertel  374:     foreach my $key (keys(%newenv)) {
                    375: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  376:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  377:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       378:                 .'</font>');
1.692     albertel  379: 	    delete($newenv{$key});
1.35      www       380:         } else {
1.692     albertel  381:             $env{$key}=$newenv{$key};
1.35      www       382:         }
1.191     harris41  383:     }
1.783     albertel  384:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    385: 	    0640)) {
                    386: 	while (my ($key,$value) = each(%newenv)) {
                    387: 	    $disk_env{$key} = $value;
1.448     albertel  388: 	}
1.783     albertel  389: 	untie(%disk_env);
1.56      www       390:     }
                    391:     return 'ok';
                    392: }
                    393: # ----------------------------------------------------- Delete from Environment
                    394: 
                    395: sub delenv {
                    396:     my $delthis=shift;
                    397:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  398:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       399:                 "Attempt to delete from environment ".$delthis);
                    400:         return 'error';
                    401:     }
1.783     albertel  402:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    403: 	    0640)) {
                    404: 	foreach my $key (keys(%disk_env)) {
                    405: 	    if ($key=~/^$delthis/) { 
1.619     albertel  406:                 delete($env{$key});
1.783     albertel  407:                 delete($disk_env{$key});
1.473     matthew   408:             }
1.448     albertel  409: 	}
1.783     albertel  410: 	untie(%disk_env);
1.5       www       411:     }
                    412:     return 'ok';
1.369     albertel  413: }
                    414: 
1.790     albertel  415: sub get_env_multiple {
                    416:     my ($name) = @_;
                    417:     my @values;
                    418:     if (defined($env{$name})) {
                    419:         # exists is it an array
                    420:         if (ref($env{$name})) {
                    421:             @values=@{ $env{$name} };
                    422:         } else {
                    423:             $values[0]=$env{$name};
                    424:         }
                    425:     }
                    426:     return(@values);
                    427: }
                    428: 
1.369     albertel  429: # ------------------------------------------ Find out current server userload
                    430: # there is a copy in lond
                    431: sub userload {
                    432:     my $numusers=0;
                    433:     {
                    434: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    435: 	my $filename;
                    436: 	my $curtime=time;
                    437: 	while ($filename=readdir(LONIDS)) {
                    438: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  439: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  440: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  441: 	}
                    442: 	closedir(LONIDS);
                    443:     }
                    444:     my $userloadpercent=0;
                    445:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    446:     if ($maxuserload) {
1.371     albertel  447: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  448:     }
1.372     albertel  449:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  450:     return $userloadpercent;
1.283     www       451: }
                    452: 
                    453: # ------------------------------------------ Fight off request when overloaded
                    454: 
                    455: sub overloaderror {
                    456:     my ($r,$checkserver)=@_;
                    457:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    458:     my $loadavg;
                    459:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  460:        open(my $loadfile,'/proc/loadavg');
1.283     www       461:        $loadavg=<$loadfile>;
                    462:        $loadavg =~ s/\s.*//g;
1.285     matthew   463:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  464:        close($loadfile);
1.283     www       465:     } else {
                    466:        $loadavg=&reply('load',$checkserver);
                    467:     }
1.285     matthew   468:     my $overload=$loadavg-100;
1.283     www       469:     if ($overload>0) {
1.285     matthew   470: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       471:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       472:         return 413;
1.283     www       473:     }    
                    474:     return '';
1.5       www       475: }
1.1       albertel  476: 
                    477: # ------------------------------ Find server with least workload from spare.tab
1.11      www       478: 
1.1       albertel  479: sub spareserver {
1.670     albertel  480:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  481:     my $spare_server;
1.370     albertel  482:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  483:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    484:                                                      :  $userloadpercent;
                    485:     
                    486:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    487: 	($spare_server, $lowest_load) =
                    488: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    489:     }
                    490: 
                    491:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    492: 
                    493:     if (!$found_server) {
                    494: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    495: 	    ($spare_server, $lowest_load) =
                    496: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    497: 	}
                    498:     }
                    499: 
                    500:     if (!$want_server_name) {
                    501: 	$spare_server="http://$hostname{$spare_server}";
                    502:     }
                    503:     return $spare_server;
                    504: }
                    505: 
                    506: sub compare_server_load {
                    507:     my ($try_server, $spare_server, $lowest_load) = @_;
                    508: 
                    509:     my $loadans     = &reply('load',    $try_server);
                    510:     my $userloadans = &reply('userload',$try_server);
                    511: 
                    512:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    513: 	next; #didn't get a number from the server
                    514:     }
                    515: 
                    516:     my $load;
                    517:     if ($loadans =~ /\d/) {
                    518: 	if ($userloadans =~ /\d/) {
                    519: 	    #both are numbers, pick the bigger one
                    520: 	    $load = ($loadans > $userloadans) ? $loadans 
                    521: 		                              : $userloadans;
1.411     albertel  522: 	} else {
1.784     albertel  523: 	    $load = $loadans;
1.411     albertel  524: 	}
1.784     albertel  525:     } else {
                    526: 	$load = $userloadans;
                    527:     }
                    528: 
                    529:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    530: 	$spare_server = $try_server;
                    531: 	$lowest_load  = $load;
1.370     albertel  532:     }
1.784     albertel  533:     return ($spare_server,$lowest_load);
1.202     matthew   534: }
                    535: # --------------------------------------------- Try to change a user's password
                    536: 
                    537: sub changepass {
1.799     raeburn   538:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   539:     $currentpass = &escape($currentpass);
                    540:     $newpass     = &escape($newpass);
1.799     raeburn   541:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   542: 		       $server);
                    543:     if (! $answer) {
                    544: 	&logthis("No reply on password change request to $server ".
                    545: 		 "by $uname in domain $udom.");
                    546:     } elsif ($answer =~ "^ok") {
                    547:         &logthis("$uname in $udom successfully changed their password ".
                    548: 		 "on $server.");
                    549:     } elsif ($answer =~ "^pwchange_failure") {
                    550: 	&logthis("$uname in $udom was unable to change their password ".
                    551: 		 "on $server.  The action was blocked by either lcpasswd ".
                    552: 		 "or pwchange");
                    553:     } elsif ($answer =~ "^non_authorized") {
                    554:         &logthis("$uname in $udom did not get their password correct when ".
                    555: 		 "attempting to change it on $server.");
                    556:     } elsif ($answer =~ "^auth_mode_error") {
                    557:         &logthis("$uname in $udom attempted to change their password despite ".
                    558: 		 "not being locally or internally authenticated on $server.");
                    559:     } elsif ($answer =~ "^unknown_user") {
                    560:         &logthis("$uname in $udom attempted to change their password ".
                    561: 		 "on $server but were unable to because $server is not ".
                    562: 		 "their home server.");
                    563:     } elsif ($answer =~ "^refused") {
                    564: 	&logthis("$server refused to change $uname in $udom password because ".
                    565: 		 "it was sent an unencrypted request to change the password.");
                    566:     }
                    567:     return $answer;
1.1       albertel  568: }
                    569: 
1.169     harris41  570: # ----------------------- Try to determine user's current authentication scheme
                    571: 
                    572: sub queryauthenticate {
                    573:     my ($uname,$udom)=@_;
1.456     albertel  574:     my $uhome=&homeserver($uname,$udom);
                    575:     if (!$uhome) {
                    576: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    577: 	return 'no_host';
                    578:     }
                    579:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    580:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    581: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  582:     }
1.456     albertel  583:     return $answer;
1.169     harris41  584: }
                    585: 
1.1       albertel  586: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       587: 
1.1       albertel  588: sub authenticate {
                    589:     my ($uname,$upass,$udom)=@_;
1.807     albertel  590:     $upass=&escape($upass);
                    591:     $uname= &LONCAPA::clean_username($uname);
1.471     albertel  592:     my $uhome=&homeserver($uname,$udom);
                    593:     if (!$uhome) {
                    594: 	&logthis("User $uname at $udom is unknown in authenticate");
                    595: 	return 'no_host';
1.1       albertel  596:     }
1.471     albertel  597:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    598:     if ($answer eq 'authorized') {
                    599: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    600: 	return $uhome; 
                    601:     }
                    602:     if ($answer eq 'non_authorized') {
                    603: 	&logthis("User $uname at $udom rejected by $uhome");
                    604: 	return 'no_host'; 
1.9       www       605:     }
1.471     albertel  606:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  607:     return 'no_host';
                    608: }
                    609: 
                    610: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       611: 
1.599     albertel  612: my %homecache;
1.1       albertel  613: sub homeserver {
1.230     stredwic  614:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  615:     my $index="$uname:$udom";
1.426     albertel  616: 
1.599     albertel  617:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  618:     my $tryserver;
                    619:     foreach $tryserver (keys %libserv) {
1.230     stredwic  620:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  621: 		 exists($badServerCache{$tryserver}));
1.1       albertel  622: 	if ($hostdom{$tryserver} eq $udom) {
                    623:            my $answer=reply("home:$udom:$uname",$tryserver);
                    624:            if ($answer eq 'found') { 
1.599     albertel  625: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  626:            } elsif ($answer eq 'no_host') {
                    627: 	       $badServerCache{$tryserver}=1;
1.221     matthew   628:            }
1.1       albertel  629:        }
                    630:     }    
                    631:     return 'no_host';
1.70      www       632: }
                    633: 
                    634: # ------------------------------------- Find the usernames behind a list of IDs
                    635: 
                    636: sub idget {
                    637:     my ($udom,@ids)=@_;
                    638:     my %returnhash=();
                    639:     
                    640:     my $tryserver;
                    641:     foreach $tryserver (keys %libserv) {
                    642:        if ($hostdom{$tryserver} eq $udom) {
                    643: 	  my $idlist=join('&',@ids);
                    644:           $idlist=~tr/A-Z/a-z/; 
                    645: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    646:           my @answer=();
1.76      www       647:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       648: 	      @answer=split(/\&/,$reply);
                    649:           }                    ;
                    650:           my $i;
                    651:           for ($i=0;$i<=$#ids;$i++) {
                    652:               if ($answer[$i]) {
                    653: 		  $returnhash{$ids[$i]}=$answer[$i];
                    654:               } 
                    655:           }
                    656:        }
                    657:     }    
                    658:     return %returnhash;
                    659: }
                    660: 
                    661: # ------------------------------------- Find the IDs behind a list of usernames
                    662: 
                    663: sub idrget {
                    664:     my ($udom,@unames)=@_;
                    665:     my %returnhash=();
1.800     albertel  666:     foreach my $uname (@unames) {
                    667:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  668:     }
1.70      www       669:     return %returnhash;
                    670: }
                    671: 
                    672: # ------------------------------- Store away a list of names and associated IDs
                    673: 
                    674: sub idput {
                    675:     my ($udom,%ids)=@_;
                    676:     my %servers=();
1.800     albertel  677:     foreach my $uname (keys(%ids)) {
                    678: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    679:         my $uhom=&homeserver($uname,$udom);
1.70      www       680:         if ($uhom ne 'no_host') {
1.800     albertel  681:             my $id=&escape($ids{$uname});
1.70      www       682:             $id=~tr/A-Z/a-z/;
1.800     albertel  683:             my $esc_unam=&escape($uname);
1.70      www       684: 	    if ($servers{$uhom}) {
1.800     albertel  685: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       686:             } else {
1.800     albertel  687:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       688:             }
                    689:         }
1.191     harris41  690:     }
1.800     albertel  691:     foreach my $server (keys(%servers)) {
                    692:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  693:     }
1.344     www       694: }
                    695: 
1.806     raeburn   696: # ------------------------------------------- get items from domain db files   
                    697: 
                    698: sub get_dom {
                    699:     my ($namespace,$storearr,$udom)=@_;
                    700:     my $items='';
                    701:     foreach my $item (@$storearr) {
                    702:         $items.=&escape($item).'&';
                    703:     }
                    704:     $items=~s/\&$//;
                    705:     if (!$udom) { $udom=$env{'user.domain'}; }
                    706:     if (exists($domain_primary{$udom})) {
                    707:         my $uhome=$domain_primary{$udom};
                    708:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    709:         my @pairs=split(/\&/,$rep);
                    710:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    711:             return @pairs;
                    712:         }
                    713:         my %returnhash=();
                    714:         my $i=0;
                    715:         foreach my $item (@$storearr) {
                    716:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    717:             $i++;
                    718:         }
                    719:         return %returnhash;
                    720:     } else {
                    721:         &logthis("get_dom failed - no primary domain server for $udom");
                    722:     }
                    723: }
                    724: 
                    725: # -------------------------------------------- put items in domain db files 
                    726: 
                    727: sub put_dom {
                    728:     my ($namespace,$storehash,$udom)=@_;
                    729:     if (!$udom) { $udom=$env{'user.domain'}; }
                    730:     if (exists($domain_primary{$udom})) {
                    731:         my $uhome=$domain_primary{$udom};
                    732:         my $items='';
                    733:         foreach my $item (keys(%$storehash)) {
                    734:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    735:         }
                    736:         $items=~s/\&$//;
                    737:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    738:     } else {
                    739:         &logthis("put_dom failed - no primary domain server for $udom");
                    740:     }
                    741: }
                    742: 
1.344     www       743: # --------------------------------------------------- Assign a key to a student
                    744: 
                    745: sub assign_access_key {
1.364     www       746: #
                    747: # a valid key looks like uname:udom#comments
                    748: # comments are being appended
                    749: #
1.498     www       750:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    751:     $kdom=
1.620     albertel  752:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       753:     $knum=
1.620     albertel  754:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       755:     $cdom=
1.620     albertel  756:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       757:     $cnum=
1.620     albertel  758:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    759:     $udom=$env{'user.name'} unless (defined($udom));
                    760:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       761:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       762:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  763:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       764:                                                   # assigned to this person
                    765:                                                   # - this should not happen,
1.345     www       766:                                                   # unless something went wrong
                    767:                                                   # the first time around
                    768: # ready to assign
1.364     www       769:         $logentry=$1.'; '.$logentry;
1.496     www       770:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       771:                                                  $kdom,$knum) eq 'ok') {
1.345     www       772: # key now belongs to user
1.346     www       773: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       774:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    775:                 &appenv('environment.'.$envkey => $ckey);
                    776:                 return 'ok';
                    777:             } else {
                    778:                 return 
                    779:   'error: Count not permanently assign key, will need to be re-entered later.';
                    780: 	    }
                    781:         } else {
                    782:             return 'error: Could not assign key, try again later.';
                    783:         }
1.364     www       784:     } elsif (!$existing{$ckey}) {
1.345     www       785: # the key does not exist
                    786: 	return 'error: The key does not exist';
                    787:     } else {
                    788: # the key is somebody else's
                    789: 	return 'error: The key is already in use';
                    790:     }
1.344     www       791: }
                    792: 
1.364     www       793: # ------------------------------------------ put an additional comment on a key
                    794: 
                    795: sub comment_access_key {
                    796: #
                    797: # a valid key looks like uname:udom#comments
                    798: # comments are being appended
                    799: #
                    800:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    801:     $cdom=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       803:     $cnum=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       805:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    806:     if ($existing{$ckey}) {
                    807:         $existing{$ckey}.='; '.$logentry;
                    808: # ready to assign
1.367     www       809:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       810:                                                  $cdom,$cnum) eq 'ok') {
                    811: 	    return 'ok';
                    812:         } else {
                    813: 	    return 'error: Count not store comment.';
                    814:         }
                    815:     } else {
                    816: # the key does not exist
                    817: 	return 'error: The key does not exist';
                    818:     }
                    819: }
                    820: 
1.344     www       821: # ------------------------------------------------------ Generate a set of keys
                    822: 
                    823: sub generate_access_keys {
1.364     www       824:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       825:     $cdom=
1.620     albertel  826:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       827:     $cnum=
1.620     albertel  828:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       829:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       830:     unless (($cdom) && ($cnum)) { return 0; }
                    831:     if ($number>10000) { return 0; }
                    832:     sleep(2); # make sure don't get same seed twice
                    833:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    834:     my $total=0;
                    835:     for (my $i=1;$i<=$number;$i++) {
                    836:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    837:                   sprintf("%lx",int(100000*rand)).'-'.
                    838:                   sprintf("%lx",int(100000*rand));
                    839:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    840:        $newkey=~s/0/h/g; # and also 0 and O
                    841:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    842:        if ($existing{$newkey}) {
                    843:            $i--;
                    844:        } else {
1.364     www       845: 	  if (&put('accesskeys',
                    846:               { $newkey => '# generated '.localtime().
1.620     albertel  847:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       848:                            '; '.$logentry },
                    849: 		   $cdom,$cnum) eq 'ok') {
1.344     www       850:               $total++;
                    851: 	  }
                    852:        }
                    853:     }
1.620     albertel  854:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       855:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    856:     return $total;
                    857: }
                    858: 
                    859: # ------------------------------------------------------- Validate an accesskey
                    860: 
                    861: sub validate_access_key {
                    862:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    863:     $cdom=
1.620     albertel  864:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       865:     $cnum=
1.620     albertel  866:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    867:     $udom=$env{'user.domain'} unless (defined($udom));
                    868:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       869:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  870:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       871: }
                    872: 
                    873: # ------------------------------------- Find the section of student in a course
1.652     albertel  874: sub devalidate_getsection_cache {
                    875:     my ($udom,$unam,$courseid)=@_;
                    876:     my $hashid="$udom:$unam:$courseid";
                    877:     &devalidate_cache_new('getsection',$hashid);
                    878: }
1.298     matthew   879: 
1.815     albertel  880: sub courseid_to_courseurl {
                    881:     my ($courseid) = @_;
                    882:     #already url style courseid
                    883:     return $courseid if ($courseid =~ m{^/});
                    884: 
                    885:     if (exists($env{'course.'.$courseid.'.num'})) {
                    886: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    887: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    888: 	return "/$cdom/$cnum";
                    889:     }
                    890: 
                    891:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    892:     if (exists($courseinfo{'num'})) {
                    893: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    894:     }
                    895: 
                    896:     return undef;
                    897: }
                    898: 
1.298     matthew   899: sub getsection {
                    900:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  901:     my $cachetime=1800;
1.551     albertel  902: 
                    903:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  904:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  905:     if (defined($cached)) { return $result; }
                    906: 
1.298     matthew   907:     my %Pending; 
                    908:     my %Expired;
                    909:     #
                    910:     # Each role can either have not started yet (pending), be active, 
                    911:     #    or have expired.
                    912:     #
                    913:     # If there is an active role, we are done.
                    914:     #
                    915:     # If there is more than one role which has not started yet, 
                    916:     #     choose the one which will start sooner
                    917:     # If there is one role which has not started yet, return it.
                    918:     #
                    919:     # If there is more than one expired role, choose the one which ended last.
                    920:     # If there is a role which has expired, return it.
                    921:     #
1.815     albertel  922:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   923:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    924:     foreach my $key (keys(%roleshash)) {
1.479     albertel  925:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   926:         my $section=$1;
                    927:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   928:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   929:         my $now=time;
1.548     albertel  930:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   931:             $Expired{$end}=$section;
                    932:             next;
                    933:         }
1.548     albertel  934:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   935:             $Pending{$start}=$section;
                    936:             next;
                    937:         }
1.599     albertel  938:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   939:     }
                    940:     #
                    941:     # Presumedly there will be few matching roles from the above
                    942:     # loop and the sorting time will be negligible.
                    943:     if (scalar(keys(%Pending))) {
                    944:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  945:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   946:     } 
                    947:     if (scalar(keys(%Expired))) {
                    948:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    949:         my $time = pop(@sorted);
1.599     albertel  950:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   951:     }
1.599     albertel  952:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   953: }
1.70      www       954: 
1.599     albertel  955: sub save_cache {
                    956:     &purge_remembered();
1.722     albertel  957:     #&Apache::loncommon::validate_page();
1.620     albertel  958:     undef(%env);
1.780     albertel  959:     undef($env_loaded);
1.599     albertel  960: }
1.452     albertel  961: 
1.599     albertel  962: my $to_remember=-1;
                    963: my %remembered;
                    964: my %accessed;
                    965: my $kicks=0;
                    966: my $hits=0;
                    967: sub devalidate_cache_new {
                    968:     my ($name,$id,$debug) = @_;
                    969:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    970:     $id=&escape($name.':'.$id);
                    971:     $memcache->delete($id);
                    972:     delete($remembered{$id});
                    973:     delete($accessed{$id});
                    974: }
                    975: 
                    976: sub is_cached_new {
                    977:     my ($name,$id,$debug) = @_;
                    978:     $id=&escape($name.':'.$id);
                    979:     if (exists($remembered{$id})) {
                    980: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    981: 	$accessed{$id}=[&gettimeofday()];
                    982: 	$hits++;
                    983: 	return ($remembered{$id},1);
                    984:     }
                    985:     my $value = $memcache->get($id);
                    986:     if (!(defined($value))) {
                    987: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  988: 	return (undef,undef);
1.416     albertel  989:     }
1.599     albertel  990:     if ($value eq '__undef__') {
                    991: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    992: 	$value=undef;
                    993:     }
                    994:     &make_room($id,$value,$debug);
                    995:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    996:     return ($value,1);
                    997: }
                    998: 
                    999: sub do_cache_new {
                   1000:     my ($name,$id,$value,$time,$debug) = @_;
                   1001:     $id=&escape($name.':'.$id);
                   1002:     my $setvalue=$value;
                   1003:     if (!defined($setvalue)) {
                   1004: 	$setvalue='__undef__';
                   1005:     }
1.623     albertel 1006:     if (!defined($time) ) {
                   1007: 	$time=600;
                   1008:     }
1.599     albertel 1009:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1010:     $memcache->set($id,$setvalue,$time);
                   1011:     # need to make a copy of $value
                   1012:     #&make_room($id,$value,$debug);
1.599     albertel 1013:     return $value;
                   1014: }
                   1015: 
                   1016: sub make_room {
                   1017:     my ($id,$value,$debug)=@_;
                   1018:     $remembered{$id}=$value;
                   1019:     if ($to_remember<0) { return; }
                   1020:     $accessed{$id}=[&gettimeofday()];
                   1021:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1022:     my $to_kick;
                   1023:     my $max_time=0;
                   1024:     foreach my $other (keys(%accessed)) {
                   1025: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1026: 	    $to_kick=$other;
                   1027: 	    $max_time=&tv_interval($accessed{$other});
                   1028: 	}
                   1029:     }
                   1030:     delete($remembered{$to_kick});
                   1031:     delete($accessed{$to_kick});
                   1032:     $kicks++;
                   1033:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1034:     return;
                   1035: }
                   1036: 
1.599     albertel 1037: sub purge_remembered {
1.604     albertel 1038:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1039:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1040:     undef(%remembered);
                   1041:     undef(%accessed);
1.428     albertel 1042: }
1.70      www      1043: # ------------------------------------- Read an entry from a user's environment
                   1044: 
                   1045: sub userenvironment {
                   1046:     my ($udom,$unam,@what)=@_;
                   1047:     my %returnhash=();
                   1048:     my @answer=split(/\&/,
                   1049:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1050:                       &homeserver($unam,$udom)));
                   1051:     my $i;
                   1052:     for ($i=0;$i<=$#what;$i++) {
                   1053: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1054:     }
                   1055:     return %returnhash;
1.1       albertel 1056: }
                   1057: 
1.617     albertel 1058: # ---------------------------------------------------------- Get a studentphoto
                   1059: sub studentphoto {
                   1060:     my ($udom,$unam,$ext) = @_;
                   1061:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1062:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1063:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1064:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1065:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1066:             } else {
                   1067:                 my ($result,$perm_reqd)=
1.707     albertel 1068: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1069:                 if ($result eq 'ok') {
                   1070:                     if (!($perm_reqd eq 'yes')) {
                   1071:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1072:                     }
                   1073:                 }
                   1074:             }
                   1075:         }
                   1076:     } else {
                   1077:         my ($result,$perm_reqd) = 
1.707     albertel 1078: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1079:         if ($result eq 'ok') {
                   1080:             if (!($perm_reqd eq 'yes')) {
                   1081:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1082:             }
                   1083:         }
                   1084:     }
                   1085:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1086: }
                   1087: 
                   1088: sub retrievestudentphoto {
                   1089:     my ($udom,$unam,$ext,$type) = @_;
                   1090:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1091:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1092:     if ($ret eq 'ok') {
                   1093:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1094:         if ($type eq 'thumbnail') {
                   1095:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1096:         }
                   1097:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1098:         return $tokenurl;
                   1099:     } else {
                   1100:         if ($type eq 'thumbnail') {
                   1101:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1102:         } else { 
                   1103:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1104:         }
1.617     albertel 1105:     }
                   1106: }
                   1107: 
1.263     www      1108: # -------------------------------------------------------------------- New chat
                   1109: 
                   1110: sub chatsend {
1.724     raeburn  1111:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1112:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1113:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1114:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1115:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1116: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1117: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1118: }
                   1119: 
                   1120: # ------------------------------------------ Find current version of a resource
                   1121: 
                   1122: sub getversion {
                   1123:     my $fname=&clutter(shift);
                   1124:     unless ($fname=~/^\/res\//) { return -1; }
                   1125:     return &currentversion(&filelocation('',$fname));
                   1126: }
                   1127: 
                   1128: sub currentversion {
                   1129:     my $fname=shift;
1.599     albertel 1130:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1131:     if (defined($cached)) { return $result; }
1.292     www      1132:     my $author=$fname;
                   1133:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1134:     my ($udom,$uname)=split(/\//,$author);
                   1135:     my $home=homeserver($uname,$udom);
                   1136:     if ($home eq 'no_host') { 
                   1137:         return -1; 
                   1138:     }
                   1139:     my $answer=reply("currentversion:$fname",$home);
                   1140:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1141: 	return -1;
                   1142:     }
1.599     albertel 1143:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1144: }
                   1145: 
1.1       albertel 1146: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1147: 
1.1       albertel 1148: sub subscribe {
                   1149:     my $fname=shift;
1.761     raeburn  1150:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1151:     $fname=~s/[\n\r]//g;
1.1       albertel 1152:     my $author=$fname;
                   1153:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1154:     my ($udom,$uname)=split(/\//,$author);
                   1155:     my $home=homeserver($uname,$udom);
1.335     albertel 1156:     if ($home eq 'no_host') {
                   1157:         return 'not_found';
1.1       albertel 1158:     }
                   1159:     my $answer=reply("sub:$fname",$home);
1.64      www      1160:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1161: 	$answer.=' by '.$home;
                   1162:     }
1.1       albertel 1163:     return $answer;
                   1164: }
                   1165:     
1.8       www      1166: # -------------------------------------------------------------- Replicate file
                   1167: 
                   1168: sub repcopy {
                   1169:     my $filename=shift;
1.23      www      1170:     $filename=~s/\/+/\//g;
1.607     raeburn  1171:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1172:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1173:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1174: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1175: 	return &repcopy_userfile($filename);
                   1176:     }
1.532     albertel 1177:     $filename=~s/[\n\r]//g;
1.8       www      1178:     my $transname="$filename.in.transfer";
1.607     raeburn  1179:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1180:     my $remoteurl=subscribe($filename);
1.64      www      1181:     if ($remoteurl =~ /^con_lost by/) {
                   1182: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1183:            return 'unavailable';
1.8       www      1184:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1185: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1186: 	   return 'not_found';
1.64      www      1187:     } elsif ($remoteurl =~ /^rejected by/) {
                   1188: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1189:            return 'forbidden';
1.20      www      1190:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1191:            return 'ok';
1.8       www      1192:     } else {
1.290     www      1193:         my $author=$filename;
                   1194:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1195:         my ($udom,$uname)=split(/\//,$author);
                   1196:         my $home=homeserver($uname,$udom);
                   1197:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1198:            my @parts=split(/\//,$filename);
                   1199:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1200:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1201:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1202: 	       return 'bad_request';
1.8       www      1203:            }
                   1204:            my $count;
                   1205:            for ($count=5;$count<$#parts;$count++) {
                   1206:                $path.="/$parts[$count]";
                   1207:                if ((-e $path)!=1) {
                   1208: 		   mkdir($path,0777);
                   1209:                }
                   1210:            }
                   1211:            my $ua=new LWP::UserAgent;
                   1212:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1213:            my $response=$ua->request($request,$transname);
                   1214:            if ($response->is_error()) {
                   1215: 	       unlink($transname);
                   1216:                my $message=$response->status_line;
1.672     albertel 1217:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1218:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1219:                return 'unavailable';
1.8       www      1220:            } else {
1.16      www      1221: 	       if ($remoteurl!~/\.meta$/) {
                   1222:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1223:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1224:                   if ($mresponse->is_error()) {
                   1225: 		      unlink($filename.'.meta');
                   1226:                       &logthis(
1.672     albertel 1227:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1228:                   }
                   1229: 	       }
1.8       www      1230:                rename($transname,$filename);
1.607     raeburn  1231:                return 'ok';
1.8       www      1232:            }
1.290     www      1233:        }
1.8       www      1234:     }
1.330     www      1235: }
                   1236: 
                   1237: # ------------------------------------------------ Get server side include body
                   1238: sub ssi_body {
1.381     albertel 1239:     my ($filelink,%form)=@_;
1.606     matthew  1240:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1241:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1242:     }
1.330     www      1243:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1244:                                      &ssi($filelink,%form));
1.778     albertel 1245:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1246:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1247:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1248:     return $output;
1.8       www      1249: }
                   1250: 
1.15      www      1251: # --------------------------------------------------------- Server Side Include
                   1252: 
1.782     albertel 1253: sub absolute_url {
                   1254:     my ($host_name) = @_;
                   1255:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1256:     if ($host_name eq '') {
                   1257: 	$host_name = $ENV{'SERVER_NAME'};
                   1258:     }
                   1259:     return $protocol.$host_name;
                   1260: }
                   1261: 
1.15      www      1262: sub ssi {
                   1263: 
1.23      www      1264:     my ($fn,%form)=@_;
1.15      www      1265: 
                   1266:     my $ua=new LWP::UserAgent;
1.23      www      1267:     
                   1268:     my $request;
1.711     albertel 1269: 
                   1270:     $form{'no_update_last_known'}=1;
                   1271: 
1.23      www      1272:     if (%form) {
1.782     albertel 1273:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1274:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1275:     } else {
1.782     albertel 1276:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1277:     }
                   1278: 
1.15      www      1279:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1280:     my $response=$ua->request($request);
                   1281: 
1.324     www      1282:     return $response->content;
                   1283: }
                   1284: 
                   1285: sub externalssi {
                   1286:     my ($url)=@_;
                   1287:     my $ua=new LWP::UserAgent;
                   1288:     my $request=new HTTP::Request('GET',$url);
                   1289:     my $response=$ua->request($request);
1.15      www      1290:     return $response->content;
                   1291: }
1.254     www      1292: 
1.492     albertel 1293: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1294: 
                   1295: sub allowuploaded {
                   1296:     my ($srcurl,$url)=@_;
                   1297:     $url=&clutter(&declutter($url));
                   1298:     my $dir=$url;
                   1299:     $dir=~s/\/[^\/]+$//;
                   1300:     my %httpref=();
                   1301:     my $httpurl=&hreflocation('',$url);
                   1302:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1303:     &Apache::lonnet::appenv(%httpref);
1.254     www      1304: }
1.477     raeburn  1305: 
1.478     albertel 1306: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1307: # input: action, courseID, current domain, intended
1.637     raeburn  1308: #        path to file, source of file, instruction to parse file for objects,
                   1309: #        ref to hash for embedded objects,
                   1310: #        ref to hash for codebase of java objects.
                   1311: #
1.485     raeburn  1312: # output: url to file (if action was uploaddoc), 
                   1313: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1314: #
1.478     albertel 1315: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1316: # course.
1.477     raeburn  1317: #
1.478     albertel 1318: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1319: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1320: #          course's home server.
1.477     raeburn  1321: #
1.478     albertel 1322: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1323: #          be copied from $source (current location) to 
                   1324: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1325: #         and will then be copied to
                   1326: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1327: #         course's home server.
1.485     raeburn  1328: #
1.481     raeburn  1329: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1330: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1331: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1332: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1333: #         in course's home server.
1.637     raeburn  1334: #
1.477     raeburn  1335: 
                   1336: sub process_coursefile {
1.638     albertel 1337:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1338:     my $fetchresult;
1.638     albertel 1339:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1340:     if ($action eq 'propagate') {
1.638     albertel 1341:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1342: 			     $home);
1.481     raeburn  1343:     } else {
1.477     raeburn  1344:         my $fpath = '';
                   1345:         my $fname = $file;
1.478     albertel 1346:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1347:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1348:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1349:         if ($action eq 'copy') {
                   1350:             if ($source eq '') {
                   1351:                 $fetchresult = 'no source file';
                   1352:                 return $fetchresult;
                   1353:             } else {
                   1354:                 my $destination = $filepath.'/'.$fname;
                   1355:                 rename($source,$destination);
                   1356:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1357:                                  $home);
1.481     raeburn  1358:             }
                   1359:         } elsif ($action eq 'uploaddoc') {
                   1360:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1361:             print $fh $env{'form.'.$source};
1.481     raeburn  1362:             close($fh);
1.637     raeburn  1363:             if ($parser eq 'parse') {
                   1364:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1365:                 unless ($parse_result eq 'ok') {
                   1366:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1367:                 }
                   1368:             }
1.477     raeburn  1369:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1370:                                  $home);
1.481     raeburn  1371:             if ($fetchresult eq 'ok') {
                   1372:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1373:             } else {
                   1374:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1375:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1376:                 return '/adm/notfound.html';
                   1377:             }
1.477     raeburn  1378:         }
                   1379:     }
1.485     raeburn  1380:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1381:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1382:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1383:     }
                   1384:     return $fetchresult;
                   1385: }
                   1386: 
1.637     raeburn  1387: sub build_filepath {
                   1388:     my ($fpath) = @_;
                   1389:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1390:     unless ($fpath eq '') {
                   1391:         my @parts=split('/',$fpath);
                   1392:         foreach my $part (@parts) {
                   1393:             $filepath.= '/'.$part;
                   1394:             if ((-e $filepath)!=1) {
                   1395:                 mkdir($filepath,0777);
                   1396:             }
                   1397:         }
                   1398:     }
                   1399:     return $filepath;
                   1400: }
                   1401: 
                   1402: sub store_edited_file {
1.638     albertel 1403:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1404:     my $file = $primary_url;
                   1405:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1406:     my $fpath = '';
                   1407:     my $fname = $file;
                   1408:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1409:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1410:     my $filepath = &build_filepath($fpath);
                   1411:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1412:     print $fh $content;
                   1413:     close($fh);
1.638     albertel 1414:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1415:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1416: 			  $home);
1.637     raeburn  1417:     if ($$fetchresult eq 'ok') {
                   1418:         return '/uploaded/'.$fpath.'/'.$fname;
                   1419:     } else {
1.638     albertel 1420:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1421: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1422:         return '/adm/notfound.html';
                   1423:     }
                   1424: }
                   1425: 
1.531     albertel 1426: sub clean_filename {
                   1427:     my ($fname)=@_;
1.315     www      1428: # Replace Windows backslashes by forward slashes
1.257     www      1429:     $fname=~s/\\/\//g;
1.315     www      1430: # Get rid of everything but the actual filename
1.257     www      1431:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1432: # Replace spaces by underscores
                   1433:     $fname=~s/\s+/\_/g;
                   1434: # Replace all other weird characters by nothing
1.317     www      1435:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1436: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1437: # numbers
                   1438:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1439:     return $fname;
                   1440: }
                   1441: 
1.608     albertel 1442: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1443: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1444: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1445: #        $coursedoc - if true up to the current course
                   1446: #                     if false
                   1447: #        $subdir - directory in userfile to store the file into
                   1448: #        $parser, $allfiles, $codebase - unknown
                   1449: #
                   1450: # output: url of file in userspace, or error: <message> 
                   1451: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1452: 
                   1453: 
1.531     albertel 1454: sub userfileupload {
1.719     banghart 1455:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1456:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1457:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1458:     $fname=&clean_filename($fname);
1.315     www      1459: # See if there is anything left
1.257     www      1460:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1461:     chop($env{'form.'.$formname});
1.523     raeburn  1462:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1463:         my $now = time;
                   1464:         my $filepath = 'tmp/helprequests/'.$now;
                   1465:         my @parts=split(/\//,$filepath);
                   1466:         my $fullpath = $perlvar{'lonDaemons'};
                   1467:         for (my $i=0;$i<@parts;$i++) {
                   1468:             $fullpath .= '/'.$parts[$i];
                   1469:             if ((-e $fullpath)!=1) {
                   1470:                 mkdir($fullpath,0777);
                   1471:             }
                   1472:         }
                   1473:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1474:         print $fh $env{'form.'.$formname};
1.523     raeburn  1475:         close($fh);
1.741     raeburn  1476:         return $fullpath.'/'.$fname;
                   1477:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1478:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1479:                        '_'.$env{'user.domain'}.'/pending';
                   1480:         my @parts=split(/\//,$filepath);
                   1481:         my $fullpath = $perlvar{'lonDaemons'};
                   1482:         for (my $i=0;$i<@parts;$i++) {
                   1483:             $fullpath .= '/'.$parts[$i];
                   1484:             if ((-e $fullpath)!=1) {
                   1485:                 mkdir($fullpath,0777);
                   1486:             }
                   1487:         }
                   1488:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1489:         print $fh $env{'form.'.$formname};
                   1490:         close($fh);
                   1491:         return $fullpath.'/'.$fname;
1.523     raeburn  1492:     }
1.719     banghart 1493:     
1.258     www      1494: # Create the directory if not present
1.493     albertel 1495:     $fname="$subdir/$fname";
1.259     www      1496:     if ($coursedoc) {
1.638     albertel 1497: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1498: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1499:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1500:             return &finishuserfileupload($docuname,$docudom,
                   1501: 					 $formname,$fname,$parser,$allfiles,
                   1502: 					 $codebase);
1.481     raeburn  1503:         } else {
1.620     albertel 1504:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1505:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1506: 				       $fname,$formname,$parser,
                   1507: 				       $allfiles,$codebase);
1.481     raeburn  1508:         }
1.719     banghart 1509:     } elsif (defined($destuname)) {
                   1510:         my $docuname=$destuname;
                   1511:         my $docudom=$destudom;
                   1512: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1513: 				     $fname,$parser,$allfiles,$codebase);
                   1514:         
1.259     www      1515:     } else {
1.638     albertel 1516:         my $docuname=$env{'user.name'};
                   1517:         my $docudom=$env{'user.domain'};
1.714     raeburn  1518:         if (exists($env{'form.group'})) {
                   1519:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1520:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1521:         }
1.638     albertel 1522: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1523: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1524:     }
1.271     www      1525: }
                   1526: 
                   1527: sub finishuserfileupload {
1.638     albertel 1528:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1529:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1530:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1531:     my ($fnamepath,$file);
                   1532:     $file=$fname;
                   1533:     if ($fname=~m|/|) {
                   1534:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1535: 	$path.=$fnamepath.'/';
                   1536:     }
1.259     www      1537:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1538:     my $count;
                   1539:     for ($count=4;$count<=$#parts;$count++) {
                   1540:         $filepath.="/$parts[$count]";
                   1541:         if ((-e $filepath)!=1) {
                   1542: 	    mkdir($filepath,0777);
                   1543:         }
                   1544:     }
                   1545: # Save the file
                   1546:     {
1.701     albertel 1547: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1548: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1549: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1550: 	    return '/adm/notfound.html';
                   1551: 	}
                   1552: 	if (!print FH ($env{'form.'.$formname})) {
                   1553: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1554: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1555: 	    return '/adm/notfound.html';
                   1556: 	}
1.570     albertel 1557: 	close(FH);
1.258     www      1558:     }
1.637     raeburn  1559:     if ($parser eq 'parse') {
1.638     albertel 1560:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1561: 						   $codebase);
1.637     raeburn  1562:         unless ($parse_result eq 'ok') {
1.638     albertel 1563:             &logthis('Failed to parse '.$filepath.$file.
                   1564: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1565:         }
                   1566:     }
1.259     www      1567: # Notify homeserver to grep it
                   1568: #
1.638     albertel 1569:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1570:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1571:     if ($fetchresult eq 'ok') {
1.259     www      1572: #
1.258     www      1573: # Return the URL to it
1.494     albertel 1574:         return '/uploaded/'.$path.$file;
1.263     www      1575:     } else {
1.494     albertel 1576:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1577: 		 ': '.$fetchresult);
1.263     www      1578:         return '/adm/notfound.html';
                   1579:     }    
1.493     albertel 1580: }
                   1581: 
1.637     raeburn  1582: sub extract_embedded_items {
1.648     raeburn  1583:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1584:     my @state = ();
                   1585:     my %javafiles = (
                   1586:                       codebase => '',
                   1587:                       code => '',
                   1588:                       archive => ''
                   1589:                     );
                   1590:     my %mediafiles = (
                   1591:                       src => '',
                   1592:                       movie => '',
                   1593:                      );
1.648     raeburn  1594:     my $p;
                   1595:     if ($content) {
                   1596:         $p = HTML::LCParser->new($content);
                   1597:     } else {
                   1598:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1599:     }
1.641     albertel 1600:     while (my $t=$p->get_token()) {
1.640     albertel 1601: 	if ($t->[0] eq 'S') {
                   1602: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1603: 	    push (@state, $tagname);
1.648     raeburn  1604:             if (lc($tagname) eq 'allow') {
                   1605:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1606:             }
1.640     albertel 1607: 	    if (lc($tagname) eq 'img') {
                   1608: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1609: 	    }
1.645     raeburn  1610:             if (lc($tagname) eq 'script') {
                   1611:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1612:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1613:                 } else {
                   1614:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1615:                 }
                   1616:             }
                   1617:             if (lc($tagname) eq 'link') {
                   1618:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1619:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1620:                 }
                   1621:             }
1.640     albertel 1622: 	    if (lc($tagname) eq 'object' ||
                   1623: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1624: 		foreach my $item (keys(%javafiles)) {
                   1625: 		    $javafiles{$item} = '';
                   1626: 		}
                   1627: 	    }
                   1628: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1629: 		my $name = lc($attr->{'name'});
                   1630: 		foreach my $item (keys(%javafiles)) {
                   1631: 		    if ($name eq $item) {
                   1632: 			$javafiles{$item} = $attr->{'value'};
                   1633: 			last;
                   1634: 		    }
                   1635: 		}
                   1636: 		foreach my $item (keys(%mediafiles)) {
                   1637: 		    if ($name eq $item) {
                   1638: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1639: 			last;
                   1640: 		    }
                   1641: 		}
                   1642: 	    }
                   1643: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1644: 		foreach my $item (keys(%javafiles)) {
                   1645: 		    if ($attr->{$item}) {
                   1646: 			$javafiles{$item} = $attr->{$item};
                   1647: 			last;
                   1648: 		    }
                   1649: 		}
                   1650: 		foreach my $item (keys(%mediafiles)) {
                   1651: 		    if ($attr->{$item}) {
                   1652: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1653: 			last;
                   1654: 		    }
                   1655: 		}
                   1656: 	    }
                   1657: 	} elsif ($t->[0] eq 'E') {
                   1658: 	    my ($tagname) = ($t->[1]);
                   1659: 	    if ($javafiles{'codebase'} ne '') {
                   1660: 		$javafiles{'codebase'} .= '/';
                   1661: 	    }  
                   1662: 	    if (lc($tagname) eq 'applet' ||
                   1663: 		lc($tagname) eq 'object' ||
                   1664: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1665: 		) {
                   1666: 		foreach my $item (keys(%javafiles)) {
                   1667: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1668: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1669: 			&add_filetype($allfiles,$file,$item);
                   1670: 		    }
                   1671: 		}
                   1672: 	    } 
                   1673: 	    pop @state;
                   1674: 	}
                   1675:     }
1.637     raeburn  1676:     return 'ok';
                   1677: }
                   1678: 
1.639     albertel 1679: sub add_filetype {
                   1680:     my ($allfiles,$file,$type)=@_;
                   1681:     if (exists($allfiles->{$file})) {
                   1682: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1683: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1684: 	}
                   1685:     } else {
                   1686: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1687:     }
                   1688: }
                   1689: 
1.493     albertel 1690: sub removeuploadedurl {
                   1691:     my ($url)=@_;
                   1692:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1693:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1694: }
                   1695: 
                   1696: sub removeuserfile {
                   1697:     my ($docuname,$docudom,$fname)=@_;
                   1698:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1699:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1700:     if ($result eq 'ok') {
                   1701:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1702:             my $metafile = $fname.'.meta';
                   1703:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.821   ! raeburn  1704:             my ($group,$file);
        !          1705:             if ($fname =~ /^groups\/(\w+)\/portfolio(\/.+)$/) {
        !          1706:                 $group = $1;
        !          1707:                 $file = $2;
        !          1708:             } elsif ($fname =~ /^portfolio(\/.+)$/) {
        !          1709:                 $file = $1;
        !          1710:             }
        !          1711:             my $sqlresult = 
        !          1712:                 &update_portfolio_table($docuname,$docudom,$group.$file,
        !          1713:                                         'portfolio_metadata',$group,
        !          1714:                                         'delete');
1.798     raeburn  1715:         }
                   1716:     }
                   1717:     return $result;
1.257     www      1718: }
1.15      www      1719: 
1.530     albertel 1720: sub mkdiruserfile {
                   1721:     my ($docuname,$docudom,$dir)=@_;
                   1722:     my $home=&homeserver($docuname,$docudom);
                   1723:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1724: }
                   1725: 
1.531     albertel 1726: sub renameuserfile {
                   1727:     my ($docuname,$docudom,$old,$new)=@_;
                   1728:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1729:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1730:                         &escape("$old").':'.&escape("$new"),$home);
                   1731:     if ($result eq 'ok') {
                   1732:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1733:             my $oldmeta = $old.'.meta';
                   1734:             my $newmeta = $new.'.meta';
                   1735:             my $metaresult = 
                   1736:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.821   ! raeburn  1737:             my ($group,$file);
        !          1738:             if ($old =~ /^groups\/(\w+)\/portfolio(\/.+)$/) {
        !          1739:                 $group = $1;
        !          1740:                 $file = $2;
        !          1741:             } elsif ($old =~ /^portfolio(\/.+)$/) {
        !          1742:                 $file = $1;
        !          1743:             }
        !          1744:             my $sqlresult = 
        !          1745:                 &update_portfolio_table($docuname,$docudom,$group.$file,
        !          1746:                                         'portfolio_metadata',$group,
        !          1747:                                         'delete');
1.798     raeburn  1748:         }
                   1749:     }
                   1750:     return $result;
1.531     albertel 1751: }
                   1752: 
1.14      www      1753: # ------------------------------------------------------------------------- Log
                   1754: 
                   1755: sub log {
                   1756:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1757:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1758: }
                   1759: 
                   1760: # ------------------------------------------------------------------ Course Log
1.352     www      1761: #
                   1762: # This routine flushes several buffers of non-mission-critical nature
                   1763: #
1.157     www      1764: 
                   1765: sub flushcourselogs {
1.352     www      1766:     &logthis('Flushing log buffers');
                   1767: #
                   1768: # course logs
                   1769: # This is a log of all transactions in a course, which can be used
                   1770: # for data mining purposes
                   1771: #
                   1772: # It also collects the courseid database, which lists last transaction
                   1773: # times and course titles for all courseids
                   1774: #
                   1775:     my %courseidbuffer=();
1.800     albertel 1776:     foreach my $crsid (keys %courselogs) {
1.352     www      1777:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1778: 		          &escape($courselogs{$crsid}),
                   1779: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1780: 	    delete $courselogs{$crsid};
                   1781:         } else {
                   1782:             &logthis('Failed to flush log buffer for '.$crsid);
                   1783:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1784:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1785:                         " exceeded maximum size, deleting.</font>");
                   1786:                delete $courselogs{$crsid};
                   1787:             }
1.352     www      1788:         }
                   1789:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1790:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1791: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1792:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1793:         } else {
                   1794:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1795: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1796:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1797:         }
1.191     harris41 1798:     }
1.352     www      1799: #
                   1800: # Write course id database (reverse lookup) to homeserver of courses 
                   1801: # Is used in pickcourse
                   1802: #
1.800     albertel 1803:     foreach my $crsid (keys(%courseidbuffer)) {
                   1804:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1805:     }
                   1806: #
                   1807: # File accesses
                   1808: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1809: #
1.449     matthew  1810:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1811:         if ($entry =~ /___count$/) {
                   1812:             my ($dom,$name);
1.807     albertel 1813:             ($dom,$name,undef)=
1.811     albertel 1814: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1815:             if (! defined($dom) || $dom eq '' || 
                   1816:                 ! defined($name) || $name eq '') {
1.620     albertel 1817:                 my $cid = $env{'request.course.id'};
                   1818:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1819:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1820:             }
1.450     matthew  1821:             my $value = $accesshash{$entry};
                   1822:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1823:             my %temphash=($url => $value);
1.449     matthew  1824:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1825:             if ($result eq 'ok') {
                   1826:                 delete $accesshash{$entry};
                   1827:             } elsif ($result eq 'unknown_cmd') {
                   1828:                 # Target server has old code running on it.
1.450     matthew  1829:                 my %temphash=($entry => $value);
1.449     matthew  1830:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1831:                     delete $accesshash{$entry};
                   1832:                 }
                   1833:             }
                   1834:         } else {
1.811     albertel 1835:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1836:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1837:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1838:                 delete $accesshash{$entry};
                   1839:             }
1.185     www      1840:         }
1.191     harris41 1841:     }
1.352     www      1842: #
                   1843: # Roles
                   1844: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1845: #
1.800     albertel 1846:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1847:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1848: 	    split(/\:/,$entry);
                   1849:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1850:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1851:                 $rudom,$runame) eq 'ok') {
                   1852: 	    delete $userrolehash{$entry};
                   1853:         }
                   1854:     }
1.662     raeburn  1855: #
                   1856: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1857: #
                   1858:     my %domrolebuffer = ();
                   1859:     foreach my $entry (keys %domainrolehash) {
                   1860:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1861:         if ($domrolebuffer{$rudom}) {
                   1862:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1863:                       '='.&escape($domainrolehash{$entry});
                   1864:         } else {
                   1865:             $domrolebuffer{$rudom}.=&escape($entry).
                   1866:                       '='.&escape($domainrolehash{$entry});
                   1867:         }
                   1868:         delete $domainrolehash{$entry};
                   1869:     }
                   1870:     foreach my $dom (keys(%domrolebuffer)) {
                   1871:         foreach my $tryserver (keys %libserv) {
                   1872:             if ($hostdom{$tryserver} eq $dom) {
                   1873:                 unless (&reply('domroleput:'.$dom.':'.
                   1874:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1875:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1876:                 }
                   1877:             }
                   1878:         }
                   1879:     }
1.186     www      1880:     $dumpcount++;
1.157     www      1881: }
                   1882: 
                   1883: sub courselog {
                   1884:     my $what=shift;
1.158     www      1885:     $what=time.':'.$what;
1.620     albertel 1886:     unless ($env{'request.course.id'}) { return ''; }
                   1887:     $coursedombuf{$env{'request.course.id'}}=
                   1888:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1889:     $coursenumbuf{$env{'request.course.id'}}=
                   1890:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1891:     $coursehombuf{$env{'request.course.id'}}=
                   1892:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1893:     $coursedescrbuf{$env{'request.course.id'}}=
                   1894:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1895:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1896:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1897:     $courseownerbuf{$env{'request.course.id'}}=
                   1898:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1899:     $coursetypebuf{$env{'request.course.id'}}=
                   1900:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1901:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1902: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1903:     } else {
1.620     albertel 1904: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1905:     }
1.620     albertel 1906:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1907: 	&flushcourselogs();
                   1908:     }
1.158     www      1909: }
                   1910: 
                   1911: sub courseacclog {
                   1912:     my $fnsymb=shift;
1.620     albertel 1913:     unless ($env{'request.course.id'}) { return ''; }
                   1914:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1915:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1916:         $what.=':POST';
1.583     matthew  1917:         # FIXME: Probably ought to escape things....
1.800     albertel 1918: 	foreach my $key (keys(%env)) {
                   1919:             if ($key=~/^form\.(.*)/) {
                   1920: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1921:             }
1.191     harris41 1922:         }
1.583     matthew  1923:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1924:         # FIXME: We should not be depending on a form parameter that someone
                   1925:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1926:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1927:             $what.= ':POST';
                   1928:             # FIXME: Probably ought to escape things....
                   1929:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1930:                                  'crsdiscuss') {
1.620     albertel 1931:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1932:             }
                   1933:         }
1.158     www      1934:     }
                   1935:     &courselog($what);
1.149     www      1936: }
                   1937: 
1.185     www      1938: sub countacc {
                   1939:     my $url=&declutter(shift);
1.458     matthew  1940:     return if (! defined($url) || $url eq '');
1.620     albertel 1941:     unless ($env{'request.course.id'}) { return ''; }
                   1942:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1943:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1944:     $accesshash{$key}++;
1.185     www      1945: }
1.349     www      1946: 
1.361     www      1947: sub linklog {
                   1948:     my ($from,$to)=@_;
                   1949:     $from=&declutter($from);
                   1950:     $to=&declutter($to);
                   1951:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1952:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1953: }
                   1954:   
1.349     www      1955: sub userrolelog {
                   1956:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1957:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1958:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1959:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1960:         ($trole=~/^ta/)) {
1.350     www      1961:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1962:        $userrolehash
                   1963:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1964:                     =$tend.':'.$tstart;
1.662     raeburn  1965:     }
                   1966:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1967:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1968:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1969:         ($trole=~/^sc/)) {
                   1970:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1971:        $domainrolehash
                   1972:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1973:                     = $tend.':'.$tstart;
                   1974:     }
1.351     www      1975: }
                   1976: 
                   1977: sub get_course_adv_roles {
                   1978:     my $cid=shift;
1.620     albertel 1979:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1980:     my %coursehash=&coursedescription($cid);
1.470     www      1981:     my %nothide=();
1.800     albertel 1982:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1983: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      1984:     }
1.351     www      1985:     my %returnhash=();
                   1986:     my %dumphash=
                   1987:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1988:     my $now=time;
1.800     albertel 1989:     foreach my $entry (keys %dumphash) {
                   1990: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      1991:         if (($tstart) && ($tstart<0)) { next; }
                   1992:         if (($tend) && ($tend<$now)) { next; }
                   1993:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1994:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 1995: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1996: 	if ((&privileged($username,$domain)) && 
                   1997: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1998: 	if ($role eq 'cr') { next; }
1.351     www      1999:         my $key=&plaintext($role);
                   2000:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2001:         if ($returnhash{$key}) {
                   2002: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2003:         } else {
                   2004:             $returnhash{$key}=$username.':'.$domain;
                   2005:         }
1.400     www      2006:      }
                   2007:     return %returnhash;
                   2008: }
                   2009: 
                   2010: sub get_my_roles {
                   2011:     my ($uname,$udom)=@_;
1.620     albertel 2012:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2013:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2014:     my %dumphash=
                   2015:             &dump('nohist_userroles',$udom,$uname);
                   2016:     my %returnhash=();
                   2017:     my $now=time;
1.800     albertel 2018:     foreach my $entry (keys(%dumphash)) {
                   2019: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2020:         if (($tstart) && ($tstart<0)) { next; }
                   2021:         if (($tend) && ($tend<$now)) { next; }
                   2022:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2023:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2024: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2025:      }
                   2026:     return %returnhash;
1.399     www      2027: }
                   2028: 
                   2029: # ----------------------------------------------------- Frontpage Announcements
                   2030: #
                   2031: #
                   2032: 
                   2033: sub postannounce {
                   2034:     my ($server,$text)=@_;
                   2035:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2036:     unless ($text=~/\w/) { $text=''; }
                   2037:     return &reply('setannounce:'.&escape($text),$server);
                   2038: }
                   2039: 
                   2040: sub getannounce {
1.448     albertel 2041: 
                   2042:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2043: 	my $announcement='';
1.800     albertel 2044: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2045: 	close($fh);
1.399     www      2046: 	if ($announcement=~/\w/) { 
                   2047: 	    return 
                   2048:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2049:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2050: 	} else {
                   2051: 	    return '';
                   2052: 	}
                   2053:     } else {
                   2054: 	return '';
                   2055:     }
1.351     www      2056: }
1.353     www      2057: 
                   2058: # ---------------------------------------------------------- Course ID routines
                   2059: # Deal with domain's nohist_courseid.db files
                   2060: #
                   2061: 
                   2062: sub courseidput {
                   2063:     my ($domain,$what,$coursehome)=@_;
                   2064:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2065: }
                   2066: 
                   2067: sub courseiddump {
1.791     raeburn  2068:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2069:     my %returnhash=();
1.355     www      2070:     unless ($domfilter) { $domfilter=''; }
1.353     www      2071:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2072:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2073: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2074: 	        foreach my $line (
1.506     raeburn  2075:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2076: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2077:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2078:                                $tryserver))) {
1.800     albertel 2079: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2080:                     if (($key) && ($value)) {
1.516     raeburn  2081: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2082:                     }
1.353     www      2083:                 }
                   2084:             }
                   2085:         }
                   2086:     }
                   2087:     return %returnhash;
                   2088: }
                   2089: 
1.658     raeburn  2090: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2091: 
                   2092: sub dcmailput {
1.685     raeburn  2093:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2094:     my $status = &Apache::lonnet::critical(
1.740     www      2095:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2096:        &escape($message),$server);
1.662     raeburn  2097:     return $status;
                   2098: }
                   2099: 
1.658     raeburn  2100: sub dcmaildump {
                   2101:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2102:     my %returnhash=();
                   2103:     if (exists($domain_primary{$dom})) {
                   2104:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2105:                                                          &escape($enddate).':';
                   2106: 	my @esc_senders=map { &escape($_)} @$senders;
                   2107: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2108: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2109:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2110:             if (($key) && ($value)) {
                   2111:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2112:             }
                   2113:         }
                   2114:     }
                   2115:     return %returnhash;
                   2116: }
1.662     raeburn  2117: # ---------------------------------------------------------- Domain roles
                   2118: 
                   2119: sub get_domain_roles {
                   2120:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2121:     if (undef($startdate) || $startdate eq '') {
                   2122:         $startdate = '.';
                   2123:     }
                   2124:     if (undef($enddate) || $enddate eq '') {
                   2125:         $enddate = '.';
                   2126:     }
                   2127:     my $rolelist = join(':',@{$roles});
                   2128:     my %personnel = ();
                   2129:     foreach my $tryserver (keys(%libserv)) {
                   2130:         if ($hostdom{$tryserver} eq $dom) {
                   2131:             %{$personnel{$tryserver}}=();
1.800     albertel 2132:             foreach my $line (
1.662     raeburn  2133:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2134:                    &escape($startdate).':'.&escape($enddate).':'.
                   2135:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2136:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2137:                 if (($key) && ($value)) {
                   2138:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2139:                 }
                   2140:             }
                   2141:         }
                   2142:     }
                   2143:     return %personnel;
                   2144: }
1.658     raeburn  2145: 
1.149     www      2146: # ----------------------------------------------------------- Check out an item
                   2147: 
1.504     albertel 2148: sub get_first_access {
                   2149:     my ($type,$argsymb)=@_;
1.790     albertel 2150:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2151:     if ($argsymb) { $symb=$argsymb; }
                   2152:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2153:     if ($type eq 'map') {
                   2154: 	$res=&symbread($map);
                   2155:     } else {
                   2156: 	$res=$symb;
                   2157:     }
                   2158:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2159:     return $times{"$courseid\0$res"};
1.504     albertel 2160: }
                   2161: 
                   2162: sub set_first_access {
                   2163:     my ($type)=@_;
1.790     albertel 2164:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2165:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2166:     if ($type eq 'map') {
                   2167: 	$res=&symbread($map);
                   2168:     } else {
                   2169: 	$res=$symb;
                   2170:     }
                   2171:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2172:     if (!$firstaccess) {
1.588     albertel 2173: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2174:     }
                   2175:     return 'already_set';
1.504     albertel 2176: }
                   2177: 
1.149     www      2178: sub checkout {
                   2179:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2180:     my $now=time;
                   2181:     my $lonhost=$perlvar{'lonHostID'};
                   2182:     my $infostr=&escape(
1.234     www      2183:                  'CHECKOUTTOKEN&'.
1.149     www      2184:                  $tuname.'&'.
                   2185:                  $tudom.'&'.
                   2186:                  $tcrsid.'&'.
                   2187:                  $symb.'&'.
                   2188: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2189:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2190:     if ($token=~/^error\:/) { 
1.672     albertel 2191:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2192:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2193:                  "</font>");
                   2194:         return ''; 
                   2195:     }
                   2196: 
1.149     www      2197:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2198:     $token=~tr/a-z/A-Z/;
                   2199: 
1.153     www      2200:     my %infohash=('resource.0.outtoken' => $token,
                   2201:                   'resource.0.checkouttime' => $now,
                   2202:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2203: 
                   2204:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2205:        return '';
1.151     www      2206:     } else {
1.672     albertel 2207:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2208:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2209:                  "</font>");
1.149     www      2210:     }    
                   2211: 
                   2212:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2213:                          &escape('Checkout '.$infostr.' - '.
                   2214:                                                  $token)) ne 'ok') {
                   2215: 	return '';
1.151     www      2216:     } else {
1.672     albertel 2217:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2218:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2219:                  "</font>");
1.149     www      2220:     }
1.151     www      2221:     return $token;
1.149     www      2222: }
                   2223: 
                   2224: # ------------------------------------------------------------ Check in an item
                   2225: 
                   2226: sub checkin {
                   2227:     my $token=shift;
1.150     www      2228:     my $now=time;
                   2229:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2230:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2231:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2232:     $dtoken=~s/\W/\_/g;
1.234     www      2233:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2234:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2235: 
1.154     www      2236:     unless (($tuname) && ($tudom)) {
                   2237:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2238:         return '';
                   2239:     }
                   2240:     
                   2241:     unless (&allowed('mgr',$tcrsid)) {
                   2242:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2243:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2244:         return '';
                   2245:     }
                   2246: 
1.153     www      2247:     my %infohash=('resource.0.intoken' => $token,
                   2248:                   'resource.0.checkintime' => $now,
                   2249:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2250: 
                   2251:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2252:        return '';
                   2253:     }    
                   2254: 
                   2255:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2256:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2257: 	return '';
                   2258:     }
                   2259: 
                   2260:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2261: }
                   2262: 
                   2263: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2264: 
                   2265: sub expirespread {
                   2266:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2267:     my $cid=$env{'request.course.id'}; 
1.110     www      2268:     if ($cid) {
                   2269:        my $now=time;
                   2270:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2271:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2272:                             $env{'course.'.$cid.'.num'}.
1.110     www      2273: 	        	    ':nohist_expirationdates:'.
                   2274:                             &escape($key).'='.$now,
1.620     albertel 2275:                             $env{'course.'.$cid.'.home'})
1.110     www      2276:     }
                   2277:     return 'ok';
1.14      www      2278: }
                   2279: 
1.109     www      2280: # ----------------------------------------------------- Devalidate Spreadsheets
                   2281: 
                   2282: sub devalidate {
1.325     www      2283:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2284:     my $cid=$env{'request.course.id'}; 
1.109     www      2285:     if ($cid) {
1.391     matthew  2286:         # delete the stored spreadsheets for
                   2287:         # - the student level sheet of this user in course's homespace
                   2288:         # - the assessment level sheet for this resource 
                   2289:         #   for this user in user's homespace
1.553     albertel 2290: 	# - current conditional state info
1.325     www      2291: 	my $key=$uname.':'.$udom.':';
1.109     www      2292:         my $status=
1.299     matthew  2293: 	    &del('nohist_calculatedsheets',
1.391     matthew  2294: 		 [$key.'studentcalc:'],
1.620     albertel 2295: 		 $env{'course.'.$cid.'.domain'},
                   2296: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2297: 		.' '.
                   2298: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2299: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2300:         unless ($status eq 'ok ok') {
                   2301:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2302:                     $uname.' at '.$udom.' for '.
1.109     www      2303: 		    $symb.': '.$status);
1.133     albertel 2304:         }
1.553     albertel 2305: 	&delenv('user.state.'.$cid);
1.109     www      2306:     }
                   2307: }
                   2308: 
1.265     albertel 2309: sub get_scalar {
                   2310:     my ($string,$end) = @_;
                   2311:     my $value;
                   2312:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2313: 	$value = $1;
                   2314:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2315: 	$value = $1;
                   2316:     }
                   2317:     return &unescape($value);
                   2318: }
                   2319: 
                   2320: sub array2str {
                   2321:   my (@array) = @_;
                   2322:   my $result=&arrayref2str(\@array);
                   2323:   $result=~s/^__ARRAY_REF__//;
                   2324:   $result=~s/__END_ARRAY_REF__$//;
                   2325:   return $result;
                   2326: }
                   2327: 
1.204     albertel 2328: sub arrayref2str {
                   2329:   my ($arrayref) = @_;
1.265     albertel 2330:   my $result='__ARRAY_REF__';
1.204     albertel 2331:   foreach my $elem (@$arrayref) {
1.265     albertel 2332:     if(ref($elem) eq 'ARRAY') {
                   2333:       $result.=&arrayref2str($elem).'&';
                   2334:     } elsif(ref($elem) eq 'HASH') {
                   2335:       $result.=&hashref2str($elem).'&';
                   2336:     } elsif(ref($elem)) {
                   2337:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2338:     } else {
                   2339:       $result.=&escape($elem).'&';
                   2340:     }
                   2341:   }
                   2342:   $result=~s/\&$//;
1.265     albertel 2343:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2344:   return $result;
                   2345: }
                   2346: 
1.168     albertel 2347: sub hash2str {
1.204     albertel 2348:   my (%hash) = @_;
                   2349:   my $result=&hashref2str(\%hash);
1.265     albertel 2350:   $result=~s/^__HASH_REF__//;
                   2351:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2352:   return $result;
                   2353: }
                   2354: 
                   2355: sub hashref2str {
                   2356:   my ($hashref)=@_;
1.265     albertel 2357:   my $result='__HASH_REF__';
1.800     albertel 2358:   foreach my $key (sort(keys(%$hashref))) {
                   2359:     if (ref($key) eq 'ARRAY') {
                   2360:       $result.=&arrayref2str($key).'=';
                   2361:     } elsif (ref($key) eq 'HASH') {
                   2362:       $result.=&hashref2str($key).'=';
                   2363:     } elsif (ref($key)) {
1.265     albertel 2364:       $result.='=';
1.800     albertel 2365:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2366:     } else {
1.800     albertel 2367: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2368:     }
                   2369: 
1.800     albertel 2370:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2371:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2372:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2373:       $result.=&hashref2str($hashref->{$key}).'&';
                   2374:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2375:        $result.='&';
1.800     albertel 2376:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2377:     } else {
1.800     albertel 2378:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2379:     }
                   2380:   }
1.168     albertel 2381:   $result=~s/\&$//;
1.265     albertel 2382:   $result .= '__END_HASH_REF__';
1.168     albertel 2383:   return $result;
                   2384: }
                   2385: 
                   2386: sub str2hash {
1.265     albertel 2387:     my ($string)=@_;
                   2388:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2389:     return %$hash;
                   2390: }
                   2391: 
                   2392: sub str2hashref {
1.168     albertel 2393:   my ($string) = @_;
1.265     albertel 2394: 
                   2395:   my %hash;
                   2396: 
                   2397:   if($string !~ /^__HASH_REF__/) {
                   2398:       if (! ($string eq '' || !defined($string))) {
                   2399: 	  $hash{'error'}='Not hash reference';
                   2400:       }
                   2401:       return (\%hash, $string);
                   2402:   }
                   2403: 
                   2404:   $string =~ s/^__HASH_REF__//;
                   2405: 
                   2406:   while($string !~ /^__END_HASH_REF__/) {
                   2407:       #key
                   2408:       my $key='';
                   2409:       if($string =~ /^__HASH_REF__/) {
                   2410:           ($key, $string)=&str2hashref($string);
                   2411:           if(defined($key->{'error'})) {
                   2412:               $hash{'error'}='Bad data';
                   2413:               return (\%hash, $string);
                   2414:           }
                   2415:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2416:           ($key, $string)=&str2arrayref($string);
                   2417:           if($key->[0] eq 'Array reference error') {
                   2418:               $hash{'error'}='Bad data';
                   2419:               return (\%hash, $string);
                   2420:           }
                   2421:       } else {
                   2422:           $string =~ s/^(.*?)=//;
1.267     albertel 2423: 	  $key=&unescape($1);
1.265     albertel 2424:       }
                   2425:       $string =~ s/^=//;
                   2426: 
                   2427:       #value
                   2428:       my $value='';
                   2429:       if($string =~ /^__HASH_REF__/) {
                   2430:           ($value, $string)=&str2hashref($string);
                   2431:           if(defined($value->{'error'})) {
                   2432:               $hash{'error'}='Bad data';
                   2433:               return (\%hash, $string);
                   2434:           }
                   2435:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2436:           ($value, $string)=&str2arrayref($string);
                   2437:           if($value->[0] eq 'Array reference error') {
                   2438:               $hash{'error'}='Bad data';
                   2439:               return (\%hash, $string);
                   2440:           }
                   2441:       } else {
                   2442: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2443:       }
                   2444:       $string =~ s/^&//;
                   2445: 
                   2446:       $hash{$key}=$value;
1.204     albertel 2447:   }
1.265     albertel 2448: 
                   2449:   $string =~ s/^__END_HASH_REF__//;
                   2450: 
                   2451:   return (\%hash, $string);
1.204     albertel 2452: }
                   2453: 
                   2454: sub str2array {
1.265     albertel 2455:     my ($string)=@_;
                   2456:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2457:     return @$array;
                   2458: }
                   2459: 
                   2460: sub str2arrayref {
1.204     albertel 2461:   my ($string) = @_;
1.265     albertel 2462:   my @array;
                   2463: 
                   2464:   if($string !~ /^__ARRAY_REF__/) {
                   2465:       if (! ($string eq '' || !defined($string))) {
                   2466: 	  $array[0]='Array reference error';
                   2467:       }
                   2468:       return (\@array, $string);
                   2469:   }
                   2470: 
                   2471:   $string =~ s/^__ARRAY_REF__//;
                   2472: 
                   2473:   while($string !~ /^__END_ARRAY_REF__/) {
                   2474:       my $value='';
                   2475:       if($string =~ /^__HASH_REF__/) {
                   2476:           ($value, $string)=&str2hashref($string);
                   2477:           if(defined($value->{'error'})) {
                   2478:               $array[0] ='Array reference error';
                   2479:               return (\@array, $string);
                   2480:           }
                   2481:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2482:           ($value, $string)=&str2arrayref($string);
                   2483:           if($value->[0] eq 'Array reference error') {
                   2484:               $array[0] ='Array reference error';
                   2485:               return (\@array, $string);
                   2486:           }
                   2487:       } else {
                   2488: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2489:       }
                   2490:       $string =~ s/^&//;
                   2491: 
                   2492:       push(@array, $value);
1.191     harris41 2493:   }
1.265     albertel 2494: 
                   2495:   $string =~ s/^__END_ARRAY_REF__//;
                   2496: 
                   2497:   return (\@array, $string);
1.168     albertel 2498: }
                   2499: 
1.167     albertel 2500: # -------------------------------------------------------------------Temp Store
                   2501: 
1.168     albertel 2502: sub tmpreset {
                   2503:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2504:   if (!$symb) {
                   2505:     $symb=&symbread();
1.620     albertel 2506:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2507:   }
                   2508:   $symb=escape($symb);
                   2509: 
1.620     albertel 2510:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2511:   $namespace=~s/\//\_/g;
                   2512:   $namespace=~s/\W//g;
                   2513: 
1.620     albertel 2514:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2515:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2516:   if ($domain eq 'public' && $stuname eq 'public') {
                   2517:       $stuname=$ENV{'REMOTE_ADDR'};
                   2518:   }
1.168     albertel 2519:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2520:   my %hash;
                   2521:   if (tie(%hash,'GDBM_File',
                   2522: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2523: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2524:     foreach my $key (keys %hash) {
1.180     albertel 2525:       if ($key=~ /:$symb/) {
1.168     albertel 2526: 	delete($hash{$key});
                   2527:       }
                   2528:     }
                   2529:   }
                   2530: }
                   2531: 
1.167     albertel 2532: sub tmpstore {
1.168     albertel 2533:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2534: 
                   2535:   if (!$symb) {
                   2536:     $symb=&symbread();
1.620     albertel 2537:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2538:   }
                   2539:   $symb=escape($symb);
                   2540: 
                   2541:   if (!$namespace) {
                   2542:     # I don't think we would ever want to store this for a course.
                   2543:     # it seems this will only be used if we don't have a course.
1.620     albertel 2544:     #$namespace=$env{'request.course.id'};
1.168     albertel 2545:     #if (!$namespace) {
1.620     albertel 2546:       $namespace=$env{'request.state'};
1.168     albertel 2547:     #}
                   2548:   }
                   2549:   $namespace=~s/\//\_/g;
                   2550:   $namespace=~s/\W//g;
1.620     albertel 2551:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2552:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2553:   if ($domain eq 'public' && $stuname eq 'public') {
                   2554:       $stuname=$ENV{'REMOTE_ADDR'};
                   2555:   }
1.168     albertel 2556:   my $now=time;
                   2557:   my %hash;
                   2558:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2559:   if (tie(%hash,'GDBM_File',
                   2560: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2561: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2562:     $hash{"version:$symb"}++;
                   2563:     my $version=$hash{"version:$symb"};
                   2564:     my $allkeys=''; 
                   2565:     foreach my $key (keys(%$storehash)) {
                   2566:       $allkeys.=$key.':';
1.591     albertel 2567:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2568:     }
                   2569:     $hash{"$version:$symb:timestamp"}=$now;
                   2570:     $allkeys.='timestamp';
                   2571:     $hash{"$version:keys:$symb"}=$allkeys;
                   2572:     if (untie(%hash)) {
                   2573:       return 'ok';
                   2574:     } else {
                   2575:       return "error:$!";
                   2576:     }
                   2577:   } else {
                   2578:     return "error:$!";
                   2579:   }
                   2580: }
1.167     albertel 2581: 
1.168     albertel 2582: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2583: 
1.168     albertel 2584: sub tmprestore {
                   2585:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2586: 
1.168     albertel 2587:   if (!$symb) {
                   2588:     $symb=&symbread();
1.620     albertel 2589:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2590:   }
                   2591:   $symb=escape($symb);
                   2592: 
1.620     albertel 2593:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2594: 
1.620     albertel 2595:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2596:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2597:   if ($domain eq 'public' && $stuname eq 'public') {
                   2598:       $stuname=$ENV{'REMOTE_ADDR'};
                   2599:   }
1.168     albertel 2600:   my %returnhash;
                   2601:   $namespace=~s/\//\_/g;
                   2602:   $namespace=~s/\W//g;
                   2603:   my %hash;
                   2604:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2605:   if (tie(%hash,'GDBM_File',
                   2606: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2607: 	  &GDBM_READER(),0640)) {
1.168     albertel 2608:     my $version=$hash{"version:$symb"};
                   2609:     $returnhash{'version'}=$version;
                   2610:     my $scope;
                   2611:     for ($scope=1;$scope<=$version;$scope++) {
                   2612:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2613:       my @keys=split(/:/,$vkeys);
                   2614:       my $key;
                   2615:       $returnhash{"$scope:keys"}=$vkeys;
                   2616:       foreach $key (@keys) {
1.591     albertel 2617: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2618: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2619:       }
                   2620:     }
1.168     albertel 2621:     if (!(untie(%hash))) {
                   2622:       return "error:$!";
                   2623:     }
                   2624:   } else {
                   2625:     return "error:$!";
                   2626:   }
                   2627:   return %returnhash;
1.167     albertel 2628: }
                   2629: 
1.9       www      2630: # ----------------------------------------------------------------------- Store
                   2631: 
                   2632: sub store {
1.124     www      2633:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2634:     my $home='';
                   2635: 
1.168     albertel 2636:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2637: 
1.213     www      2638:     $symb=&symbclean($symb);
1.122     albertel 2639:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2640: 
1.620     albertel 2641:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2642:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2643: 
                   2644:     &devalidate($symb,$stuname,$domain);
1.109     www      2645: 
                   2646:     $symb=escape($symb);
1.187     www      2647:     if (!$namespace) { 
1.620     albertel 2648:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2649:           return ''; 
                   2650:        } 
                   2651:     }
1.620     albertel 2652:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2653: 
                   2654:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2655:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2656: 
1.12      www      2657:     my $namevalue='';
1.800     albertel 2658:     foreach my $key (keys(%$storehash)) {
                   2659:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2660:     }
1.12      www      2661:     $namevalue=~s/\&$//;
1.187     www      2662:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2663:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2664: }
                   2665: 
1.47      www      2666: # -------------------------------------------------------------- Critical Store
                   2667: 
                   2668: sub cstore {
1.124     www      2669:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2670:     my $home='';
                   2671: 
1.168     albertel 2672:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2673: 
1.213     www      2674:     $symb=&symbclean($symb);
1.122     albertel 2675:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2676: 
1.620     albertel 2677:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2678:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2679: 
                   2680:     &devalidate($symb,$stuname,$domain);
1.109     www      2681: 
                   2682:     $symb=escape($symb);
1.187     www      2683:     if (!$namespace) { 
1.620     albertel 2684:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2685:           return ''; 
                   2686:        } 
                   2687:     }
1.620     albertel 2688:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2689: 
                   2690:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2691:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2692: 
1.47      www      2693:     my $namevalue='';
1.800     albertel 2694:     foreach my $key (keys(%$storehash)) {
                   2695:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2696:     }
1.47      www      2697:     $namevalue=~s/\&$//;
1.187     www      2698:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2699:     return critical
                   2700:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2701: }
                   2702: 
1.9       www      2703: # --------------------------------------------------------------------- Restore
                   2704: 
                   2705: sub restore {
1.124     www      2706:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2707:     my $home='';
                   2708: 
1.168     albertel 2709:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2710: 
1.122     albertel 2711:     if (!$symb) {
                   2712:       unless ($symb=escape(&symbread())) { return ''; }
                   2713:     } else {
1.213     www      2714:       $symb=&escape(&symbclean($symb));
1.122     albertel 2715:     }
1.188     www      2716:     if (!$namespace) { 
1.620     albertel 2717:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2718:           return ''; 
                   2719:        } 
                   2720:     }
1.620     albertel 2721:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2722:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2723:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2724:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2725: 
1.12      www      2726:     my %returnhash=();
1.800     albertel 2727:     foreach my $line (split(/\&/,$answer)) {
                   2728: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2729:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2730:     }
1.75      www      2731:     my $version;
                   2732:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2733:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2734:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2735:        }
1.75      www      2736:     }
1.13      www      2737:     return %returnhash;
1.34      www      2738: }
                   2739: 
                   2740: # ---------------------------------------------------------- Course Description
                   2741: 
                   2742: sub coursedescription {
1.731     albertel 2743:     my ($courseid,$args)=@_;
1.34      www      2744:     $courseid=~s/^\///;
1.49      www      2745:     $courseid=~s/\_/\//g;
1.34      www      2746:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2747:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2748:     my $normalid=$cdomain.'_'.$cnum;
                   2749:     # need to always cache even if we get errors otherwise we keep 
                   2750:     # trying and trying and trying to get the course description.
                   2751:     my %envhash=();
                   2752:     my %returnhash=();
1.731     albertel 2753:     
                   2754:     my $expiretime=600;
                   2755:     if ($env{'request.course.id'} eq $normalid) {
                   2756: 	$expiretime=120;
                   2757:     }
                   2758: 
                   2759:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2760:     if (!$args->{'freshen_cache'}
                   2761: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2762: 	foreach my $key (keys(%env)) {
                   2763: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2764: 	    my ($setting) = $1;
                   2765: 	    $returnhash{$setting} = $env{$key};
                   2766: 	}
                   2767: 	return %returnhash;
                   2768:     }
                   2769: 
                   2770:     # get the data agin
                   2771:     if (!$args->{'one_time'}) {
                   2772: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2773:     }
1.811     albertel 2774: 
1.34      www      2775:     if ($chome ne 'no_host') {
1.302     albertel 2776:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2777:        if (!exists($returnhash{'con_lost'})) {
                   2778:            $returnhash{'home'}= $chome;
                   2779: 	   $returnhash{'domain'} = $cdomain;
                   2780: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2781:            if (!defined($returnhash{'type'})) {
                   2782:                $returnhash{'type'} = 'Course';
                   2783:            }
1.130     albertel 2784:            while (my ($name,$value) = each %returnhash) {
1.53      www      2785:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2786:            }
1.270     www      2787:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2788:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2789: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2790:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2791:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2792:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2793:        }
                   2794:     }
1.731     albertel 2795:     if (!$args->{'one_time'}) {
                   2796: 	&appenv(%envhash);
                   2797:     }
1.302     albertel 2798:     return %returnhash;
1.461     www      2799: }
                   2800: 
                   2801: # -------------------------------------------------See if a user is privileged
                   2802: 
                   2803: sub privileged {
                   2804:     my ($username,$domain)=@_;
                   2805:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2806: 			&homeserver($username,$domain));
                   2807:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2808:     my $now=time;
                   2809:     if ($rolesdump ne '') {
1.800     albertel 2810:         foreach my $entry (split(/&/,$rolesdump)) {
                   2811: 	    if ($entry!~/^rolesdef_/) {
                   2812: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2813: 		$area=~s/\_\w\w$//;
                   2814: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2815: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2816: 		    my $active=1;
                   2817: 		    if ($tend) {
                   2818: 			if ($tend<$now) { $active=0; }
                   2819: 		    }
                   2820: 		    if ($tstart) {
                   2821: 			if ($tstart>$now) { $active=0; }
                   2822: 		    }
                   2823: 		    if ($active) { return 1; }
                   2824: 		}
                   2825: 	    }
                   2826: 	}
                   2827:     }
                   2828:     return 0;
1.9       www      2829: }
1.1       albertel 2830: 
1.103     harris41 2831: # -------------------------------------------------------- Get user privileges
1.11      www      2832: 
                   2833: sub rolesinit {
                   2834:     my ($domain,$username,$authhost)=@_;
                   2835:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2836:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2837:     my %allroles=();
1.678     raeburn  2838:     my %allgroups=();   
1.11      www      2839:     my $now=time;
1.743     albertel 2840:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2841:     my $group_privs;
1.11      www      2842: 
                   2843:     if ($rolesdump ne '') {
1.800     albertel 2844:         foreach my $entry (split(/&/,$rolesdump)) {
                   2845: 	  if ($entry!~/^rolesdef_/) {
                   2846:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2847: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2848:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2849: 	    if ($role=~/^cr/) { 
1.807     albertel 2850: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2851: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2852: 		    ($tend,$tstart)=split('_',$trest);
                   2853: 		} else {
                   2854: 		    $trole=$role;
                   2855: 		}
1.678     raeburn  2856:             } elsif ($role =~ m|^gr/|) {
                   2857:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2858:                 ($trole,$group_privs) = split(/\//,$trole);
                   2859:                 $group_privs = &unescape($group_privs);
1.587     albertel 2860: 	    } else {
                   2861: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2862: 	    }
1.743     albertel 2863: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2864: 					 $username);
                   2865: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2866:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2867:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2868:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2869: 		my $spec=$trole.'.'.$area;
                   2870: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2871: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2872:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2873:                 } elsif ($trole eq 'gr') {
                   2874:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2875: 		} else {
1.567     raeburn  2876:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2877: 		}
1.12      www      2878:             }
1.662     raeburn  2879:           }
1.191     harris41 2880:         }
1.743     albertel 2881:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2882:         $userroles{'user.adv'}    = $adv;
                   2883: 	$userroles{'user.author'} = $author;
1.620     albertel 2884:         $env{'user.adv'}=$adv;
1.11      www      2885:     }
1.743     albertel 2886:     return \%userroles;  
1.11      www      2887: }
                   2888: 
1.567     raeburn  2889: sub set_arearole {
                   2890:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2891: # log the associated role with the area
                   2892:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2893:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2894: }
                   2895: 
                   2896: sub custom_roleprivs {
                   2897:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2898:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2899:     my $homsvr=homeserver($rauthor,$rdomain);
                   2900:     if ($hostname{$homsvr} ne '') {
                   2901:         my ($rdummy,$roledef)=
                   2902:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2903:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2904:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2905:             if (defined($syspriv)) {
                   2906:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2907:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2908:             }
                   2909:             if ($tdomain ne '') {
                   2910:                 if (defined($dompriv)) {
                   2911:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2912:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2913:                 }
                   2914:                 if (($trest ne '') && (defined($coursepriv))) {
                   2915:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2916:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2917:                 }
                   2918:             }
                   2919:         }
                   2920:     }
                   2921: }
                   2922: 
1.678     raeburn  2923: sub group_roleprivs {
                   2924:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2925:     my $access = 1;
                   2926:     my $now = time;
                   2927:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2928:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2929:     if ($access) {
1.811     albertel 2930:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2931:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2932:     }
                   2933: }
1.567     raeburn  2934: 
                   2935: sub standard_roleprivs {
                   2936:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2937:     if (defined($pr{$trole.':s'})) {
                   2938:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2939:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2940:     }
                   2941:     if ($tdomain ne '') {
                   2942:         if (defined($pr{$trole.':d'})) {
                   2943:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2944:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2945:         }
                   2946:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2947:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2948:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2949:         }
                   2950:     }
                   2951: }
                   2952: 
                   2953: sub set_userprivs {
1.678     raeburn  2954:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2955:     my $author=0;
                   2956:     my $adv=0;
1.678     raeburn  2957:     my %grouproles = ();
                   2958:     if (keys(%{$allgroups}) > 0) {
                   2959:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2960:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2961:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2962:                 $trole = $1;
                   2963:                 $area = $2;
1.681     raeburn  2964:                 $sec = $3;
                   2965:                 $extendedarea = $area.$sec;
                   2966:                 if (exists($$allgroups{$area})) {
                   2967:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2968:                         my $spec = $trole.'.'.$extendedarea;
                   2969:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2970:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2971:                     }
                   2972:                 }
                   2973:             }
                   2974:         }
                   2975:     }
1.800     albertel 2976:     foreach my $group (keys(%grouproles)) {
                   2977:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2978:     }
1.800     albertel 2979:     foreach my $role (keys(%{$allroles})) {
                   2980:         my %thesepriv;
                   2981:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   2982:         foreach my $item (split(/:/,$$allroles{$role})) {
                   2983:             if ($item ne '') {
                   2984:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  2985:                 if ($restrictions eq '') {
                   2986:                     $thesepriv{$privilege}='F';
                   2987:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2988:                     $thesepriv{$privilege}.=$restrictions;
                   2989:                 }
                   2990:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2991:             }
                   2992:         }
                   2993:         my $thesestr='';
1.800     albertel 2994:         foreach my $priv (keys(%thesepriv)) {
                   2995: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   2996: 	}
                   2997:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  2998:     }
                   2999:     return ($author,$adv);
                   3000: }
                   3001: 
1.12      www      3002: # --------------------------------------------------------------- get interface
                   3003: 
                   3004: sub get {
1.131     albertel 3005:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3006:    my $items='';
1.800     albertel 3007:    foreach my $item (@$storearr) {
                   3008:        $items.=&escape($item).'&';
1.191     harris41 3009:    }
1.12      www      3010:    $items=~s/\&$//;
1.620     albertel 3011:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3012:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3013:    my $uhome=&homeserver($uname,$udomain);
                   3014: 
1.133     albertel 3015:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3016:    my @pairs=split(/\&/,$rep);
1.273     albertel 3017:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3018:      return @pairs;
                   3019:    }
1.15      www      3020:    my %returnhash=();
1.42      www      3021:    my $i=0;
1.800     albertel 3022:    foreach my $item (@$storearr) {
                   3023:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3024:       $i++;
1.191     harris41 3025:    }
1.15      www      3026:    return %returnhash;
1.27      www      3027: }
                   3028: 
                   3029: # --------------------------------------------------------------- del interface
                   3030: 
                   3031: sub del {
1.133     albertel 3032:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3033:    my $items='';
1.800     albertel 3034:    foreach my $item (@$storearr) {
                   3035:        $items.=&escape($item).'&';
1.191     harris41 3036:    }
1.27      www      3037:    $items=~s/\&$//;
1.620     albertel 3038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3039:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3040:    my $uhome=&homeserver($uname,$udomain);
                   3041: 
                   3042:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3043: }
                   3044: 
                   3045: # -------------------------------------------------------------- dump interface
                   3046: 
                   3047: sub dump {
1.755     albertel 3048:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3049:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3050:     if (!$uname) { $uname=$env{'user.name'}; }
                   3051:     my $uhome=&homeserver($uname,$udomain);
                   3052:     if ($regexp) {
                   3053: 	$regexp=&escape($regexp);
                   3054:     } else {
                   3055: 	$regexp='.';
                   3056:     }
                   3057:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3058:     my @pairs=split(/\&/,$rep);
                   3059:     my %returnhash=();
                   3060:     foreach my $item (@pairs) {
                   3061: 	my ($key,$value)=split(/=/,$item,2);
                   3062: 	$key = &unescape($key);
                   3063: 	next if ($key =~ /^error: 2 /);
                   3064: 	$returnhash{$key}=&thaw_unescape($value);
                   3065:     }
                   3066:     return %returnhash;
1.407     www      3067: }
                   3068: 
1.717     albertel 3069: # --------------------------------------------------------- dumpstore interface
                   3070: 
                   3071: sub dumpstore {
                   3072:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3073:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   3074: }
                   3075: 
1.407     www      3076: # -------------------------------------------------------------- keys interface
                   3077: 
                   3078: sub getkeys {
                   3079:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3080:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3081:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3082:    my $uhome=&homeserver($uname,$udomain);
                   3083:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3084:    my @keyarray=();
1.800     albertel 3085:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3086:       next if ($key =~ /^error: 2 /);
1.800     albertel 3087:       push(@keyarray,&unescape($key));
1.407     www      3088:    }
                   3089:    return @keyarray;
1.318     matthew  3090: }
                   3091: 
1.319     matthew  3092: # --------------------------------------------------------------- currentdump
                   3093: sub currentdump {
1.328     matthew  3094:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3095:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3096:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3097:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3098:    my $uhome = &homeserver($sname,$sdom);
                   3099:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3100:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3101:    #
1.318     matthew  3102:    my %returnhash=();
1.319     matthew  3103:    #
                   3104:    if ($rep eq "unknown_cmd") { 
                   3105:        # an old lond will not know currentdump
                   3106:        # Do a dump and make it look like a currentdump
1.326     matthew  3107:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3108:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3109:        my %hash = @tmp;
                   3110:        @tmp=();
1.424     matthew  3111:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3112:    } else {
                   3113:        my @pairs=split(/\&/,$rep);
1.800     albertel 3114:        foreach my $pair (@pairs) {
                   3115:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3116:            my ($symb,$param) = split(/:/,$key);
                   3117:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3118:                                                         &thaw_unescape($value);
1.319     matthew  3119:        }
1.191     harris41 3120:    }
1.12      www      3121:    return %returnhash;
1.424     matthew  3122: }
                   3123: 
                   3124: sub convert_dump_to_currentdump{
                   3125:     my %hash = %{shift()};
                   3126:     my %returnhash;
                   3127:     # Code ripped from lond, essentially.  The only difference
                   3128:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3129:     # we might run in to problems with parameter names =~ /^v\./
                   3130:     while (my ($key,$value) = each(%hash)) {
                   3131:         my ($v,$symb,$param) = split(/:/,$key);
                   3132:         next if ($v eq 'version' || $symb eq 'keys');
                   3133:         next if (exists($returnhash{$symb}) &&
                   3134:                  exists($returnhash{$symb}->{$param}) &&
                   3135:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3136:         $returnhash{$symb}->{$param}=$value;
                   3137:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3138:     }
                   3139:     #
                   3140:     # Remove all of the keys in the hashes which keep track of
                   3141:     # the version of the parameter.
                   3142:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3143:         # use a foreach because we are going to delete from the hash.
                   3144:         foreach my $key (keys(%$param_hash)) {
                   3145:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3146:         }
                   3147:     }
                   3148:     return \%returnhash;
1.12      www      3149: }
                   3150: 
1.627     albertel 3151: # ------------------------------------------------------ critical inc interface
                   3152: 
                   3153: sub cinc {
                   3154:     return &inc(@_,'critical');
                   3155: }
                   3156: 
1.449     matthew  3157: # --------------------------------------------------------------- inc interface
                   3158: 
                   3159: sub inc {
1.627     albertel 3160:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3161:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3162:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3163:     my $uhome=&homeserver($uname,$udomain);
                   3164:     my $items='';
                   3165:     if (! ref($store)) {
                   3166:         # got a single value, so use that instead
                   3167:         $items = &escape($store).'=&';
                   3168:     } elsif (ref($store) eq 'SCALAR') {
                   3169:         $items = &escape($$store).'=&';        
                   3170:     } elsif (ref($store) eq 'ARRAY') {
                   3171:         $items = join('=&',map {&escape($_);} @{$store});
                   3172:     } elsif (ref($store) eq 'HASH') {
                   3173:         while (my($key,$value) = each(%{$store})) {
                   3174:             $items.= &escape($key).'='.&escape($value).'&';
                   3175:         }
                   3176:     }
                   3177:     $items=~s/\&$//;
1.627     albertel 3178:     if ($critical) {
                   3179: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3180:     } else {
                   3181: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3182:     }
1.449     matthew  3183: }
                   3184: 
1.12      www      3185: # --------------------------------------------------------------- put interface
                   3186: 
                   3187: sub put {
1.134     albertel 3188:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3189:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3190:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3191:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3192:    my $items='';
1.800     albertel 3193:    foreach my $item (keys(%$storehash)) {
                   3194:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3195:    }
1.12      www      3196:    $items=~s/\&$//;
1.134     albertel 3197:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3198: }
                   3199: 
1.631     albertel 3200: # ------------------------------------------------------------ newput interface
                   3201: 
                   3202: sub newput {
                   3203:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3204:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3205:    if (!$uname) { $uname=$env{'user.name'}; }
                   3206:    my $uhome=&homeserver($uname,$udomain);
                   3207:    my $items='';
                   3208:    foreach my $key (keys(%$storehash)) {
                   3209:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3210:    }
                   3211:    $items=~s/\&$//;
                   3212:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3213: }
                   3214: 
                   3215: # ---------------------------------------------------------  putstore interface
                   3216: 
1.524     raeburn  3217: sub putstore {
1.715     albertel 3218:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3219:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3220:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3221:    my $uhome=&homeserver($uname,$udomain);
                   3222:    my $items='';
1.715     albertel 3223:    foreach my $key (keys(%$storehash)) {
                   3224:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3225:    }
1.715     albertel 3226:    $items=~s/\&$//;
1.716     albertel 3227:    my $esc_symb=&escape($symb);
                   3228:    my $esc_v=&escape($version);
1.715     albertel 3229:    my $reply =
1.716     albertel 3230:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3231: 	      $uhome);
                   3232:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3233:        # gfall back to way things use to be done
1.715     albertel 3234:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3235: 			    $uname);
1.524     raeburn  3236:    }
1.715     albertel 3237:    return $reply;
                   3238: }
                   3239: 
                   3240: sub old_putstore {
1.716     albertel 3241:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3242:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3243:     if (!$uname) { $uname=$env{'user.name'}; }
                   3244:     my $uhome=&homeserver($uname,$udomain);
                   3245:     my %newstorehash;
1.800     albertel 3246:     foreach my $item (keys(%$storehash)) {
                   3247: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3248: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3249:     }
                   3250:     my $items='';
                   3251:     my %allitems = ();
1.800     albertel 3252:     foreach my $item (keys(%newstorehash)) {
                   3253: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3254: 	    my $key = $1.':keys:'.$2;
                   3255: 	    $allitems{$key} .= $3.':';
                   3256: 	}
1.800     albertel 3257: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3258:     }
1.800     albertel 3259:     foreach my $item (keys(%allitems)) {
                   3260: 	$allitems{$item} =~ s/\:$//;
                   3261: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3262:     }
                   3263:     $items=~s/\&$//;
                   3264:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3265: }
                   3266: 
1.47      www      3267: # ------------------------------------------------------ critical put interface
                   3268: 
                   3269: sub cput {
1.134     albertel 3270:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3271:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3272:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3273:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3274:    my $items='';
1.800     albertel 3275:    foreach my $item (keys(%$storehash)) {
                   3276:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3277:    }
1.47      www      3278:    $items=~s/\&$//;
1.134     albertel 3279:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3280: }
                   3281: 
                   3282: # -------------------------------------------------------------- eget interface
                   3283: 
                   3284: sub eget {
1.133     albertel 3285:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3286:    my $items='';
1.800     albertel 3287:    foreach my $item (@$storearr) {
                   3288:        $items.=&escape($item).'&';
1.191     harris41 3289:    }
1.12      www      3290:    $items=~s/\&$//;
1.620     albertel 3291:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3292:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3293:    my $uhome=&homeserver($uname,$udomain);
                   3294:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3295:    my @pairs=split(/\&/,$rep);
                   3296:    my %returnhash=();
1.42      www      3297:    my $i=0;
1.800     albertel 3298:    foreach my $item (@$storearr) {
                   3299:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3300:       $i++;
1.191     harris41 3301:    }
1.12      www      3302:    return %returnhash;
                   3303: }
                   3304: 
1.667     albertel 3305: # ------------------------------------------------------------ tmpput interface
                   3306: sub tmpput {
1.802     raeburn  3307:     my ($storehash,$server,$context)=@_;
1.667     albertel 3308:     my $items='';
1.800     albertel 3309:     foreach my $item (keys(%$storehash)) {
                   3310: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3311:     }
                   3312:     $items=~s/\&$//;
1.802     raeburn  3313:     if (defined($context)) {
                   3314:         $items .= ':'.&escape($context);
                   3315:     }
1.667     albertel 3316:     return &reply("tmpput:$items",$server);
                   3317: }
                   3318: 
                   3319: # ------------------------------------------------------------ tmpget interface
                   3320: sub tmpget {
1.688     albertel 3321:     my ($token,$server)=@_;
                   3322:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3323:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3324:     my %returnhash;
                   3325:     foreach my $item (split(/\&/,$rep)) {
                   3326: 	my ($key,$value)=split(/=/,$item);
                   3327: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3328:     }
                   3329:     return %returnhash;
                   3330: }
                   3331: 
1.688     albertel 3332: # ------------------------------------------------------------ tmpget interface
                   3333: sub tmpdel {
                   3334:     my ($token,$server)=@_;
                   3335:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3336:     return &reply("tmpdel:$token",$server);
                   3337: }
                   3338: 
1.765     albertel 3339: # -------------------------------------------------- portfolio access checking
                   3340: 
                   3341: sub portfolio_access {
1.766     albertel 3342:     my ($requrl) = @_;
1.765     albertel 3343:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3344:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3345:     if ($result) {
                   3346:         my %setters;
                   3347:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3348:             my ($startblock,$endblock) =
                   3349:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3350:             if ($startblock && $endblock) {
                   3351:                 return 'B';
                   3352:             }
                   3353:         } else {
                   3354:             my ($startblock,$endblock) =
                   3355:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3356:             if ($startblock && $endblock) {
                   3357:                 return 'B';
                   3358:             }
                   3359:         }
                   3360:     }
1.765     albertel 3361:     if ($result eq 'ok') {
1.766     albertel 3362:        return 'F';
1.765     albertel 3363:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3364:        return 'A';
1.765     albertel 3365:     }
1.766     albertel 3366:     return '';
1.765     albertel 3367: }
                   3368: 
                   3369: sub get_portfolio_access {
1.767     albertel 3370:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3371: 
                   3372:     if (!ref($access_hash)) {
                   3373: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3374: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3375: 						   $file_name);
                   3376: 	$access_hash = $access_controls{$file_name};
                   3377:     }
                   3378: 
1.765     albertel 3379:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3380:     my $now = time;
                   3381:     if (ref($access_hash) eq 'HASH') {
                   3382:         foreach my $key (keys(%{$access_hash})) {
                   3383:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3384:             if ($start > $now) {
                   3385:                 next;
                   3386:             }
                   3387:             if ($end && $end<$now) {
                   3388:                 next;
                   3389:             }
                   3390:             if ($scope eq 'public') {
                   3391:                 $public = $key;
                   3392:                 last;
                   3393:             } elsif ($scope eq 'guest') {
                   3394:                 $guest = $key;
                   3395:             } elsif ($scope eq 'domains') {
                   3396:                 push(@domains,$key);
                   3397:             } elsif ($scope eq 'users') {
                   3398:                 push(@users,$key);
                   3399:             } elsif ($scope eq 'course') {
                   3400:                 push(@courses,$key);
                   3401:             } elsif ($scope eq 'group') {
                   3402:                 push(@groups,$key);
                   3403:             }
                   3404:         }
                   3405:         if ($public) {
                   3406:             return 'ok';
                   3407:         }
                   3408:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3409:             if ($guest) {
                   3410:                 return $guest;
                   3411:             }
                   3412:         } else {
                   3413:             if (@domains > 0) {
                   3414:                 foreach my $domkey (@domains) {
                   3415:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3416:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3417:                             return 'ok';
                   3418:                         }
                   3419:                     }
                   3420:                 }
                   3421:             }
                   3422:             if (@users > 0) {
                   3423:                 foreach my $userkey (@users) {
                   3424:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3425:                         return 'ok';
                   3426:                     }
                   3427:                 }
                   3428:             }
                   3429:             my %roleshash;
                   3430:             my @courses_and_groups = @courses;
                   3431:             push(@courses_and_groups,@groups); 
                   3432:             if (@courses_and_groups > 0) {
                   3433:                 my (%allgroups,%allroles); 
                   3434:                 my ($start,$end,$role,$sec,$group);
                   3435:                 foreach my $envkey (%env) {
1.811     albertel 3436:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3437:                         my $cid = $2.'_'.$3; 
                   3438:                         if ($1 eq 'gr') {
                   3439:                             $group = $4;
                   3440:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3441:                         } else {
                   3442:                             if ($4 eq '') {
                   3443:                                 $sec = 'none';
                   3444:                             } else {
                   3445:                                 $sec = $4;
                   3446:                             }
                   3447:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3448:                         }
1.811     albertel 3449:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3450:                         my $cid = $2.'_'.$3;
                   3451:                         if ($4 eq '') {
                   3452:                             $sec = 'none';
                   3453:                         } else {
                   3454:                             $sec = $4;
                   3455:                         }
                   3456:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3457:                     }
                   3458:                 }
                   3459:                 if (keys(%allroles) == 0) {
                   3460:                     return;
                   3461:                 }
                   3462:                 foreach my $key (@courses_and_groups) {
                   3463:                     my %content = %{$$access_hash{$key}};
                   3464:                     my $cnum = $content{'number'};
                   3465:                     my $cdom = $content{'domain'};
                   3466:                     my $cid = $cdom.'_'.$cnum;
                   3467:                     if (!exists($allroles{$cid})) {
                   3468:                         next;
                   3469:                     }    
                   3470:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3471:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3472:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3473:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3474:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3475:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3476:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3477:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3478:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3479:                                         if (grep/^all$/,@sections) {
                   3480:                                             return 'ok';
                   3481:                                         } else {
                   3482:                                             if (grep/^$sec$/,@sections) {
                   3483:                                                 return 'ok';
                   3484:                                             }
                   3485:                                         }
                   3486:                                     }
                   3487:                                 }
                   3488:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3489:                                     if (grep/^none$/,@groups) {
                   3490:                                         return 'ok';
                   3491:                                     }
                   3492:                                 } else {
                   3493:                                     if (grep/^all$/,@groups) {
                   3494:                                         return 'ok';
                   3495:                                     } 
                   3496:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3497:                                         if (grep/^$group$/,@groups) {
                   3498:                                             return 'ok';
                   3499:                                         }
                   3500:                                     }
                   3501:                                 } 
                   3502:                             }
                   3503:                         }
                   3504:                     }
                   3505:                 }
                   3506:             }
                   3507:             if ($guest) {
                   3508:                 return $guest;
                   3509:             }
                   3510:         }
                   3511:     }
                   3512:     return;
                   3513: }
                   3514: 
                   3515: sub course_group_datechecker {
                   3516:     my ($dates,$now,$status) = @_;
                   3517:     my ($start,$end) = split(/\./,$dates);
                   3518:     if (!$start && !$end) {
                   3519:         return 'ok';
                   3520:     }
                   3521:     if (grep/^active$/,@{$status}) {
                   3522:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3523:             return 'ok';
                   3524:         }
                   3525:     }
                   3526:     if (grep/^previous$/,@{$status}) {
                   3527:         if ($end > $now ) {
                   3528:             return 'ok';
                   3529:         }
                   3530:     }
                   3531:     if (grep/^future$/,@{$status}) {
                   3532:         if ($start > $now) {
                   3533:             return 'ok';
                   3534:         }
                   3535:     }
                   3536:     return; 
                   3537: }
                   3538: 
                   3539: sub parse_portfolio_url {
                   3540:     my ($url) = @_;
                   3541: 
                   3542:     my ($type,$udom,$unum,$group,$file_name);
                   3543:     
1.807     albertel 3544:     if ($url =~  m-^/*uploaded/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3545: 	$type = 1;
                   3546:         $udom = $1;
                   3547:         $unum = $2;
                   3548:         $file_name = $3;
1.811     albertel 3549:     } elsif ($url =~ m-^/*uploaded/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3550: 	$type = 2;
                   3551:         $udom = $1;
                   3552:         $unum = $2;
                   3553:         $group = $3;
                   3554:         $file_name = $3.'/'.$4;
                   3555:     }
                   3556:     if (wantarray) {
                   3557: 	return ($type,$udom,$unum,$file_name,$group);
                   3558:     }
                   3559:     return $type;
                   3560: }
                   3561: 
                   3562: sub is_portfolio_url {
                   3563:     my ($url) = @_;
                   3564:     return scalar(&parse_portfolio_url($url));
                   3565: }
                   3566: 
1.798     raeburn  3567: sub is_portfolio_file {
                   3568:     my ($file) = @_;
1.820     raeburn  3569:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3570:         return 1;
                   3571:     }
                   3572:     return;
                   3573: }
                   3574: 
                   3575: 
1.341     www      3576: # ---------------------------------------------- Custom access rule evaluation
                   3577: 
                   3578: sub customaccess {
                   3579:     my ($priv,$uri)=@_;
1.807     albertel 3580:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3581:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3582:     $udom = &LONCAPA::clean_domain($udom);
                   3583:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3584:     my $access=0;
1.800     albertel 3585:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3586: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3587:         if ($role) {
                   3588: 	   if ($role ne $urole) { next; }
                   3589:         }
1.800     albertel 3590:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3591:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3592:             if ($tdom) {
                   3593: 		if ($tdom ne $udom) { next; }
                   3594:             }
                   3595:             if ($tcrs) {
                   3596: 		if ($tcrs ne $ucrs) { next; }
                   3597:             }
                   3598:             if ($tsec) {
                   3599: 		if ($tsec ne $usec) { next; }
                   3600:             }
                   3601:             $access=($effect eq 'allow');
                   3602:             last;
1.342     www      3603:         }
1.402     bowersj2 3604: 	if ($realm eq '' && $role eq '') {
                   3605:             $access=($effect eq 'allow');
                   3606: 	}
1.341     www      3607:     }
                   3608:     return $access;
                   3609: }
                   3610: 
1.103     harris41 3611: # ------------------------------------------------- Check for a user privilege
1.12      www      3612: 
                   3613: sub allowed {
1.810     raeburn  3614:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3615:     my $ver_orguri=$uri;
1.439     www      3616:     $uri=&deversion($uri);
1.152     www      3617:     my $orguri=$uri;
1.52      www      3618:     $uri=&declutter($uri);
1.809     raeburn  3619: 
1.810     raeburn  3620:     if ($priv eq 'evb') {
                   3621: # Evade communication block restrictions for specified role in a course
                   3622:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3623:             return $1;
                   3624:         } else {
                   3625:             return;
                   3626:         }
                   3627:     }
                   3628: 
1.620     albertel 3629:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3630: # Free bre access to adm and meta resources
1.775     albertel 3631:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3632: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3633: 	&& ($priv eq 'bre')) {
1.14      www      3634: 	return 'F';
1.159     www      3635:     }
                   3636: 
1.545     banghart 3637: # Free bre access to user's own portfolio contents
1.714     raeburn  3638:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3639:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3640: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3641:         my %setters;
                   3642:         my ($startblock,$endblock) = 
                   3643:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3644:         if ($startblock && $endblock) {
                   3645:             return 'B';
                   3646:         } else {
                   3647:             return 'F';
                   3648:         }
1.545     banghart 3649:     }
                   3650: 
1.762     raeburn  3651: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3652:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3653:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3654:         if (exists($env{'request.course.id'})) {
                   3655:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3656:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3657:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3658:                 my $courseprivid=$env{'request.course.id'};
                   3659:                 $courseprivid=~s/\_/\//;
                   3660:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3661:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3662:                     return $1; 
1.762     raeburn  3663:                 } else {
                   3664:                     if ($env{'request.course.sec'}) {
                   3665:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3666:                     }
                   3667:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3668:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3669:                         return $2;
                   3670:                     }
1.714     raeburn  3671:                 }
                   3672:             }
                   3673:         }
                   3674:     }
                   3675: 
1.159     www      3676: # Free bre to public access
                   3677: 
                   3678:     if ($priv eq 'bre') {
1.238     www      3679:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3680: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3681:            return 'F'; 
                   3682:         }
1.238     www      3683:         if ($copyright eq 'priv') {
                   3684:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3685: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3686: 		return '';
                   3687:             }
                   3688:         }
                   3689:         if ($copyright eq 'domain') {
                   3690:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3691: 	    unless (($env{'user.domain'} eq $1) ||
                   3692:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3693: 		return '';
                   3694:             }
1.262     matthew  3695:         }
1.620     albertel 3696:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3697:             # Library role, so allow browsing of resources in this domain.
                   3698:             return 'F';
1.238     www      3699:         }
1.341     www      3700:         if ($copyright eq 'custom') {
                   3701: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3702:         }
1.14      www      3703:     }
1.264     matthew  3704:     # Domain coordinator is trying to create a course
1.620     albertel 3705:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3706:         # uri is the requested domain in this case.
                   3707:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3708:         # a role of dc for the domain in question.
1.620     albertel 3709:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3710:     }
1.29      www      3711: 
1.52      www      3712:     my $thisallowed='';
                   3713:     my $statecond=0;
                   3714:     my $courseprivid='';
                   3715: 
                   3716: # Course
                   3717: 
1.620     albertel 3718:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3719:        $thisallowed.=$1;
                   3720:     }
1.29      www      3721: 
1.52      www      3722: # Domain
                   3723: 
1.620     albertel 3724:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3725:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3726:        $thisallowed.=$1;
                   3727:     }
1.52      www      3728: 
                   3729: # Course: uri itself is a course
1.66      www      3730:     my $courseuri=$uri;
                   3731:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3732:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3733: 
1.620     albertel 3734:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3735:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3736:        $thisallowed.=$1;
                   3737:     }
1.29      www      3738: 
1.665     albertel 3739: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3740: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3741:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3742: 	$thisallowed='';
1.671     raeburn  3743:         my ($match)=&is_on_map($uri);
                   3744:         if ($match) {
                   3745:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3746:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3747:                 $thisallowed.=$1;
                   3748:             }
                   3749:         } else {
1.705     albertel 3750:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3751:             if ($refuri) {
                   3752:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3753:                     $thisallowed='F';
1.671     raeburn  3754:                 } else {
                   3755:                     $refuri=&declutter($refuri);
                   3756:                     my ($match) = &is_on_map($refuri);
                   3757:                     if ($match) {
                   3758:                         $thisallowed='F';
                   3759:                     }
1.669     raeburn  3760:                 }
1.671     raeburn  3761:             }
                   3762:         }
1.314     www      3763:     }
1.492     albertel 3764: 
1.766     albertel 3765:     if ($priv eq 'bre'
                   3766: 	&& $thisallowed ne 'F' 
                   3767: 	&& $thisallowed ne '2'
                   3768: 	&& &is_portfolio_url($uri)) {
                   3769: 	$thisallowed = &portfolio_access($uri);
                   3770:     }
                   3771:     
1.52      www      3772: # Full access at system, domain or course-wide level? Exit.
1.29      www      3773: 
                   3774:     if ($thisallowed=~/F/) {
                   3775: 	return 'F';
                   3776:     }
                   3777: 
1.52      www      3778: # If this is generating or modifying users, exit with special codes
1.29      www      3779: 
1.643     www      3780:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3781: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3782: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3783: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3784: 	    unless ($auname) { return $thisallowed; }
                   3785: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3786: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3787: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3788: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3789: 	}
1.52      www      3790: 	return $thisallowed;
                   3791:     }
                   3792: #
1.103     harris41 3793: # Gathered so far: system, domain and course wide privileges
1.52      www      3794: #
                   3795: # Course: See if uri or referer is an individual resource that is part of 
                   3796: # the course
                   3797: 
1.620     albertel 3798:     if ($env{'request.course.id'}) {
1.232     www      3799: 
1.620     albertel 3800:        $courseprivid=$env{'request.course.id'};
                   3801:        if ($env{'request.course.sec'}) {
                   3802:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3803:        }
                   3804:        $courseprivid=~s/\_/\//;
                   3805:        my $checkreferer=1;
1.232     www      3806:        my ($match,$cond)=&is_on_map($uri);
                   3807:        if ($match) {
                   3808:            $statecond=$cond;
1.620     albertel 3809:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3810:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3811:                $thisallowed.=$1;
                   3812:                $checkreferer=0;
                   3813:            }
1.29      www      3814:        }
1.83      www      3815:        
1.148     www      3816:        if ($checkreferer) {
1.620     albertel 3817: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3818:             unless ($refuri) {
1.800     albertel 3819:                 foreach my $key (keys(%env)) {
                   3820: 		    if ($key=~/^httpref\..*\*/) {
                   3821: 			my $pattern=$key;
1.156     www      3822:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3823:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3824:                         $pattern=~s/\//\\\//g;
1.152     www      3825:                         if ($orguri=~/$pattern/) {
1.800     albertel 3826: 			    $refuri=$env{$key};
1.148     www      3827:                         }
                   3828:                     }
1.191     harris41 3829:                 }
1.148     www      3830:             }
1.232     www      3831: 
1.148     www      3832:          if ($refuri) { 
1.152     www      3833: 	  $refuri=&declutter($refuri);
1.232     www      3834:           my ($match,$cond)=&is_on_map($refuri);
                   3835:             if ($match) {
                   3836:               my $refstatecond=$cond;
1.620     albertel 3837:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3838:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3839:                   $thisallowed.=$1;
1.53      www      3840:                   $uri=$refuri;
                   3841:                   $statecond=$refstatecond;
1.52      www      3842:               }
                   3843:           }
1.148     www      3844:         }
1.29      www      3845:        }
1.52      www      3846:    }
1.29      www      3847: 
1.52      www      3848: #
1.103     harris41 3849: # Gathered now: all privileges that could apply, and condition number
1.52      www      3850: # 
                   3851: #
                   3852: # Full or no access?
                   3853: #
1.29      www      3854: 
1.52      www      3855:     if ($thisallowed=~/F/) {
                   3856: 	return 'F';
                   3857:     }
1.29      www      3858: 
1.52      www      3859:     unless ($thisallowed) {
                   3860:         return '';
                   3861:     }
1.29      www      3862: 
1.52      www      3863: # Restrictions exist, deal with them
                   3864: #
                   3865: #   C:according to course preferences
                   3866: #   R:according to resource settings
                   3867: #   L:unless locked
                   3868: #   X:according to user session state
                   3869: #
                   3870: 
                   3871: # Possibly locked functionality, check all courses
1.54      www      3872: # Locks might take effect only after 10 minutes cache expiration for other
                   3873: # courses, and 2 minutes for current course
1.52      www      3874: 
                   3875:     my $envkey;
                   3876:     if ($thisallowed=~/L/) {
1.620     albertel 3877:         foreach $envkey (keys %env) {
1.54      www      3878:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3879:                my $courseid=$2;
                   3880:                my $roleid=$1.'.'.$2;
1.92      www      3881:                $courseid=~s/^\///;
1.54      www      3882:                my $expiretime=600;
1.620     albertel 3883:                if ($env{'request.role'} eq $roleid) {
1.54      www      3884: 		  $expiretime=120;
                   3885:                }
                   3886: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3887:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3888:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3889: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3890:                }
1.620     albertel 3891:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3892:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3893: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3894:                        &log($env{'user.domain'},$env{'user.name'},
                   3895:                             $env{'user.home'},
1.57      www      3896:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3897:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3898:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3899: 		       return '';
                   3900:                    }
                   3901:                }
1.620     albertel 3902:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3903:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3904: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3905:                        &log($env{'user.domain'},$env{'user.name'},
                   3906:                             $env{'user.home'},
1.57      www      3907:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3908:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3909:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3910: 		       return '';
                   3911:                    }
                   3912:                }
                   3913: 	   }
1.29      www      3914:        }
1.52      www      3915:     }
                   3916:    
                   3917: #
                   3918: # Rest of the restrictions depend on selected course
                   3919: #
                   3920: 
1.620     albertel 3921:     unless ($env{'request.course.id'}) {
1.766     albertel 3922: 	if ($thisallowed eq 'A') {
                   3923: 	    return 'A';
1.814     raeburn  3924:         } elsif ($thisallowed eq 'B') {
                   3925:             return 'B';
1.766     albertel 3926: 	} else {
                   3927: 	    return '1';
                   3928: 	}
1.52      www      3929:     }
1.29      www      3930: 
1.52      www      3931: #
                   3932: # Now user is definitely in a course
                   3933: #
1.53      www      3934: 
                   3935: 
                   3936: # Course preferences
                   3937: 
                   3938:    if ($thisallowed=~/C/) {
1.620     albertel 3939:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3940:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3941:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3942: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3943: 	   if ($priv ne 'pch') { 
                   3944: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3945: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3946: 			$env{'request.course.id'});
                   3947: 	   }
1.237     www      3948:            return '';
                   3949:        }
                   3950: 
1.620     albertel 3951:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3952: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3953: 	   if ($priv ne 'pch') { 
                   3954: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3955: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3956: 			$env{'request.course.id'});
                   3957: 	   }
1.54      www      3958:            return '';
                   3959:        }
1.53      www      3960:    }
                   3961: 
                   3962: # Resource preferences
                   3963: 
                   3964:    if ($thisallowed=~/R/) {
1.620     albertel 3965:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3966:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3967: 	   if ($priv ne 'pch') { 
                   3968: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3969: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3970: 	   }
                   3971: 	   return '';
1.54      www      3972:        }
1.53      www      3973:    }
1.30      www      3974: 
1.246     www      3975: # Restricted by state or randomout?
1.30      www      3976: 
1.52      www      3977:    if ($thisallowed=~/X/) {
1.620     albertel 3978:       if ($env{'acc.randomout'}) {
1.579     albertel 3979: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3980:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3981:             return ''; 
                   3982:          }
1.247     www      3983:       }
                   3984:       if (&condval($statecond)) {
1.52      www      3985: 	 return '2';
                   3986:       } else {
                   3987:          return '';
                   3988:       }
                   3989:    }
1.30      www      3990: 
1.766     albertel 3991:     if ($thisallowed eq 'A') {
                   3992: 	return 'A';
1.814     raeburn  3993:     } elsif ($thisallowed eq 'B') {
                   3994:         return 'B';
1.766     albertel 3995:     }
1.52      www      3996:    return 'F';
1.232     www      3997: }
                   3998: 
1.710     albertel 3999: sub split_uri_for_cond {
                   4000:     my $uri=&deversion(&declutter(shift));
                   4001:     my @uriparts=split(/\//,$uri);
                   4002:     my $filename=pop(@uriparts);
                   4003:     my $pathname=join('/',@uriparts);
                   4004:     return ($pathname,$filename);
                   4005: }
1.232     www      4006: # --------------------------------------------------- Is a resource on the map?
                   4007: 
                   4008: sub is_on_map {
1.710     albertel 4009:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4010:     #Trying to find the conditional for the file
1.620     albertel 4011:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4012: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4013:     if ($match) {
1.289     bowersj2 4014: 	return (1,$1);
                   4015:     } else {
1.434     www      4016: 	return (0,0);
1.289     bowersj2 4017:     }
1.12      www      4018: }
                   4019: 
1.427     www      4020: # --------------------------------------------------------- Get symb from alias
                   4021: 
                   4022: sub get_symb_from_alias {
                   4023:     my $symb=shift;
                   4024:     my ($map,$resid,$url)=&decode_symb($symb);
                   4025: # Already is a symb
                   4026:     if ($url) { return $symb; }
                   4027: # Must be an alias
                   4028:     my $aliassymb='';
                   4029:     my %bighash;
1.620     albertel 4030:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4031:                             &GDBM_READER(),0640)) {
                   4032:         my $rid=$bighash{'mapalias_'.$symb};
                   4033: 	if ($rid) {
                   4034: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4035: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4036: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4037: 	}
                   4038:         untie %bighash;
                   4039:     }
                   4040:     return $aliassymb;
                   4041: }
                   4042: 
1.12      www      4043: # ----------------------------------------------------------------- Define Role
                   4044: 
                   4045: sub definerole {
                   4046:   if (allowed('mcr','/')) {
                   4047:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4048:     foreach my $role (split(':',$sysrole)) {
                   4049: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4050:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4051:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4052: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4053:                return "refused:s:$crole&$cqual"; 
                   4054:             }
                   4055:         }
1.191     harris41 4056:     }
1.800     albertel 4057:     foreach my $role (split(':',$domrole)) {
                   4058: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4059:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4060:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4061: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4062:                return "refused:d:$crole&$cqual"; 
                   4063:             }
                   4064:         }
1.191     harris41 4065:     }
1.800     albertel 4066:     foreach my $role (split(':',$courole)) {
                   4067: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4068:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4069:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4070: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4071:                return "refused:c:$crole&$cqual"; 
                   4072:             }
                   4073:         }
1.191     harris41 4074:     }
1.620     albertel 4075:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4076:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4077: 	        "rolesdef_$rolename=".
                   4078:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4079:     return reply($command,$env{'user.home'});
1.12      www      4080:   } else {
                   4081:     return 'refused';
                   4082:   }
1.105     harris41 4083: }
                   4084: 
                   4085: # ---------------- Make a metadata query against the network of library servers
                   4086: 
                   4087: sub metadata_query {
1.244     matthew  4088:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4089:     my %rhash;
1.244     matthew  4090:     my @server_list = (defined($server_array) ? @$server_array
                   4091:                                               : keys(%libserv) );
                   4092:     for my $server (@server_list) {
1.118     harris41 4093: 	unless ($custom or $customshow) {
                   4094: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4095: 	    $rhash{$server}=$reply;
                   4096: 	}
                   4097: 	else {
                   4098: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4099: 			     &escape($custom).':'.&escape($customshow),
                   4100: 			     $server);
                   4101: 	    $rhash{$server}=$reply;
                   4102: 	}
1.112     harris41 4103:     }
1.118     harris41 4104:     return \%rhash;
1.240     www      4105: }
                   4106: 
                   4107: # ----------------------------------------- Send log queries and wait for reply
                   4108: 
                   4109: sub log_query {
                   4110:     my ($uname,$udom,$query,%filters)=@_;
                   4111:     my $uhome=&homeserver($uname,$udom);
                   4112:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4113:     my $uhost=$hostname{$uhome};
1.800     albertel 4114:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4115:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4116:                        $uhome);
1.479     albertel 4117:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4118:     return get_query_reply($queryid);
                   4119: }
                   4120: 
1.818     raeburn  4121: # -------------------------- Update MySQL table for portfolio file
                   4122: 
                   4123: sub update_portfolio_table {
1.821   ! raeburn  4124:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4125:     my $homeserver = &homeserver($uname,$udom);
                   4126:     my $queryid=
1.821   ! raeburn  4127:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
        !          4128:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4129:     my $reply = &get_query_reply($queryid);
                   4130:     return $reply;
                   4131: }
                   4132: 
1.508     raeburn  4133: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4134: 
                   4135: sub fetch_enrollment_query {
1.511     raeburn  4136:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4137:     my $homeserver;
1.547     raeburn  4138:     my $maxtries = 1;
1.508     raeburn  4139:     if ($context eq 'automated') {
                   4140:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4141:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4142:     } else {
                   4143:         $homeserver = &homeserver($cnum,$dom);
                   4144:     }
1.506     raeburn  4145:     my $host=$hostname{$homeserver};
                   4146:     my $cmd = '';
1.800     albertel 4147:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4148:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4149:     }
                   4150:     $cmd =~ s/%%$//;
                   4151:     $cmd = &escape($cmd);
                   4152:     my $query = 'fetchenrollment';
1.620     albertel 4153:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4154:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4155:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4156:         return 'error: '.$queryid;
                   4157:     }
1.506     raeburn  4158:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4159:     my $tries = 1;
                   4160:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4161:         $reply = &get_query_reply($queryid);
                   4162:         $tries ++;
                   4163:     }
1.526     raeburn  4164:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4165:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4166:     } else {
1.515     raeburn  4167:         my @responses = split/:/,$reply;
                   4168:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4169:             foreach my $line (@responses) {
                   4170:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4171:                 $$replyref{$key} = $value;
                   4172:             }
                   4173:         } else {
1.506     raeburn  4174:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4175:             foreach my $line (@responses) {
                   4176:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4177:                 $$replyref{$key} = $value;
                   4178:                 if ($value > 0) {
1.800     albertel 4179:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4180:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4181:                         my $destname = $pathname.'/'.$filename;
                   4182:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4183:                         if ($xml_classlist =~ /^error/) {
                   4184:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4185:                         } else {
1.506     raeburn  4186:                             if ( open(FILE,">$destname") ) {
                   4187:                                 print FILE &unescape($xml_classlist);
                   4188:                                 close(FILE);
1.526     raeburn  4189:                             } else {
                   4190:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4191:                             }
                   4192:                         }
                   4193:                     }
                   4194:                 }
                   4195:             }
                   4196:         }
                   4197:         return 'ok';
                   4198:     }
                   4199:     return 'error';
                   4200: }
                   4201: 
1.242     www      4202: sub get_query_reply {
                   4203:     my $queryid=shift;
1.240     www      4204:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4205:     my $reply='';
                   4206:     for (1..100) {
                   4207: 	sleep 2;
                   4208:         if (-e $replyfile.'.end') {
1.448     albertel 4209: 	    if (open(my $fh,$replyfile)) {
1.240     www      4210:                $reply.=<$fh>;
1.448     albertel 4211:                close($fh);
1.240     www      4212: 	   } else { return 'error: reply_file_error'; }
1.242     www      4213:            return &unescape($reply);
                   4214: 	}
1.240     www      4215:     }
1.242     www      4216:     return 'timeout:'.$queryid;
1.240     www      4217: }
                   4218: 
                   4219: sub courselog_query {
1.241     www      4220: #
                   4221: # possible filters:
                   4222: # url: url or symb
                   4223: # username
                   4224: # domain
                   4225: # action: view, submit, grade
                   4226: # start: timestamp
                   4227: # end: timestamp
                   4228: #
1.240     www      4229:     my (%filters)=@_;
1.620     albertel 4230:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4231:     if ($filters{'url'}) {
                   4232: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4233:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4234:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4235:     }
1.620     albertel 4236:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4237:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4238:     return &log_query($cname,$cdom,'courselog',%filters);
                   4239: }
                   4240: 
                   4241: sub userlog_query {
                   4242:     my ($uname,$udom,%filters)=@_;
                   4243:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4244: }
                   4245: 
1.506     raeburn  4246: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4247: 
                   4248: sub auto_run {
1.508     raeburn  4249:     my ($cnum,$cdom) = @_;
                   4250:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4251:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4252:     return $response;
                   4253: }
1.776     albertel 4254: 
1.506     raeburn  4255: sub auto_get_sections {
1.508     raeburn  4256:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4257:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4258:     my @secs = ();
1.511     raeburn  4259:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4260:     unless ($response eq 'refused') {
                   4261:         @secs = split/:/,$response;
                   4262:     }
                   4263:     return @secs;
                   4264: }
1.776     albertel 4265: 
1.506     raeburn  4266: sub auto_new_course {
1.508     raeburn  4267:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4268:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4269:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4270:     return $response;
                   4271: }
1.776     albertel 4272: 
1.506     raeburn  4273: sub auto_validate_courseID {
1.508     raeburn  4274:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4275:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4276:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4277:     return $response;
                   4278: }
1.776     albertel 4279: 
1.506     raeburn  4280: sub auto_create_password {
1.508     raeburn  4281:     my ($cnum,$cdom,$authparam) = @_;
                   4282:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4283:     my $create_passwd = 0;
                   4284:     my $authchk = '';
1.511     raeburn  4285:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4286:     if ($response eq 'refused') {
                   4287:         $authchk = 'refused';
                   4288:     } else {
                   4289:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4290:     }
                   4291:     return ($authparam,$create_passwd,$authchk);
                   4292: }
                   4293: 
1.706     raeburn  4294: sub auto_photo_permission {
                   4295:     my ($cnum,$cdom,$students) = @_;
                   4296:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4297:     my ($outcome,$perm_reqd,$conditions) = 
                   4298: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4299:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4300: 	return (undef,undef);
                   4301:     }
1.706     raeburn  4302:     return ($outcome,$perm_reqd,$conditions);
                   4303: }
                   4304: 
                   4305: sub auto_checkphotos {
                   4306:     my ($uname,$udom,$pid) = @_;
                   4307:     my $homeserver = &homeserver($uname,$udom);
                   4308:     my ($result,$resulttype);
                   4309:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4310: 				   &escape($uname).':'.&escape($pid),
                   4311: 				   $homeserver));
1.709     albertel 4312:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4313: 	return (undef,undef);
                   4314:     }
1.706     raeburn  4315:     if ($outcome) {
                   4316:         ($result,$resulttype) = split(/:/,$outcome);
                   4317:     } 
                   4318:     return ($result,$resulttype);
                   4319: }
                   4320: 
                   4321: sub auto_photochoice {
                   4322:     my ($cnum,$cdom) = @_;
                   4323:     my $homeserver = &homeserver($cnum,$cdom);
                   4324:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4325: 						       &escape($cdom),
                   4326: 						       $homeserver)));
1.709     albertel 4327:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4328: 	return (undef,undef);
                   4329:     }
1.706     raeburn  4330:     return ($update,$comment);
                   4331: }
                   4332: 
                   4333: sub auto_photoupdate {
                   4334:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4335:     my $homeserver = &homeserver($cnum,$dom);
                   4336:     my $host=$hostname{$homeserver};
                   4337:     my $cmd = '';
                   4338:     my $maxtries = 1;
1.800     albertel 4339:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4340:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4341:     }
                   4342:     $cmd =~ s/%%$//;
                   4343:     $cmd = &escape($cmd);
                   4344:     my $query = 'institutionalphotos';
                   4345:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4346:     unless ($queryid=~/^\Q$host\E\_/) {
                   4347:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4348:         return 'error: '.$queryid;
                   4349:     }
                   4350:     my $reply = &get_query_reply($queryid);
                   4351:     my $tries = 1;
                   4352:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4353:         $reply = &get_query_reply($queryid);
                   4354:         $tries ++;
                   4355:     }
                   4356:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4357:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4358:     } else {
                   4359:         my @responses = split(/:/,$reply);
                   4360:         my $outcome = shift(@responses); 
                   4361:         foreach my $item (@responses) {
                   4362:             my ($key,$value) = split(/=/,$item);
                   4363:             $$photo{$key} = $value;
                   4364:         }
                   4365:         return $outcome;
                   4366:     }
                   4367:     return 'error';
                   4368: }
                   4369: 
1.521     raeburn  4370: sub auto_instcode_format {
1.793     albertel 4371:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4372: 	$cat_order) = @_;
1.521     raeburn  4373:     my $courses = '';
1.772     raeburn  4374:     my @homeservers;
1.521     raeburn  4375:     if ($caller eq 'global') {
1.793     albertel 4376:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4377:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4378:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4379:                     push(@homeservers,$tryserver);
                   4380:                 }
1.584     raeburn  4381:             }
                   4382:         }
1.521     raeburn  4383:     } else {
1.772     raeburn  4384:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4385:     }
1.793     albertel 4386:     foreach my $code (keys(%{$instcodes})) {
                   4387:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4388:     }
                   4389:     chop($courses);
1.772     raeburn  4390:     my $ok_response = 0;
                   4391:     my $response;
                   4392:     while (@homeservers > 0 && $ok_response == 0) {
                   4393:         my $server = shift(@homeservers); 
                   4394:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4395:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4396:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4397: 		split/:/,$response;
1.772     raeburn  4398:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4399:             push(@{$codetitles},&str2array($codetitles_str));
                   4400:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4401:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4402:             $ok_response = 1;
                   4403:         }
                   4404:     }
                   4405:     if ($ok_response) {
1.521     raeburn  4406:         return 'ok';
1.772     raeburn  4407:     } else {
                   4408:         return $response;
1.521     raeburn  4409:     }
                   4410: }
                   4411: 
1.792     raeburn  4412: sub auto_instcode_defaults {
                   4413:     my ($domain,$returnhash,$code_order) = @_;
                   4414:     my @homeservers;
1.793     albertel 4415:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4416:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4417:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4418:                 push(@homeservers,$tryserver);
                   4419:             }
                   4420:         }
                   4421:     }
                   4422:     my $ok_response = 0;
                   4423:     my $response;
                   4424:     while (@homeservers > 0 && $ok_response == 0) {
                   4425:         my $server = shift(@homeservers);
                   4426:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4427:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4428:             foreach my $pair (split(/\&/,$response)) {
                   4429:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4430:                 if ($name eq 'code_order') {
1.796     raeburn  4431:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4432:                 } else {
1.796     raeburn  4433:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4434:                 }
                   4435:             }
1.804     raeburn  4436:             $ok_response = 1;
1.792     raeburn  4437:         }
                   4438:     }
                   4439:     if ($ok_response) {
                   4440:         return 'ok';
                   4441:     } else {
                   4442:         return $response;
                   4443:     }
                   4444: } 
                   4445: 
1.777     albertel 4446: sub auto_validate_class_sec {
1.773     raeburn  4447:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4448:     my $homeserver = &homeserver($cnum,$cdom);
                   4449:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4450:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4451:     return $response;
                   4452: }
                   4453: 
1.679     raeburn  4454: # ------------------------------------------------------- Course Group routines
                   4455: 
                   4456: sub get_coursegroups {
1.809     raeburn  4457:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4458:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4459: }
                   4460: 
1.679     raeburn  4461: sub modify_coursegroup {
                   4462:     my ($cdom,$cnum,$groupsettings) = @_;
                   4463:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4464: }
                   4465: 
1.809     raeburn  4466: sub toggle_coursegroup_status {
                   4467:     my ($cdom,$cnum,$group,$action) = @_;
                   4468:     my ($from_namespace,$to_namespace);
                   4469:     if ($action eq 'delete') {
                   4470:         $from_namespace = 'coursegroups';
                   4471:         $to_namespace = 'deleted_groups';
                   4472:     } else {
                   4473:         $from_namespace = 'deleted_groups';
                   4474:         $to_namespace = 'coursegroups';
                   4475:     }
                   4476:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4477:     if (my $tmp = &error(%curr_group)) {
                   4478:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4479:         return ('read error',$tmp);
                   4480:     } else {
                   4481:         my %savedsettings = %curr_group; 
1.809     raeburn  4482:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4483:         my $deloutcome;
                   4484:         if ($result eq 'ok') {
1.809     raeburn  4485:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4486:         } else {
                   4487:             return ('write error',$result);
                   4488:         }
                   4489:         if ($deloutcome eq 'ok') {
                   4490:             return 'ok';
                   4491:         } else {
                   4492:             return ('delete error',$deloutcome);
                   4493:         }
                   4494:     }
                   4495: }
                   4496: 
1.679     raeburn  4497: sub modify_group_roles {
                   4498:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4499:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4500:     my $role = 'gr/'.&escape($userprivs);
                   4501:     my ($uname,$udom) = split(/:/,$user);
                   4502:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4503:     if ($result eq 'ok') {
                   4504:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4505:     }
1.679     raeburn  4506:     return $result;
                   4507: }
                   4508: 
                   4509: sub modify_coursegroup_membership {
                   4510:     my ($cdom,$cnum,$membership) = @_;
                   4511:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4512:     return $result;
                   4513: }
                   4514: 
1.682     raeburn  4515: sub get_active_groups {
                   4516:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4517:     my $now = time;
                   4518:     my %groups = ();
                   4519:     foreach my $key (keys(%env)) {
1.811     albertel 4520:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4521:             my ($start,$end) = split(/\./,$env{$key});
                   4522:             if (($end!=0) && ($end<$now)) { next; }
                   4523:             if (($start!=0) && ($start>$now)) { next; }
                   4524:             if ($1 eq $cdom && $2 eq $cnum) {
                   4525:                 $groups{$3} = $env{$key} ;
                   4526:             }
                   4527:         }
                   4528:     }
                   4529:     return %groups;
                   4530: }
                   4531: 
1.683     raeburn  4532: sub get_group_membership {
                   4533:     my ($cdom,$cnum,$group) = @_;
                   4534:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4535: }
                   4536: 
                   4537: sub get_users_groups {
                   4538:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4539:     my @usersgroups;
1.683     raeburn  4540:     my $cachetime=1800;
                   4541: 
                   4542:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4543:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4544:     if (defined($cached)) {
1.734     albertel 4545:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4546:     } else {  
                   4547:         $grouplist = '';
1.816     raeburn  4548:         my $courseurl = &courseid_to_courseurl($courseid);
                   4549:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4550:         my $access_end = $env{'course.'.$courseid.
                   4551:                               '.default_enrollment_end_date'};
                   4552:         my $now = time;
                   4553:         foreach my $key (keys(%roleshash)) {
                   4554:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4555:                 my $group = $1;
                   4556:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4557:                     my $start = $2;
                   4558:                     my $end = $1;
                   4559:                     if ($start == -1) { next; } # deleted from group
                   4560:                     if (($start!=0) && ($start>$now)) { next; }
                   4561:                     if (($end!=0) && ($end<$now)) {
                   4562:                         if ($access_end && $access_end < $now) {
                   4563:                             if ($access_end - $end < 86400) {
                   4564:                                 push(@usersgroups,$group);
1.733     raeburn  4565:                             }
                   4566:                         }
1.817     raeburn  4567:                         next;
1.733     raeburn  4568:                     }
1.817     raeburn  4569:                     push(@usersgroups,$group);
1.683     raeburn  4570:                 }
                   4571:             }
                   4572:         }
1.817     raeburn  4573:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4574:         $grouplist = join(':',@usersgroups);
                   4575:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4576:     }
1.733     raeburn  4577:     return @usersgroups;
1.683     raeburn  4578: }
                   4579: 
                   4580: sub devalidate_getgroups_cache {
                   4581:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4582:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4583: 
1.683     raeburn  4584:     my $hashid="$udom:$uname:$courseid";
                   4585:     &devalidate_cache_new('getgroups',$hashid);
                   4586: }
                   4587: 
1.12      www      4588: # ------------------------------------------------------------------ Plain Text
                   4589: 
                   4590: sub plaintext {
1.742     raeburn  4591:     my ($short,$type,$cid) = @_;
1.758     albertel 4592:     if ($short =~ /^cr/) {
                   4593: 	return (split('/',$short))[-1];
                   4594:     }
1.742     raeburn  4595:     if (!defined($cid)) {
                   4596:         $cid = $env{'request.course.id'};
                   4597:     }
                   4598:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4599:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4600:                                           '.plaintext'});
                   4601:     }
                   4602:     my %rolenames = (
                   4603:                       Course => 'std',
                   4604:                       Group => 'alt1',
                   4605:                     );
                   4606:     if (defined($type) && 
                   4607:          defined($rolenames{$type}) && 
                   4608:          defined($prp{$short}{$rolenames{$type}})) {
                   4609:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4610:     } else {
                   4611:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4612:     }
1.12      www      4613: }
                   4614: 
                   4615: # ----------------------------------------------------------------- Assign Role
                   4616: 
                   4617: sub assignrole {
1.357     www      4618:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4619:     my $mrole;
                   4620:     if ($role =~ /^cr\//) {
1.393     www      4621:         my $cwosec=$url;
1.811     albertel 4622:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4623: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4624:            &logthis('Refused custom assignrole: '.
                   4625:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4626: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4627:            return 'refused'; 
                   4628:         }
1.21      www      4629:         $mrole='cr';
1.678     raeburn  4630:     } elsif ($role =~ /^gr\//) {
                   4631:         my $cwogrp=$url;
1.811     albertel 4632:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4633:         unless (&allowed('mdg',$cwogrp)) {
                   4634:             &logthis('Refused group assignrole: '.
                   4635:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4636:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4637:             return 'refused';
                   4638:         }
                   4639:         $mrole='gr';
1.21      www      4640:     } else {
1.82      www      4641:         my $cwosec=$url;
1.811     albertel 4642:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4643:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4644:            &logthis('Refused assignrole: '.
                   4645:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4646: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4647:            return 'refused'; 
                   4648:         }
1.21      www      4649:         $mrole=$role;
                   4650:     }
1.620     albertel 4651:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4652:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4653:     if ($end) { $command.='_'.$end; }
1.21      www      4654:     if ($start) {
                   4655: 	if ($end) { 
1.81      www      4656:            $command.='_'.$start; 
1.21      www      4657:         } else {
1.81      www      4658:            $command.='_0_'.$start;
1.21      www      4659:         }
                   4660:     }
1.739     raeburn  4661:     my $origstart = $start;
                   4662:     my $origend = $end;
1.357     www      4663: # actually delete
                   4664:     if ($deleteflag) {
1.373     www      4665: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4666: # modify command to delete the role
1.620     albertel 4667:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4668:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4669: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4670: # set start and finish to negative values for userrolelog
                   4671:            $start=-1;
                   4672:            $end=-1;
                   4673:         }
                   4674:     }
                   4675: # send command
1.349     www      4676:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4677: # log new user role if status is ok
1.349     www      4678:     if ($answer eq 'ok') {
1.663     raeburn  4679: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4680: # for course roles, perform group memberships changes triggered by role change.
                   4681:         unless ($role =~ /^gr/) {
                   4682:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4683:                                              $origstart);
                   4684:         }
1.349     www      4685:     }
                   4686:     return $answer;
1.169     harris41 4687: }
                   4688: 
                   4689: # -------------------------------------------------- Modify user authentication
1.197     www      4690: # Overrides without validation
                   4691: 
1.169     harris41 4692: sub modifyuserauth {
                   4693:     my ($udom,$uname,$umode,$upass)=@_;
                   4694:     my $uhome=&homeserver($uname,$udom);
1.197     www      4695:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4696:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4697:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4698:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4699:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4700: 		     &escape($upass),$uhome);
1.620     albertel 4701:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4702:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4703:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4704:     &log($udom,,$uname,$uhome,
1.620     albertel 4705:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4706:                                      $env{'user.name'}.', '.$umode.
1.197     www      4707:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4708:     unless ($reply eq 'ok') {
1.197     www      4709:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4710: 	return 'error: '.$reply;
                   4711:     }   
1.170     harris41 4712:     return 'ok';
1.80      www      4713: }
                   4714: 
1.81      www      4715: # --------------------------------------------------------------- Modify a user
1.80      www      4716: 
1.81      www      4717: sub modifyuser {
1.206     matthew  4718:     my ($udom,    $uname, $uid,
                   4719:         $umode,   $upass, $first,
                   4720:         $middle,  $last,  $gene,
1.387     www      4721:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4722:     $udom= &LONCAPA::clean_domain($udom);
                   4723:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4724:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4725:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4726: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4727:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4728:                                      ' desiredhome not specified'). 
1.620     albertel 4729:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4730:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4731:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4732: # ----------------------------------------------------------------- Create User
1.406     albertel 4733:     if (($uhome eq 'no_host') && 
                   4734: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4735:         my $unhome='';
1.209     matthew  4736:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4737:             $unhome = $desiredhome;
1.620     albertel 4738: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4739: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4740:         } else { # load balancing routine for determining $unhome
1.80      www      4741:             my $tryserver;
1.81      www      4742:             my $loadm=10000000;
1.80      www      4743:             foreach $tryserver (keys %libserv) {
                   4744: 	       if ($hostdom{$tryserver} eq $udom) {
                   4745:                   my $answer=reply('load',$tryserver);
                   4746:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4747: 		      $loadm=$answer;
                   4748:                       $unhome=$tryserver;
                   4749:                   }
                   4750: 	       }
                   4751: 	    }
                   4752:         }
                   4753:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4754: 	    return 'error: unable to find a home server for '.$uname.
                   4755:                    ' in domain '.$udom;
1.80      www      4756:         }
                   4757:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4758:                          &escape($upass),$unhome);
                   4759: 	unless ($reply eq 'ok') {
                   4760:             return 'error: '.$reply;
                   4761:         }   
1.230     stredwic 4762:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4763:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4764: 	    return 'error: unable verify users home machine.';
1.80      www      4765:         }
1.209     matthew  4766:     }   # End of creation of new user
1.80      www      4767: # ---------------------------------------------------------------------- Add ID
                   4768:     if ($uid) {
                   4769:        $uid=~tr/A-Z/a-z/;
                   4770:        my %uidhash=&idrget($udom,$uname);
1.196     www      4771:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4772:          && (!$forceid)) {
1.80      www      4773: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4774: 	      return 'error: user id "'.$uid.'" does not match '.
                   4775:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4776:           }
                   4777:        } else {
                   4778: 	  &idput($udom,($uname => $uid));
                   4779:        }
                   4780:     }
                   4781: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4782:     my @tmp=&get('environment',
1.134     albertel 4783: 		   ['firstname','middlename','lastname','generation'],
                   4784: 		   $udom,$uname);
1.313     matthew  4785:     my %names;
                   4786:     if ($tmp[0] =~ m/^error:.*/) { 
                   4787:         %names=(); 
                   4788:     } else {
                   4789:         %names = @tmp;
                   4790:     }
1.388     www      4791: #
                   4792: # Make sure to not trash student environment if instructor does not bother
                   4793: # to supply name and email information
                   4794: #
                   4795:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4796:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4797:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4798:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4799:     if ($email) {
                   4800:        $email=~s/[^\w\@\.\-\,]//gs;
                   4801:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4802: 			   $names{'critnotification'} = $email;
                   4803: 			   $names{'permanentemail'} = $email; }
                   4804:     }
1.134     albertel 4805:     my $reply = &put('environment', \%names, $udom,$uname);
                   4806:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4807:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4808:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4809:              $umode.', '.$first.', '.$middle.', '.
                   4810: 	     $last.', '.$gene.' by '.
1.620     albertel 4811:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4812:     return 'ok';
1.80      www      4813: }
                   4814: 
1.81      www      4815: # -------------------------------------------------------------- Modify student
1.80      www      4816: 
1.81      www      4817: sub modifystudent {
                   4818:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4819:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4820:     if (!$cid) {
1.620     albertel 4821: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4822: 	    return 'not_in_class';
                   4823: 	}
1.80      www      4824:     }
                   4825: # --------------------------------------------------------------- Make the user
1.81      www      4826:     my $reply=&modifyuser
1.209     matthew  4827: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4828:          $desiredhome,$email);
1.80      www      4829:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4830:     # This will cause &modify_student_enrollment to get the uid from the
                   4831:     # students environment
                   4832:     $uid = undef if (!$forceid);
1.455     albertel 4833:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4834: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4835:     return $reply;
                   4836: }
                   4837: 
                   4838: sub modify_student_enrollment {
1.515     raeburn  4839:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4840:     my ($cdom,$cnum,$chome);
                   4841:     if (!$cid) {
1.620     albertel 4842: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4843: 	    return 'not_in_class';
                   4844: 	}
1.620     albertel 4845: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4846: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4847:     } else {
                   4848: 	($cdom,$cnum)=split(/_/,$cid);
                   4849:     }
1.620     albertel 4850:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4851:     if (!$chome) {
1.457     raeburn  4852: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4853:     }
1.455     albertel 4854:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4855:     # Make sure the user exists
1.81      www      4856:     my $uhome=&homeserver($uname,$udom);
                   4857:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4858: 	return 'error: no such user';
                   4859:     }
1.297     matthew  4860:     # Get student data if we were not given enough information
                   4861:     if (!defined($first)  || $first  eq '' || 
                   4862:         !defined($last)   || $last   eq '' || 
                   4863:         !defined($uid)    || $uid    eq '' || 
                   4864:         !defined($middle) || $middle eq '' || 
                   4865:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4866:         # They did not supply us with enough data to enroll the student, so
                   4867:         # we need to pick up more information.
1.297     matthew  4868:         my %tmp = &get('environment',
1.294     matthew  4869:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4870:                        ,$udom,$uname);
                   4871: 
1.800     albertel 4872:         #foreach my $key (keys(%tmp)) {
                   4873:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4874:         #}
1.294     matthew  4875:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4876:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4877:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4878:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4879:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4880:     }
1.556     albertel 4881:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4882:     my $reply=cput('classlist',
                   4883: 		   {"$uname:$udom" => 
1.515     raeburn  4884: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4885: 		   $cdom,$cnum);
1.81      www      4886:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4887: 	return 'error: '.$reply;
1.652     albertel 4888:     } else {
                   4889: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4890:     }
1.297     matthew  4891:     # Add student role to user
1.83      www      4892:     my $uurl='/'.$cid;
1.81      www      4893:     $uurl=~s/\_/\//g;
                   4894:     if ($usec) {
                   4895: 	$uurl.='/'.$usec;
                   4896:     }
                   4897:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4898: }
                   4899: 
1.556     albertel 4900: sub format_name {
                   4901:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4902:     my $name;
                   4903:     if ($first ne 'lastname') {
                   4904: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4905:     } else {
                   4906: 	if ($lastname=~/\S/) {
                   4907: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4908: 	    $name=~s/\s+,/,/;
                   4909: 	} else {
                   4910: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4911: 	}
                   4912:     }
                   4913:     $name=~s/^\s+//;
                   4914:     $name=~s/\s+$//;
                   4915:     $name=~s/\s+/ /g;
                   4916:     return $name;
                   4917: }
                   4918: 
1.84      www      4919: # ------------------------------------------------- Write to course preferences
                   4920: 
                   4921: sub writecoursepref {
                   4922:     my ($courseid,%prefs)=@_;
                   4923:     $courseid=~s/^\///;
                   4924:     $courseid=~s/\_/\//g;
                   4925:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4926:     my $chome=homeserver($cnum,$cdomain);
                   4927:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4928: 	return 'error: no such course';
                   4929:     }
                   4930:     my $cstring='';
1.800     albertel 4931:     foreach my $pref (keys(%prefs)) {
                   4932: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4933:     }
1.84      www      4934:     $cstring=~s/\&$//;
                   4935:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4936: }
                   4937: 
                   4938: # ---------------------------------------------------------- Make/modify course
                   4939: 
                   4940: sub createcourse {
1.741     raeburn  4941:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4942:         $course_owner,$crstype)=@_;
1.84      www      4943:     $url=&declutter($url);
                   4944:     my $cid='';
1.264     matthew  4945:     unless (&allowed('ccc',$udom)) {
1.84      www      4946:         return 'refused';
                   4947:     }
                   4948: # ------------------------------------------------------------------- Create ID
1.674     www      4949:    my $uname=int(1+rand(9)).
                   4950:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4951:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4952:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4953: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4954:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4955:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4956:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4957:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4958:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4959:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4960:            return 'error: unable to generate unique course-ID';
                   4961:        } 
                   4962:    }
1.264     matthew  4963: # ------------------------------------------------ Check supplied server name
1.620     albertel 4964:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4965:     if (! exists($libserv{$course_server})) {
                   4966:         return 'error:bad server name '.$course_server;
                   4967:     }
1.84      www      4968: # ------------------------------------------------------------- Make the course
                   4969:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4970:                       $course_server);
1.84      www      4971:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4972:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4973:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4974: 	return 'error: no such course';
                   4975:     }
1.271     www      4976: # ----------------------------------------------------------------- Course made
1.516     raeburn  4977: # log existence
                   4978:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4979:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4980:                   &escape($crstype),$uhome);
1.358     www      4981:     &flushcourselogs();
                   4982: # set toplevel url
1.271     www      4983:     my $topurl=$url;
                   4984:     unless ($nonstandard) {
                   4985: # ------------------------------------------ For standard courses, make top url
                   4986:         my $mapurl=&clutter($url);
1.278     www      4987:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4988:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4989: <map>
                   4990: <resource id="1" type="start"></resource>
                   4991: <resource id="2" src="$mapurl"></resource>
                   4992: <resource id="3" type="finish"></resource>
                   4993: <link index="1" from="1" to="2"></link>
                   4994: <link index="2" from="2" to="3"></link>
                   4995: </map>
                   4996: ENDINITMAP
                   4997:         $topurl=&declutter(
1.638     albertel 4998:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4999:                           );
                   5000:     }
                   5001: # ----------------------------------------------------------- Write preferences
1.84      www      5002:     &writecoursepref($udom.'_'.$uname,
                   5003:                      ('description' => $description,
1.271     www      5004:                       'url'         => $topurl));
1.84      www      5005:     return '/'.$udom.'/'.$uname;
                   5006: }
                   5007: 
1.813     albertel 5008: sub is_course {
                   5009:     my ($cdom,$cnum) = @_;
                   5010:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5011: 				undef,'.');
                   5012:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5013:         return 1;
                   5014:     }
                   5015:     return 0;
                   5016: }
                   5017: 
1.21      www      5018: # ---------------------------------------------------------- Assign Custom Role
                   5019: 
                   5020: sub assigncustomrole {
1.357     www      5021:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5022:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5023:                        $end,$start,$deleteflag);
1.21      www      5024: }
                   5025: 
                   5026: # ----------------------------------------------------------------- Revoke Role
                   5027: 
                   5028: sub revokerole {
1.357     www      5029:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5030:     my $now=time;
1.357     www      5031:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5032: }
                   5033: 
                   5034: # ---------------------------------------------------------- Revoke Custom Role
                   5035: 
                   5036: sub revokecustomrole {
1.357     www      5037:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5038:     my $now=time;
1.357     www      5039:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5040:            $deleteflag);
1.17      www      5041: }
                   5042: 
1.533     banghart 5043: # ------------------------------------------------------------ Disk usage
1.535     albertel 5044: sub diskusage {
1.533     banghart 5045:     my ($udom,$uname,$directoryRoot)=@_;
                   5046:     $directoryRoot =~ s/\/$//;
1.535     albertel 5047:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5048:     return $listing;
1.512     banghart 5049: }
                   5050: 
1.566     banghart 5051: sub is_locked {
                   5052:     my ($file_name, $domain, $user) = @_;
                   5053:     my @check;
                   5054:     my $is_locked;
                   5055:     push @check, $file_name;
1.613     albertel 5056:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5057: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5058:     my ($tmp)=keys(%locked);
                   5059:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5060:     
1.566     banghart 5061:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5062:         $is_locked = 'false';
                   5063:         foreach my $entry (@{$locked{$file_name}}) {
                   5064:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5065:                $is_locked = 'true';
                   5066:                last;
1.745     raeburn  5067:            }
                   5068:        }
1.566     banghart 5069:     } else {
                   5070:         $is_locked = 'false';
                   5071:     }
                   5072: }
                   5073: 
1.759     albertel 5074: sub declutter_portfile {
                   5075:     my ($file) = @_;
                   5076:     &logthis("got $file");
                   5077:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5078:     &logthis("ret $file");
                   5079:     return $file;
                   5080: }
                   5081: 
1.559     banghart 5082: # ------------------------------------------------------------- Mark as Read Only
                   5083: 
                   5084: sub mark_as_readonly {
                   5085:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5086:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5087:     my ($tmp)=keys(%current_permissions);
                   5088:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5089:     foreach my $file (@{$files}) {
1.759     albertel 5090: 	$file = &declutter_portfile($file);
1.561     banghart 5091:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5092:     }
1.613     albertel 5093:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5094:     return;
                   5095: }
                   5096: 
1.572     banghart 5097: # ------------------------------------------------------------Save Selected Files
                   5098: 
                   5099: sub save_selected_files {
                   5100:     my ($user, $path, @files) = @_;
                   5101:     my $filename = $user."savedfiles";
1.573     banghart 5102:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5103:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5104:     foreach my $file (@files) {
1.620     albertel 5105:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5106:     }
                   5107:     foreach my $file (@other_files) {
1.574     banghart 5108:         print (OUT $file."\n");
1.572     banghart 5109:     }
1.574     banghart 5110:     close (OUT);
1.572     banghart 5111:     return 'ok';
                   5112: }
                   5113: 
1.574     banghart 5114: sub clear_selected_files {
                   5115:     my ($user) = @_;
                   5116:     my $filename = $user."savedfiles";
                   5117:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5118:     print (OUT undef);
                   5119:     close (OUT);
                   5120:     return ("ok");    
                   5121: }
                   5122: 
1.572     banghart 5123: sub files_in_path {
                   5124:     my ($user, $path) = @_;
                   5125:     my $filename = $user."savedfiles";
                   5126:     my %return_files;
1.574     banghart 5127:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5128:     while (my $line_in = <IN>) {
1.574     banghart 5129:         chomp ($line_in);
                   5130:         my @paths_and_file = split (m!/!, $line_in);
                   5131:         my $file_part = pop (@paths_and_file);
                   5132:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5133:         $path_part.='/';
                   5134:         my $path_and_file = $path_part.$file_part;
                   5135:         if ($path_part eq $path) {
                   5136:             $return_files{$file_part}= 'selected';
                   5137:         }
                   5138:     }
1.574     banghart 5139:     close (IN);
                   5140:     return (\%return_files);
1.572     banghart 5141: }
                   5142: 
                   5143: # called in portfolio select mode, to show files selected NOT in current directory
                   5144: sub files_not_in_path {
                   5145:     my ($user, $path) = @_;
                   5146:     my $filename = $user."savedfiles";
                   5147:     my @return_files;
                   5148:     my $path_part;
1.800     albertel 5149:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5150:     while (my $line = <IN>) {
1.572     banghart 5151:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5152:         my @paths_and_file = split(m|/|, $line);
                   5153:         my $file_part = pop(@paths_and_file);
                   5154:         chomp($file_part);
                   5155:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5156:         $path_part .= '/';
                   5157:         my $path_and_file = $path_part.$file_part;
                   5158:         if ($path_part ne $path) {
1.800     albertel 5159:             push(@return_files, ($path_and_file));
1.572     banghart 5160:         }
                   5161:     }
1.800     albertel 5162:     close(OUT);
1.574     banghart 5163:     return (@return_files);
1.572     banghart 5164: }
                   5165: 
1.745     raeburn  5166: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5167: 
1.745     raeburn  5168: sub get_portfile_permissions {
                   5169:     my ($domain,$user) = @_;
1.613     albertel 5170:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5171:     my ($tmp)=keys(%current_permissions);
                   5172:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5173:     return \%current_permissions;
                   5174: }
                   5175: 
                   5176: #---------------------------------------------Get portfolio file access controls
                   5177: 
1.749     raeburn  5178: sub get_access_controls {
1.745     raeburn  5179:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5180:     my %access;
                   5181:     my $real_file = $file;
                   5182:     $file =~ s/\.meta$//;
1.745     raeburn  5183:     if (defined($file)) {
1.749     raeburn  5184:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5185:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5186:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5187:             }
                   5188:         }
1.745     raeburn  5189:     } else {
1.749     raeburn  5190:         foreach my $key (keys(%{$current_permissions})) {
                   5191:             if ($key =~ /\0accesscontrol$/) {
                   5192:                 if (defined($group)) {
                   5193:                     if ($key !~ m-^\Q$group\E/-) {
                   5194:                         next;
                   5195:                     }
                   5196:                 }
                   5197:                 my ($fullpath) = split(/\0/,$key);
                   5198:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5199:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5200:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5201:                     }
                   5202:                 }
                   5203:             }
                   5204:         }
                   5205:     }
                   5206:     return %access;
                   5207: }
                   5208: 
                   5209: sub modify_access_controls {
                   5210:     my ($file_name,$changes,$domain,$user)=@_;
                   5211:     my ($outcome,$deloutcome);
                   5212:     my %store_permissions;
                   5213:     my %new_values;
                   5214:     my %new_control;
                   5215:     my %translation;
                   5216:     my @deletions = ();
                   5217:     my $now = time;
                   5218:     if (exists($$changes{'activate'})) {
                   5219:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5220:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5221:             my $numnew = scalar(@newitems);
                   5222:             for (my $i=0; $i<$numnew; $i++) {
                   5223:                 my $newkey = $newitems[$i];
                   5224:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5225:                 if ($newkey =~ /^\d+:/) { 
                   5226:                     $newkey =~ s/^(\d+)/$newid/;
                   5227:                     $translation{$1} = $newid;
                   5228:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5229:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5230:                     $translation{$1} = $newid;
                   5231:                 }
1.749     raeburn  5232:                 $new_values{$file_name."\0".$newkey} = 
                   5233:                                           $$changes{'activate'}{$newitems[$i]};
                   5234:                 $new_control{$newkey} = $now;
                   5235:             }
                   5236:         }
                   5237:     }
                   5238:     my %todelete;
                   5239:     my %changed_items;
                   5240:     foreach my $action ('delete','update') {
                   5241:         if (exists($$changes{$action})) {
                   5242:             if (ref($$changes{$action}) eq 'HASH') {
                   5243:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5244:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5245:                     if ($action eq 'delete') { 
                   5246:                         $todelete{$itemnum} = 1;
                   5247:                     } else {
                   5248:                         $changed_items{$itemnum} = $key;
                   5249:                     }
                   5250:                 }
1.745     raeburn  5251:             }
                   5252:         }
1.749     raeburn  5253:     }
                   5254:     # get lock on access controls for file.
                   5255:     my $lockhash = {
                   5256:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5257:                                                        ':'.$env{'user.domain'},
                   5258:                    }; 
                   5259:     my $tries = 0;
                   5260:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5261:    
                   5262:     while (($gotlock ne 'ok') && $tries <3) {
                   5263:         $tries ++;
                   5264:         sleep 1;
                   5265:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5266:     }
                   5267:     if ($gotlock eq 'ok') {
                   5268:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5269:         my ($tmp)=keys(%curr_permissions);
                   5270:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5271:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5272:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5273:             if (ref($curr_controls) eq 'HASH') {
                   5274:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5275:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5276:                     if (defined($todelete{$itemnum})) {
                   5277:                         push(@deletions,$file_name."\0".$control_item);
                   5278:                     } else {
                   5279:                         if (defined($changed_items{$itemnum})) {
                   5280:                             $new_control{$changed_items{$itemnum}} = $now;
                   5281:                             push(@deletions,$file_name."\0".$control_item);
                   5282:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5283:                         } else {
                   5284:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5285:                         }
                   5286:                     }
1.745     raeburn  5287:                 }
                   5288:             }
                   5289:         }
1.749     raeburn  5290:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5291:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5292:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5293:         #  remove lock
                   5294:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5295:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5296:         my ($file,$group);
                   5297:         if (&is_course($domain,$user)) {
                   5298:             ($group,$file) = split(/\//,$file_name,2);
                   5299:         } else {
                   5300:             $file = $file_name;
                   5301:         }
                   5302:         my $sqlresult =
                   5303:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5304:                                     $group);
1.749     raeburn  5305:     } else {
                   5306:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5307:     }
1.749     raeburn  5308:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5309: }
                   5310: 
                   5311: #------------------------------------------------------Get Marked as Read Only
                   5312: 
                   5313: sub get_marked_as_readonly {
                   5314:     my ($domain,$user,$what,$group) = @_;
                   5315:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5316:     my @readonly_files;
1.629     banghart 5317:     my $cmp1=$what;
                   5318:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5319:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5320:         if (defined($group)) {
                   5321:             if ($file_name !~ m-^\Q$group\E/-) {
                   5322:                 next;
                   5323:             }
                   5324:         }
1.561     banghart 5325:         if (ref($value) eq "ARRAY"){
                   5326:             foreach my $stored_what (@{$value}) {
1.629     banghart 5327:                 my $cmp2=$stored_what;
1.759     albertel 5328:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5329:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5330:                 }
1.629     banghart 5331:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5332:                     push(@readonly_files, $file_name);
1.745     raeburn  5333:                     last;
1.563     banghart 5334:                 } elsif (!defined($what)) {
                   5335:                     push(@readonly_files, $file_name);
1.745     raeburn  5336:                     last;
1.561     banghart 5337:                 }
                   5338:             }
1.745     raeburn  5339:         }
1.561     banghart 5340:     }
                   5341:     return @readonly_files;
                   5342: }
1.577     banghart 5343: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5344: 
1.577     banghart 5345: sub get_marked_as_readonly_hash {
1.745     raeburn  5346:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5347:     my %readonly_files;
1.745     raeburn  5348:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5349:         if (defined($group)) {
                   5350:             if ($file_name !~ m-^\Q$group\E/-) {
                   5351:                 next;
                   5352:             }
                   5353:         }
1.577     banghart 5354:         if (ref($value) eq "ARRAY"){
                   5355:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5356:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5357:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5358:                         if ($lock_descriptor eq 'graded') {
                   5359:                             $readonly_files{$file_name} = 'graded';
                   5360:                         } elsif ($lock_descriptor eq 'handback') {
                   5361:                             $readonly_files{$file_name} = 'handback';
                   5362:                         } else {
                   5363:                             if (!exists($readonly_files{$file_name})) {
                   5364:                                 $readonly_files{$file_name} = 'locked';
                   5365:                             }
                   5366:                         }
1.745     raeburn  5367:                     }
1.750     banghart 5368:                 } 
1.577     banghart 5369:             }
                   5370:         } 
                   5371:     }
                   5372:     return %readonly_files;
                   5373: }
1.559     banghart 5374: # ------------------------------------------------------------ Unmark as Read Only
                   5375: 
                   5376: sub unmark_as_readonly {
1.629     banghart 5377:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5378:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5379:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5380:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5381:     my $symb_crs = $what;
                   5382:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5383:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5384:     my ($tmp)=keys(%current_permissions);
                   5385:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5386:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5387:     foreach my $file (@readonly_files) {
1.759     albertel 5388: 	my $clean_file = &declutter_portfile($file);
                   5389: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5390: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5391:         my @new_locks;
                   5392:         my @del_keys;
                   5393:         if (ref($current_locks) eq "ARRAY"){
                   5394:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5395:                 my $compare=$locker;
1.749     raeburn  5396:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5397:                     $compare=join('',@{$locker});
1.746     raeburn  5398:                     if ($compare ne $symb_crs) {
                   5399:                         push(@new_locks, $locker);
                   5400:                     }
1.563     banghart 5401:                 }
                   5402:             }
1.650     albertel 5403:             if (scalar(@new_locks) > 0) {
1.563     banghart 5404:                 $current_permissions{$file} = \@new_locks;
                   5405:             } else {
                   5406:                 push(@del_keys, $file);
1.613     albertel 5407:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5408:                 delete($current_permissions{$file});
1.563     banghart 5409:             }
                   5410:         }
1.561     banghart 5411:     }
1.613     albertel 5412:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5413:     return;
                   5414: }
1.512     banghart 5415: 
1.17      www      5416: # ------------------------------------------------------------ Directory lister
                   5417: 
                   5418: sub dirlist {
1.253     stredwic 5419:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5420: 
1.18      www      5421:     $uri=~s/^\///;
                   5422:     $uri=~s/\/$//;
1.253     stredwic 5423:     my ($udom, $uname);
                   5424:     (undef,$udom,$uname)=split(/\//,$uri);
                   5425:     if(defined($userdomain)) {
                   5426:         $udom = $userdomain;
                   5427:     }
                   5428:     if(defined($username)) {
                   5429:         $uname = $username;
                   5430:     }
                   5431: 
                   5432:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5433:     if(defined($alternateDirectoryRoot)) {
                   5434:         $dirRoot = $alternateDirectoryRoot;
                   5435:         $dirRoot =~ s/\/$//;
1.751     banghart 5436:     }
1.253     stredwic 5437: 
                   5438:     if($udom) {
                   5439:         if($uname) {
1.800     albertel 5440:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5441: 				 &homeserver($uname,$udom));
1.605     matthew  5442:             my @listing_results;
                   5443:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5444:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5445: 				  &homeserver($uname,$udom));
1.605     matthew  5446:                 @listing_results = split(/:/,$listing);
                   5447:             } else {
                   5448:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5449:             }
                   5450:             return @listing_results;
1.253     stredwic 5451:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5452:             my %allusers;
                   5453:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5454:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5455:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5456: 					 $udom, $tryserver);
1.605     matthew  5457:                     my @listing_results;
                   5458:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5459:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5460: 					  $udom, $tryserver);
1.605     matthew  5461:                         @listing_results = split(/:/,$listing);
                   5462:                     } else {
                   5463:                         @listing_results =
                   5464:                             map { &unescape($_); } split(/:/,$listing);
                   5465:                     }
                   5466:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5467:                         $listing_results[0] ne 'empty'       &&
                   5468:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5469:                         foreach my $line (@listing_results) {
                   5470:                             my ($entry) = split(/&/,$line,2);
                   5471:                             $allusers{$entry} = 1;
1.253     stredwic 5472:                         }
                   5473:                     }
1.191     harris41 5474:                 }
1.253     stredwic 5475:             }
                   5476:             my $alluserstr='';
1.800     albertel 5477:             foreach my $user (sort(keys(%allusers))) {
                   5478:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5479:             }
                   5480:             $alluserstr=~s/:$//;
                   5481:             return split(/:/,$alluserstr);
                   5482:         } else {
1.800     albertel 5483:             return ('missing user name');
1.253     stredwic 5484:         }
                   5485:     } elsif(!defined($alternateDirectoryRoot)) {
                   5486:         my $tryserver;
                   5487:         my %alldom=();
1.800     albertel 5488:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5489:             $alldom{$hostdom{$tryserver}}=1;
                   5490:         }
                   5491:         my $alldomstr='';
1.800     albertel 5492:         foreach my $domain (sort(keys(%alldom))) {
                   5493:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5494:         }
                   5495:         $alldomstr=~s/:$//;
                   5496:         return split(/:/,$alldomstr);       
                   5497:     } else {
1.800     albertel 5498:         return ('missing domain');
1.275     stredwic 5499:     }
                   5500: }
                   5501: 
                   5502: # --------------------------------------------- GetFileTimestamp
                   5503: # This function utilizes dirlist and returns the date stamp for
                   5504: # when it was last modified.  It will also return an error of -1
                   5505: # if an error occurs
                   5506: 
1.410     matthew  5507: ##
                   5508: ## FIXME: This subroutine assumes its caller knows something about the
                   5509: ## directory structure of the home server for the student ($root).
                   5510: ## Not a good assumption to make.  Since this is for looking up files
                   5511: ## in user directories, the full path should be constructed by lond, not
                   5512: ## whatever machine we request data from.
                   5513: ##
1.275     stredwic 5514: sub GetFileTimestamp {
                   5515:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5516:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5517:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5518:     my $subdir=$studentName.'__';
                   5519:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5520:     my $proname="$studentDomain/$subdir/$studentName";
                   5521:     $proname .= '/'.$filename;
1.375     matthew  5522:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5523:                                               $studentName, $root);
1.275     stredwic 5524:     my @stats = split('&', $fileStat);
                   5525:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5526:         # @stats contains first the filename, then the stat output
                   5527:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5528:     } else {
                   5529:         return -1;
1.253     stredwic 5530:     }
1.26      www      5531: }
                   5532: 
1.712     albertel 5533: sub stat_file {
                   5534:     my ($uri) = @_;
1.787     albertel 5535:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5536: 
1.712     albertel 5537:     my ($udom,$uname,$file,$dir);
                   5538:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5539: 	($udom,$uname,$file) =
1.811     albertel 5540: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5541: 	$file = 'userfiles/'.$file;
1.740     www      5542: 	$dir = &propath($udom,$uname);
1.712     albertel 5543:     }
                   5544:     if ($uri =~ m-^/res/-) {
                   5545: 	($udom,$uname) = 
1.807     albertel 5546: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5547: 	$file = $uri;
                   5548:     }
                   5549: 
                   5550:     if (!$udom || !$uname || !$file) {
                   5551: 	# unable to handle the uri
                   5552: 	return ();
                   5553:     }
                   5554: 
                   5555:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5556:     my @stats = split('&', $result);
1.721     banghart 5557:     
1.712     albertel 5558:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5559: 	shift(@stats); #filename is first
                   5560: 	return @stats;
                   5561:     }
                   5562:     return ();
                   5563: }
                   5564: 
1.26      www      5565: # -------------------------------------------------------- Value of a Condition
                   5566: 
1.713     albertel 5567: # gets the value of a specific preevaluated condition
                   5568: #    stored in the string  $env{user.state.<cid>}
                   5569: # or looks up a condition reference in the bighash and if if hasn't
                   5570: # already been evaluated recurses into docondval to get the value of
                   5571: # the condition, then memoizing it to 
                   5572: #   $env{user.state.<cid>.<condition>}
1.40      www      5573: sub directcondval {
                   5574:     my $number=shift;
1.620     albertel 5575:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5576: 	&Apache::lonuserstate::evalstate();
                   5577:     }
1.713     albertel 5578:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5579: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5580:     } elsif ($number =~ /^_/) {
                   5581: 	my $sub_condition;
                   5582: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5583: 		&GDBM_READER(),0640)) {
                   5584: 	    $sub_condition=$bighash{'conditions'.$number};
                   5585: 	    untie(%bighash);
                   5586: 	}
                   5587: 	my $value = &docondval($sub_condition);
                   5588: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5589: 	return $value;
                   5590:     }
1.620     albertel 5591:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5592:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5593:     } else {
                   5594:        return 2;
                   5595:     }
                   5596: }
                   5597: 
1.713     albertel 5598: # get the collection of conditions for this resource
1.26      www      5599: sub condval {
                   5600:     my $condidx=shift;
1.54      www      5601:     my $allpathcond='';
1.713     albertel 5602:     foreach my $cond (split(/\|/,$condidx)) {
                   5603: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5604: 	    $allpathcond.=
                   5605: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5606: 	}
1.191     harris41 5607:     }
1.54      www      5608:     $allpathcond=~s/\|$//;
1.713     albertel 5609:     return &docondval($allpathcond);
                   5610: }
                   5611: 
                   5612: #evaluates an expression of conditions
                   5613: sub docondval {
                   5614:     my ($allpathcond) = @_;
                   5615:     my $result=0;
                   5616:     if ($env{'request.course.id'}
                   5617: 	&& defined($allpathcond)) {
                   5618: 	my $operand='|';
                   5619: 	my @stack;
                   5620: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5621: 	    if ($chunk eq '(') {
                   5622: 		push @stack,($operand,$result);
                   5623: 	    } elsif ($chunk eq ')') {
                   5624: 		my $before=pop @stack;
                   5625: 		if (pop @stack eq '&') {
                   5626: 		    $result=$result>$before?$before:$result;
                   5627: 		} else {
                   5628: 		    $result=$result>$before?$result:$before;
                   5629: 		}
                   5630: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5631: 		$operand=$chunk;
                   5632: 	    } else {
                   5633: 		my $new=directcondval($chunk);
                   5634: 		if ($operand eq '&') {
                   5635: 		    $result=$result>$new?$new:$result;
                   5636: 		} else {
                   5637: 		    $result=$result>$new?$result:$new;
                   5638: 		}
                   5639: 	    }
                   5640: 	}
1.26      www      5641:     }
                   5642:     return $result;
1.421     albertel 5643: }
                   5644: 
                   5645: # ---------------------------------------------------- Devalidate courseresdata
                   5646: 
                   5647: sub devalidatecourseresdata {
                   5648:     my ($coursenum,$coursedomain)=@_;
                   5649:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5650:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5651: }
                   5652: 
1.763     www      5653: 
1.200     www      5654: # --------------------------------------------------- Course Resourcedata Query
                   5655: 
1.624     albertel 5656: sub get_courseresdata {
                   5657:     my ($coursenum,$coursedomain)=@_;
1.200     www      5658:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5659:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5660:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5661:     my %dumpreply;
1.417     albertel 5662:     unless (defined($cached)) {
1.624     albertel 5663: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5664: 	$result=\%dumpreply;
1.251     albertel 5665: 	my ($tmp) = keys(%dumpreply);
                   5666: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5667: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5668: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5669: 	    return $tmp;
1.416     albertel 5670: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5671: 	    $result=undef;
1.599     albertel 5672: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5673: 	}
                   5674:     }
1.624     albertel 5675:     return $result;
                   5676: }
                   5677: 
1.633     albertel 5678: sub devalidateuserresdata {
                   5679:     my ($uname,$udom)=@_;
                   5680:     my $hashid="$udom:$uname";
                   5681:     &devalidate_cache_new('userres',$hashid);
                   5682: }
                   5683: 
1.624     albertel 5684: sub get_userresdata {
                   5685:     my ($uname,$udom)=@_;
                   5686:     #most student don\'t have any data set, check if there is some data
                   5687:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5688: 
                   5689:     my $hashid="$udom:$uname";
                   5690:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5691:     if (!defined($cached)) {
                   5692: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5693: 	$result=\%resourcedata;
                   5694: 	&do_cache_new('userres',$hashid,$result,600);
                   5695:     }
                   5696:     my ($tmp)=keys(%$result);
                   5697:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5698: 	return $result;
                   5699:     }
                   5700:     #error 2 occurs when the .db doesn't exist
                   5701:     if ($tmp!~/error: 2 /) {
1.672     albertel 5702: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5703: 		 " Trying to get resource data for ".
                   5704: 		 $uname." at ".$udom.": ".
                   5705: 		 $tmp."</font>");
                   5706:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5707: 	#&EXT_cache_set($udom,$uname);
                   5708: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5709: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5710:     }
                   5711:     return $tmp;
                   5712: }
                   5713: 
                   5714: sub resdata {
                   5715:     my ($name,$domain,$type,@which)=@_;
                   5716:     my $result;
                   5717:     if ($type eq 'course') {
                   5718: 	$result=&get_courseresdata($name,$domain);
                   5719:     } elsif ($type eq 'user') {
                   5720: 	$result=&get_userresdata($name,$domain);
                   5721:     }
                   5722:     if (!ref($result)) { return $result; }    
1.251     albertel 5723:     foreach my $item (@which) {
1.417     albertel 5724: 	if (defined($result->{$item})) {
                   5725: 	    return $result->{$item};
1.251     albertel 5726: 	}
1.250     albertel 5727:     }
1.291     albertel 5728:     return undef;
1.200     www      5729: }
                   5730: 
1.379     matthew  5731: #
                   5732: # EXT resource caching routines
                   5733: #
                   5734: 
                   5735: sub clear_EXT_cache_status {
1.383     albertel 5736:     &delenv('cache.EXT.');
1.379     matthew  5737: }
                   5738: 
                   5739: sub EXT_cache_status {
                   5740:     my ($target_domain,$target_user) = @_;
1.383     albertel 5741:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5742:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5743:         # We know already the user has no data
                   5744:         return 1;
                   5745:     } else {
                   5746:         return 0;
                   5747:     }
                   5748: }
                   5749: 
                   5750: sub EXT_cache_set {
                   5751:     my ($target_domain,$target_user) = @_;
1.383     albertel 5752:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5753:     #&appenv($cachename => time);
1.379     matthew  5754: }
                   5755: 
1.28      www      5756: # --------------------------------------------------------- Value of a Variable
1.58      www      5757: sub EXT {
1.715     albertel 5758: 
1.395     albertel 5759:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5760:     unless ($varname) { return ''; }
1.218     albertel 5761:     #get real user name/domain, courseid and symb
                   5762:     my $courseid;
1.359     albertel 5763:     my $publicuser;
1.427     www      5764:     if ($symbparm) {
                   5765: 	$symbparm=&get_symb_from_alias($symbparm);
                   5766:     }
1.218     albertel 5767:     if (!($uname && $udom)) {
1.790     albertel 5768:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5769:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5770:     } else {
1.620     albertel 5771: 	$courseid=$env{'request.course.id'};
1.218     albertel 5772:     }
1.48      www      5773:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5774:     my $rest;
1.320     albertel 5775:     if (defined($therest[0])) {
1.48      www      5776:        $rest=join('.',@therest);
                   5777:     } else {
                   5778:        $rest='';
                   5779:     }
1.320     albertel 5780: 
1.57      www      5781:     my $qualifierrest=$qualifier;
                   5782:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5783:     my $spacequalifierrest=$space;
                   5784:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5785:     if ($realm eq 'user') {
1.48      www      5786: # --------------------------------------------------------------- user.resource
                   5787: 	if ($space eq 'resource') {
1.651     albertel 5788: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5789: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5790: 		 &&
1.744     albertel 5791: 		 ($symbparm eq &symbread()) ) {	
                   5792: 		# if we are in the middle of processing the resource the
                   5793: 		# get the value we are planning on committing
                   5794:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5795:                     return $Apache::lonhomework::results{$qualifierrest};
                   5796:                 } else {
                   5797:                     return $Apache::lonhomework::history{$qualifierrest};
                   5798:                 }
1.335     albertel 5799: 	    } else {
1.359     albertel 5800: 		my %restored;
1.620     albertel 5801: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5802: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5803: 		} else {
                   5804: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5805: 		}
1.335     albertel 5806: 		return $restored{$qualifierrest};
                   5807: 	    }
1.48      www      5808: # ----------------------------------------------------------------- user.access
                   5809:         } elsif ($space eq 'access') {
1.218     albertel 5810: 	    # FIXME - not supporting calls for a specific user
1.48      www      5811:             return &allowed($qualifier,$rest);
                   5812: # ------------------------------------------ user.preferences, user.environment
                   5813:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5814: 	    if (($uname eq $env{'user.name'}) &&
                   5815: 		($udom eq $env{'user.domain'})) {
                   5816: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5817: 	    } else {
1.359     albertel 5818: 		my %returnhash;
                   5819: 		if (!$publicuser) {
                   5820: 		    %returnhash=&userenvironment($udom,$uname,
                   5821: 						 $qualifierrest);
                   5822: 		}
1.218     albertel 5823: 		return $returnhash{$qualifierrest};
                   5824: 	    }
1.48      www      5825: # ----------------------------------------------------------------- user.course
                   5826:         } elsif ($space eq 'course') {
1.218     albertel 5827: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5828:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5829: # ------------------------------------------------------------------- user.role
                   5830:         } elsif ($space eq 'role') {
1.218     albertel 5831: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5832:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5833:             if ($qualifier eq 'value') {
                   5834: 		return $role;
                   5835:             } elsif ($qualifier eq 'extent') {
                   5836:                 return $where;
                   5837:             }
                   5838: # ----------------------------------------------------------------- user.domain
                   5839:         } elsif ($space eq 'domain') {
1.218     albertel 5840:             return $udom;
1.48      www      5841: # ------------------------------------------------------------------- user.name
                   5842:         } elsif ($space eq 'name') {
1.218     albertel 5843:             return $uname;
1.48      www      5844: # ---------------------------------------------------- Any other user namespace
1.29      www      5845:         } else {
1.359     albertel 5846: 	    my %reply;
                   5847: 	    if (!$publicuser) {
                   5848: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5849: 	    }
                   5850: 	    return $reply{$qualifierrest};
1.48      www      5851:         }
1.236     www      5852:     } elsif ($realm eq 'query') {
                   5853: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5854:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5855: 						[$spacequalifierrest]);
1.620     albertel 5856: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5857:    } elsif ($realm eq 'request') {
1.48      www      5858: # ------------------------------------------------------------- request.browser
                   5859:         if ($space eq 'browser') {
1.430     www      5860: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5861: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5862: 		    return 1;
                   5863: 		} else {
                   5864: 		    return 0;
                   5865: 		}
                   5866: 	    } else {
1.620     albertel 5867: 		return $env{'browser.'.$qualifier};
1.430     www      5868: 	    }
1.57      www      5869: # ------------------------------------------------------------ request.filename
                   5870:         } else {
1.620     albertel 5871:             return $env{'request.'.$spacequalifierrest};
1.29      www      5872:         }
1.28      www      5873:     } elsif ($realm eq 'course') {
1.48      www      5874: # ---------------------------------------------------------- course.description
1.620     albertel 5875:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5876:     } elsif ($realm eq 'resource') {
1.165     www      5877: 
1.620     albertel 5878: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5879: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5880: 	}
1.693     albertel 5881: 
                   5882: 	if ($space eq 'title') {
                   5883: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5884: 	    return &gettitle($symbparm);
                   5885: 	}
                   5886: 	
                   5887: 	if ($space eq 'map') {
                   5888: 	    my ($map) = &decode_symb($symbparm);
                   5889: 	    return &symbread($map);
                   5890: 	}
                   5891: 
                   5892: 	my ($section, $group, @groups);
1.593     albertel 5893: 	my ($courselevelm,$courselevel);
1.539     albertel 5894: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5895: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5896: 
1.218     albertel 5897: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5898: 
1.60      www      5899: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5900: 	    my $symbp=$symbparm;
1.735     albertel 5901: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5902: 
                   5903: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5904: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5905: 
1.620     albertel 5906: 	    if (($env{'user.name'} eq $uname) &&
                   5907: 		($env{'user.domain'} eq $udom)) {
                   5908: 		$section=$env{'request.course.sec'};
1.733     raeburn  5909:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5910:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5911: 	    } else {
1.539     albertel 5912: 		if (! defined($usection)) {
1.551     albertel 5913: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5914: 		} else {
                   5915: 		    $section = $usection;
                   5916: 		}
1.733     raeburn  5917:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5918: 	    }
                   5919: 
                   5920: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5921: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5922: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5923: 
1.593     albertel 5924: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5925: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5926: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5927: 
1.60      www      5928: # ----------------------------------------------------------- first, check user
1.624     albertel 5929: 
                   5930: 	    my $userreply=&resdata($uname,$udom,'user',
                   5931: 				       ($courselevelr,$courselevelm,
                   5932: 					$courselevel));
                   5933: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5934: 
1.594     albertel 5935: # ------------------------------------------------ second, check some of course
1.684     raeburn  5936:             my $coursereply;
1.691     raeburn  5937:             if (@groups > 0) {
                   5938:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5939:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5940:                 if (defined($coursereply)) { return $coursereply; }
                   5941:             }
1.96      www      5942: 
1.684     raeburn  5943: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5944: 				     $env{'course.'.$courseid.'.domain'},
                   5945: 				     'course',
                   5946: 				     ($seclevelr,$seclevelm,$seclevel,
                   5947: 				      $courselevelr));
1.287     albertel 5948: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5949: 
1.60      www      5950: # ------------------------------------------------------ third, check map parms
1.218     albertel 5951: 	    my %parmhash=();
                   5952: 	    my $thisparm='';
                   5953: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5954: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5955: 		    &GDBM_READER(),0640)) {
1.218     albertel 5956: 		$thisparm=$parmhash{$symbparm};
                   5957: 		untie(%parmhash);
                   5958: 	    }
                   5959: 	    if ($thisparm) { return $thisparm; }
                   5960: 	}
1.594     albertel 5961: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5962: 
1.218     albertel 5963: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5964: 	my $filename;
                   5965: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5966: 	if ($symbparm) {
1.409     www      5967: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5968: 	} else {
1.620     albertel 5969: 	    $filename=$env{'request.filename'};
1.282     albertel 5970: 	}
                   5971: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5972: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5973: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5974: 	if (defined($metadata)) { return $metadata; }
1.142     www      5975: 
1.594     albertel 5976: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5977: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5978: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5979: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5980: 				     $env{'course.'.$courseid.'.domain'},
                   5981: 				     'course',
                   5982: 				     ($courselevelm,$courselevel));
1.593     albertel 5983: 	    if (defined($coursereply)) { return $coursereply; }
                   5984: 	}
1.145     www      5985: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5986: 	unless ($space eq '0') {
1.336     albertel 5987: 	    my @parts=split(/_/,$space);
                   5988: 	    my $id=pop(@parts);
                   5989: 	    my $part=join('_',@parts);
                   5990: 	    if ($part eq '') { $part='0'; }
                   5991: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5992: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5993: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5994: 	}
1.395     albertel 5995: 	if ($recurse) { return undef; }
                   5996: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5997: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5998: 
1.48      www      5999: # ---------------------------------------------------- Any other user namespace
                   6000:     } elsif ($realm eq 'environment') {
                   6001: # ----------------------------------------------------------------- environment
1.620     albertel 6002: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6003: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6004: 	} else {
1.770     albertel 6005: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6006: 		return '';
                   6007: 	    }
1.219     albertel 6008: 	    my %returnhash=&userenvironment($udom,$uname,
                   6009: 					    $spacequalifierrest);
                   6010: 	    return $returnhash{$spacequalifierrest};
                   6011: 	}
1.28      www      6012:     } elsif ($realm eq 'system') {
1.48      www      6013: # ----------------------------------------------------------------- system.time
                   6014: 	if ($space eq 'time') {
                   6015: 	    return time;
                   6016:         }
1.696     albertel 6017:     } elsif ($realm eq 'server') {
                   6018: # ----------------------------------------------------------------- system.time
                   6019: 	if ($space eq 'name') {
                   6020: 	    return $ENV{'SERVER_NAME'};
                   6021:         }
1.28      www      6022:     }
1.48      www      6023:     return '';
1.61      www      6024: }
                   6025: 
1.691     raeburn  6026: sub check_group_parms {
                   6027:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6028:     my @groupitems = ();
                   6029:     my $resultitem;
                   6030:     my @levels = ($symbparm,$mapparm,$what);
                   6031:     foreach my $group (@{$groups}) {
                   6032:         foreach my $level (@levels) {
                   6033:              my $item = $courseid.'.['.$group.'].'.$level;
                   6034:              push(@groupitems,$item);
                   6035:         }
                   6036:     }
                   6037:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6038:                             $env{'course.'.$courseid.'.domain'},
                   6039:                                      'course',@groupitems);
                   6040:     return $coursereply;
                   6041: }
                   6042: 
                   6043: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6044:     my ($courseid,@groups) = @_;
                   6045:     @groups = sort(@groups);
1.691     raeburn  6046:     return @groups;
                   6047: }
                   6048: 
1.395     albertel 6049: sub packages_tab_default {
                   6050:     my ($uri,$varname)=@_;
                   6051:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6052: 
                   6053:     my (@extension,@specifics,$do_default);
                   6054:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6055: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6056: 	if ($pack_type eq 'default') {
                   6057: 	    $do_default=1;
                   6058: 	} elsif ($pack_type eq 'extension') {
                   6059: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6060: 	} else {
                   6061: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6062: 	}
                   6063:     }
                   6064:     # first look for a package that matches the requested part id
                   6065:     foreach my $package (@specifics) {
                   6066: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6067: 	next if ($pack_part ne $part);
                   6068: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6069: 	    return $packagetab{"$pack_type&$name&default"};
                   6070: 	}
                   6071:     }
                   6072:     # look for any possible matching non extension_ package
                   6073:     foreach my $package (@specifics) {
                   6074: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6075: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6076: 	    return $packagetab{"$pack_type&$name&default"};
                   6077: 	}
1.585     albertel 6078: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6079: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6080: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6081: 	}
                   6082:     }
1.738     albertel 6083:     # look for any posible extension_ match
                   6084:     foreach my $package (@extension) {
                   6085: 	my ($package,$pack_type)=@{$package};
                   6086: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6087: 	    return $packagetab{"$pack_type&$name&default"};
                   6088: 	}
                   6089: 	if (defined($packagetab{$package."&$name&default"})) {
                   6090: 	    return $packagetab{$package."&$name&default"};
                   6091: 	}
                   6092:     }
                   6093:     # look for a global default setting
                   6094:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6095: 	return $packagetab{"default&$name&default"};
                   6096:     }
1.395     albertel 6097:     return undef;
                   6098: }
                   6099: 
1.334     albertel 6100: sub add_prefix_and_part {
                   6101:     my ($prefix,$part)=@_;
                   6102:     my $keyroot;
                   6103:     if (defined($prefix) && $prefix !~ /^__/) {
                   6104: 	# prefix that has a part already
                   6105: 	$keyroot=$prefix;
                   6106:     } elsif (defined($prefix)) {
                   6107: 	# prefix that is missing a part
                   6108: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6109:     } else {
                   6110: 	# no prefix at all
                   6111: 	if (defined($part)) { $keyroot='_'.$part; }
                   6112:     }
                   6113:     return $keyroot;
                   6114: }
                   6115: 
1.71      www      6116: # ---------------------------------------------------------------- Get metadata
                   6117: 
1.599     albertel 6118: my %metaentry;
1.71      www      6119: sub metadata {
1.176     www      6120:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6121:     $uri=&declutter($uri);
1.288     albertel 6122:     # if it is a non metadata possible uri return quickly
1.529     albertel 6123:     if (($uri eq '') || 
                   6124: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6125: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6126:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6127: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6128: 	return undef;
1.288     albertel 6129:     }
1.73      www      6130:     my $filename=$uri;
                   6131:     $uri=~s/\.meta$//;
1.172     www      6132: #
                   6133: # Is the metadata already cached?
1.177     www      6134: # Look at timestamp of caching
1.172     www      6135: # Everything is cached by the main uri, libraries are never directly cached
                   6136: #
1.428     albertel 6137:     if (!defined($liburi)) {
1.599     albertel 6138: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6139: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6140:     }
                   6141:     {
1.172     www      6142: #
                   6143: # Is this a recursive call for a library?
                   6144: #
1.599     albertel 6145: #	if (! exists($metacache{$uri})) {
                   6146: #	    $metacache{$uri}={};
                   6147: #	}
1.171     www      6148:         if ($liburi) {
                   6149: 	    $liburi=&declutter($liburi);
                   6150:             $filename=$liburi;
1.401     bowersj2 6151:         } else {
1.599     albertel 6152: 	    &devalidate_cache_new('meta',$uri);
                   6153: 	    undef(%metaentry);
1.401     bowersj2 6154: 	}
1.140     www      6155:         my %metathesekeys=();
1.73      www      6156:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6157: 	my $metastring;
1.768     albertel 6158: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6159: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6160: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6161: 	    $metastring=&getfile($file);
1.489     albertel 6162: 	}
1.208     albertel 6163:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6164:         my $token;
1.140     www      6165:         undef %metathesekeys;
1.71      www      6166:         while ($token=$parser->get_token) {
1.339     albertel 6167: 	    if ($token->[0] eq 'S') {
                   6168: 		if (defined($token->[2]->{'package'})) {
1.172     www      6169: #
                   6170: # This is a package - get package info
                   6171: #
1.339     albertel 6172: 		    my $package=$token->[2]->{'package'};
                   6173: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6174: 		    if (defined($token->[2]->{'id'})) { 
                   6175: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6176: 		    }
1.599     albertel 6177: 		    if ($metaentry{':packages'}) {
                   6178: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6179: 		    } else {
1.599     albertel 6180: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6181: 		    }
1.736     albertel 6182: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6183: 			my $part=$keyroot;
                   6184: 			$part=~s/^\_//;
1.736     albertel 6185: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6186: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6187: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6188: 			    # ignore package.tab specified default values
                   6189:                             # here &package_tab_default() will fetch those
                   6190: 			    if ($subp eq 'default') { next; }
1.736     albertel 6191: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6192: 			    my $unikey;
                   6193: 			    if ($pack =~ /_0$/) {
                   6194: 				$unikey='parameter_0_'.$name;
                   6195: 				$part=0;
                   6196: 			    } else {
                   6197: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6198: 			    }
1.339     albertel 6199: 			    if ($subp eq 'display') {
                   6200: 				$value.=' [Part: '.$part.']';
                   6201: 			    }
1.599     albertel 6202: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6203: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6204: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6205: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6206: 			    }
1.599     albertel 6207: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6208: 				$metaentry{':'.$unikey}=
                   6209: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6210: 			    }
1.339     albertel 6211: 			}
                   6212: 		    }
                   6213: 		} else {
1.172     www      6214: #
                   6215: # This is not a package - some other kind of start tag
1.339     albertel 6216: #
                   6217: 		    my $entry=$token->[1];
                   6218: 		    my $unikey;
                   6219: 		    if ($entry eq 'import') {
                   6220: 			$unikey='';
                   6221: 		    } else {
                   6222: 			$unikey=$entry;
                   6223: 		    }
                   6224: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6225: 
                   6226: 		    if (defined($token->[2]->{'id'})) { 
                   6227: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6228: 		    }
1.175     www      6229: 
1.339     albertel 6230: 		    if ($entry eq 'import') {
1.175     www      6231: #
                   6232: # Importing a library here
1.339     albertel 6233: #
                   6234: 			if ($depthcount<20) {
                   6235: 			    my $location=$parser->get_text('/import');
                   6236: 			    my $dir=$filename;
                   6237: 			    $dir=~s|[^/]*$||;
                   6238: 			    $location=&filelocation($dir,$location);
1.736     albertel 6239: 			    my $metadata = 
                   6240: 				&metadata($uri,'keys', $location,$unikey,
                   6241: 					  $depthcount+1);
                   6242: 			    foreach my $meta (split(',',$metadata)) {
                   6243: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6244: 				$metathesekeys{$meta}=1;
1.339     albertel 6245: 			    }
                   6246: 			}
                   6247: 		    } else { 
                   6248: 			
                   6249: 			if (defined($token->[2]->{'name'})) { 
                   6250: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6251: 			}
                   6252: 			$metathesekeys{$unikey}=1;
1.736     albertel 6253: 			foreach my $param (@{$token->[3]}) {
                   6254: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6255: 				$token->[2]->{$param};
1.339     albertel 6256: 			}
                   6257: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6258: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6259: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6260: 		 # only ws inside the tag, and not in default, so use default
                   6261: 		 # as value
1.599     albertel 6262: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6263: 			} else {
1.321     albertel 6264: 		  # either something interesting inside the tag or default
                   6265:                   # uninteresting
1.599     albertel 6266: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6267: 			}
1.172     www      6268: # end of not-a-package not-a-library import
1.339     albertel 6269: 		    }
1.172     www      6270: # end of not-a-package start tag
1.339     albertel 6271: 		}
1.172     www      6272: # the next is the end of "start tag"
1.339     albertel 6273: 	    }
                   6274: 	}
1.483     albertel 6275: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6276: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6277: 	    #no specific packages #how's our extension
                   6278: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6279: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6280: 					 \%metathesekeys);
                   6281: 	}
1.599     albertel 6282: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6283: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6284: 		#no specific packages well let's get default then
                   6285: 		if ($key!~/^default&/) { next; }
1.488     albertel 6286: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6287: 					     \%metathesekeys);
                   6288: 	    }
                   6289: 	}
1.338     www      6290: # are there custom rights to evaluate
1.599     albertel 6291: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6292: 
1.338     www      6293:     #
                   6294:     # Importing a rights file here
1.339     albertel 6295:     #
                   6296: 	    unless ($depthcount) {
1.599     albertel 6297: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6298: 		my $dir=$filename;
                   6299: 		$dir=~s|[^/]*$||;
                   6300: 		$location=&filelocation($dir,$location);
1.736     albertel 6301: 		my $rights_metadata =
                   6302: 		    &metadata($uri,'keys',$location,'_rights',
                   6303: 			      $depthcount+1);
                   6304: 		foreach my $rights (split(',',$rights_metadata)) {
                   6305: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6306: 		    $metathesekeys{$rights}=1;
1.339     albertel 6307: 		}
                   6308: 	    }
                   6309: 	}
1.737     albertel 6310: 	# uniqifiy package listing
                   6311: 	my %seen;
                   6312: 	my @uniq_packages =
                   6313: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6314: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6315: 
                   6316: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6317: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6318: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6319: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6320: # this is the end of "was not already recently cached
1.71      www      6321:     }
1.599     albertel 6322:     return $metaentry{':'.$what};
1.261     albertel 6323: }
                   6324: 
1.488     albertel 6325: sub metadata_create_package_def {
1.483     albertel 6326:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6327:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6328:     if ($subp eq 'default') { next; }
                   6329:     
1.599     albertel 6330:     if (defined($metaentry{':packages'})) {
                   6331: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6332:     } else {
1.599     albertel 6333: 	$metaentry{':packages'}=$package;
1.483     albertel 6334:     }
                   6335:     my $value=$packagetab{$key};
                   6336:     my $unikey;
                   6337:     $unikey='parameter_0_'.$name;
1.599     albertel 6338:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6339:     $$metathesekeys{$unikey}=1;
1.599     albertel 6340:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6341: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6342:     }
1.599     albertel 6343:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6344: 	$metaentry{':'.$unikey}=
                   6345: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6346:     }
                   6347: }
                   6348: 
1.261     albertel 6349: sub metadata_generate_part0 {
                   6350:     my ($metadata,$metacache,$uri) = @_;
                   6351:     my %allnames;
1.737     albertel 6352:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6353: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6354: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6355: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6356: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6357: 	    $allnames{$name}=$part;
                   6358: 	  }
                   6359: 	}
                   6360:     }
                   6361:     foreach my $name (keys(%allnames)) {
                   6362:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6363:       my $key=":parameter_0_$name";
1.261     albertel 6364:       $$metacache{"$key.part"}='0';
                   6365:       $$metacache{"$key.name"}=$name;
1.428     albertel 6366:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6367: 					   $allnames{$name}.'_'.$name.
                   6368: 					   '.type'};
1.428     albertel 6369:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6370: 			     '.display'};
1.644     www      6371:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6372:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6373:       $$metacache{"$key.display"}=$olddis;
                   6374:     }
1.71      www      6375: }
                   6376: 
1.764     albertel 6377: # ------------------------------------------------------ Devalidate title cache
                   6378: 
                   6379: sub devalidate_title_cache {
                   6380:     my ($url)=@_;
                   6381:     if (!$env{'request.course.id'}) { return; }
                   6382:     my $symb=&symbread($url);
                   6383:     if (!$symb) { return; }
                   6384:     my $key=$env{'request.course.id'}."\0".$symb;
                   6385:     &devalidate_cache_new('title',$key);
                   6386: }
                   6387: 
1.301     www      6388: # ------------------------------------------------- Get the title of a resource
                   6389: 
                   6390: sub gettitle {
                   6391:     my $urlsymb=shift;
                   6392:     my $symb=&symbread($urlsymb);
1.534     albertel 6393:     if ($symb) {
1.620     albertel 6394: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6395: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6396: 	if (defined($cached)) { 
                   6397: 	    return $result;
                   6398: 	}
1.534     albertel 6399: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6400: 	my $title='';
                   6401: 	my %bighash;
1.620     albertel 6402: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6403: 		&GDBM_READER(),0640)) {
                   6404: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6405: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6406: 	    untie %bighash;
                   6407: 	}
                   6408: 	$title=~s/\&colon\;/\:/gs;
                   6409: 	if ($title) {
1.599     albertel 6410: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6411: 	}
                   6412: 	$urlsymb=$url;
                   6413:     }
                   6414:     my $title=&metadata($urlsymb,'title');
                   6415:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6416:     return $title;
1.301     www      6417: }
1.613     albertel 6418: 
1.614     albertel 6419: sub get_slot {
                   6420:     my ($which,$cnum,$cdom)=@_;
                   6421:     if (!$cnum || !$cdom) {
1.790     albertel 6422: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6423: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6424: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6425:     }
1.703     albertel 6426:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6427:     my %slotinfo;
                   6428:     if (exists($remembered{$key})) {
                   6429: 	$slotinfo{$which} = $remembered{$key};
                   6430:     } else {
                   6431: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6432: 	&Apache::lonhomework::showhash(%slotinfo);
                   6433: 	my ($tmp)=keys(%slotinfo);
                   6434: 	if ($tmp=~/^error:/) { return (); }
                   6435: 	$remembered{$key} = $slotinfo{$which};
                   6436:     }
1.616     albertel 6437:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6438: 	return %{$slotinfo{$which}};
                   6439:     }
                   6440:     return $slotinfo{$which};
1.614     albertel 6441: }
1.31      www      6442: # ------------------------------------------------- Update symbolic store links
                   6443: 
                   6444: sub symblist {
                   6445:     my ($mapname,%newhash)=@_;
1.438     www      6446:     $mapname=&deversion(&declutter($mapname));
1.31      www      6447:     my %hash;
1.620     albertel 6448:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6449:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6450:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6451: 	    foreach my $url (keys %newhash) {
                   6452: 		next if ($url eq 'last_known'
                   6453: 			 && $env{'form.no_update_last_known'});
                   6454: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6455: 						    $newhash{$url}->[1],
                   6456: 						    $newhash{$url}->[0]);
1.191     harris41 6457:             }
1.31      www      6458:             if (untie(%hash)) {
                   6459: 		return 'ok';
                   6460:             }
                   6461:         }
                   6462:     }
                   6463:     return 'error';
1.212     www      6464: }
                   6465: 
                   6466: # --------------------------------------------------------------- Verify a symb
                   6467: 
                   6468: sub symbverify {
1.510     www      6469:     my ($symb,$thisurl)=@_;
                   6470:     my $thisfn=$thisurl;
1.439     www      6471:     $thisfn=&declutter($thisfn);
1.215     www      6472: # direct jump to resource in page or to a sequence - will construct own symbs
                   6473:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6474: # check URL part
1.409     www      6475:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6476: 
1.431     www      6477:     unless ($url eq $thisfn) { return 0; }
1.213     www      6478: 
1.216     www      6479:     $symb=&symbclean($symb);
1.510     www      6480:     $thisurl=&deversion($thisurl);
1.439     www      6481:     $thisfn=&deversion($thisfn);
1.213     www      6482: 
                   6483:     my %bighash;
                   6484:     my $okay=0;
1.431     www      6485: 
1.620     albertel 6486:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6487:                             &GDBM_READER(),0640)) {
1.510     www      6488:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6489:         unless ($ids) { 
1.510     www      6490:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6491:         }
                   6492:         if ($ids) {
                   6493: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6494: 	    foreach my $id (split(/\,/,$ids)) {
                   6495: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6496:                if (
                   6497:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6498:    eq $symb) { 
1.620     albertel 6499: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6500: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6501: 		       $okay=1; 
                   6502: 		   }
                   6503: 	       }
1.216     www      6504: 	   }
                   6505:         }
1.213     www      6506: 	untie(%bighash);
                   6507:     }
                   6508:     return $okay;
1.31      www      6509: }
                   6510: 
1.210     www      6511: # --------------------------------------------------------------- Clean-up symb
                   6512: 
                   6513: sub symbclean {
                   6514:     my $symb=shift;
1.568     albertel 6515:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6516: # remove version from map
                   6517:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6518: 
1.210     www      6519: # remove version from URL
                   6520:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6521: 
1.507     www      6522: # remove wrapper
                   6523: 
1.510     www      6524:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6525:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6526:     return $symb;
1.409     www      6527: }
                   6528: 
                   6529: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6530: 
                   6531: sub encode_symb {
                   6532:     my ($map,$resid,$url)=@_;
                   6533:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6534: }
1.409     www      6535: 
                   6536: sub decode_symb {
1.568     albertel 6537:     my $symb=shift;
                   6538:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6539:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6540:     return (&fixversion($map),$resid,&fixversion($url));
                   6541: }
                   6542: 
                   6543: sub fixversion {
                   6544:     my $fn=shift;
1.609     banghart 6545:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6546:     my %bighash;
                   6547:     my $uri=&clutter($fn);
1.620     albertel 6548:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6549: # is this cached?
1.599     albertel 6550:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6551:     if (defined($cached)) { return $result; }
                   6552: # unfortunately not cached, or expired
1.620     albertel 6553:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6554: 	    &GDBM_READER(),0640)) {
                   6555:  	if ($bighash{'version_'.$uri}) {
                   6556:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6557:  	    unless (($version eq 'mostrecent') || 
                   6558: 		    ($version==&getversion($uri))) {
1.440     www      6559:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6560:  	    }
                   6561:  	}
                   6562:  	untie %bighash;
1.413     www      6563:     }
1.599     albertel 6564:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6565: }
                   6566: 
                   6567: sub deversion {
                   6568:     my $url=shift;
                   6569:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6570:     return $url;
1.210     www      6571: }
                   6572: 
1.31      www      6573: # ------------------------------------------------------ Return symb list entry
                   6574: 
                   6575: sub symbread {
1.249     www      6576:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6577:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6578:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6579: # no filename provided? try from environment
1.44      www      6580:     unless ($thisfn) {
1.620     albertel 6581:         if ($env{'request.symb'}) {
                   6582: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6583: 	}
1.620     albertel 6584: 	$thisfn=$env{'request.filename'};
1.44      www      6585:     }
1.569     albertel 6586:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6587: # is that filename actually a symb? Verify, clean, and return
                   6588:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6589: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6590: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6591: 	}
1.242     www      6592:     }
1.44      www      6593:     $thisfn=declutter($thisfn);
1.31      www      6594:     my %hash;
1.37      www      6595:     my %bighash;
                   6596:     my $syval='';
1.620     albertel 6597:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6598:         my $targetfn = $thisfn;
1.609     banghart 6599:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6600:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6601:         }
1.687     albertel 6602: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6603: 	    $targetfn=$1;
                   6604: 	}
1.620     albertel 6605:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6606:                       &GDBM_READER(),0640)) {
1.481     raeburn  6607: 	    $syval=$hash{$targetfn};
1.37      www      6608:             untie(%hash);
                   6609:         }
                   6610: # ---------------------------------------------------------- There was an entry
                   6611:         if ($syval) {
1.601     albertel 6612: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6613: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6614: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6615: 		    #return $env{$cache_str}='';
1.601     albertel 6616: 		#}    
                   6617: 		#$syval.=$1;
                   6618: 	    #}
1.37      www      6619:         } else {
                   6620: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6621:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6622:                             &GDBM_READER(),0640)) {
1.37      www      6623: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6624:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6625:               unless ($ids) { 
                   6626:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6627:               }
                   6628:               unless ($ids) {
                   6629: # alias?
                   6630: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6631:               }
1.37      www      6632:               if ($ids) {
                   6633: # ------------------------------------------------------------------- Has ID(s)
                   6634:                  my @possibilities=split(/\,/,$ids);
1.39      www      6635:                  if ($#possibilities==0) {
                   6636: # ----------------------------------------------- There is only one possibility
1.37      www      6637: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6638: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6639: 						    $resid,$thisfn);
1.249     www      6640:                  } elsif (!$donotrecurse) {
1.39      www      6641: # ------------------------------------------ There is more than one possibility
                   6642:                      my $realpossible=0;
1.800     albertel 6643:                      foreach my $id (@possibilities) {
                   6644: 			 my $file=$bighash{'src_'.$id};
1.39      www      6645:                          if (&allowed('bre',$file)) {
1.800     albertel 6646:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6647:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6648: 				$realpossible++;
1.626     albertel 6649:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6650: 						    $resid,$thisfn);
1.39      www      6651:                             }
                   6652: 			 }
1.191     harris41 6653:                      }
1.39      www      6654: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6655:                  } else {
                   6656:                      $syval='';
1.37      www      6657:                  }
                   6658: 	      }
                   6659:               untie(%bighash)
1.481     raeburn  6660:            }
1.31      www      6661:         }
1.62      www      6662:         if ($syval) {
1.620     albertel 6663: 	    return $env{$cache_str}=$syval;
1.62      www      6664:         }
1.31      www      6665:     }
1.44      www      6666:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6667:     return $env{$cache_str}='';
1.31      www      6668: }
                   6669: 
                   6670: # ---------------------------------------------------------- Return random seed
                   6671: 
1.32      www      6672: sub numval {
                   6673:     my $txt=shift;
                   6674:     $txt=~tr/A-J/0-9/;
                   6675:     $txt=~tr/a-j/0-9/;
                   6676:     $txt=~tr/K-T/0-9/;
                   6677:     $txt=~tr/k-t/0-9/;
                   6678:     $txt=~tr/U-Z/0-5/;
                   6679:     $txt=~tr/u-z/0-5/;
                   6680:     $txt=~s/\D//g;
1.564     albertel 6681:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6682:     return int($txt);
1.368     albertel 6683: }
                   6684: 
1.484     albertel 6685: sub numval2 {
                   6686:     my $txt=shift;
                   6687:     $txt=~tr/A-J/0-9/;
                   6688:     $txt=~tr/a-j/0-9/;
                   6689:     $txt=~tr/K-T/0-9/;
                   6690:     $txt=~tr/k-t/0-9/;
                   6691:     $txt=~tr/U-Z/0-5/;
                   6692:     $txt=~tr/u-z/0-5/;
                   6693:     $txt=~s/\D//g;
                   6694:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6695:     my $total;
                   6696:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6697:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6698:     return int($total);
                   6699: }
                   6700: 
1.575     albertel 6701: sub numval3 {
                   6702:     use integer;
                   6703:     my $txt=shift;
                   6704:     $txt=~tr/A-J/0-9/;
                   6705:     $txt=~tr/a-j/0-9/;
                   6706:     $txt=~tr/K-T/0-9/;
                   6707:     $txt=~tr/k-t/0-9/;
                   6708:     $txt=~tr/U-Z/0-5/;
                   6709:     $txt=~tr/u-z/0-5/;
                   6710:     $txt=~s/\D//g;
                   6711:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6712:     my $total;
                   6713:     foreach my $val (@txts) { $total+=$val; }
                   6714:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6715:     return $total;
                   6716: }
                   6717: 
1.675     albertel 6718: sub digest {
                   6719:     my ($data)=@_;
                   6720:     my $digest=&Digest::MD5::md5($data);
                   6721:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6722:     my ($e,$f);
                   6723:     {
                   6724:         use integer;
                   6725:         $e=($a+$b);
                   6726:         $f=($c+$d);
                   6727:         if ($_64bit) {
                   6728:             $e=(($e<<32)>>32);
                   6729:             $f=(($f<<32)>>32);
                   6730:         }
                   6731:     }
                   6732:     if (wantarray) {
                   6733: 	return ($e,$f);
                   6734:     } else {
                   6735: 	my $g;
                   6736: 	{
                   6737: 	    use integer;
                   6738: 	    $g=($e+$f);
                   6739: 	    if ($_64bit) {
                   6740: 		$g=(($g<<32)>>32);
                   6741: 	    }
                   6742: 	}
                   6743: 	return $g;
                   6744:     }
                   6745: }
                   6746: 
1.368     albertel 6747: sub latest_rnd_algorithm_id {
1.675     albertel 6748:     return '64bit5';
1.366     albertel 6749: }
1.32      www      6750: 
1.503     albertel 6751: sub get_rand_alg {
                   6752:     my ($courseid)=@_;
1.790     albertel 6753:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6754:     if ($courseid) {
1.620     albertel 6755: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6756:     }
                   6757:     return &latest_rnd_algorithm_id();
                   6758: }
                   6759: 
1.562     albertel 6760: sub validCODE {
                   6761:     my ($CODE)=@_;
                   6762:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6763:     return 0;
                   6764: }
                   6765: 
1.491     albertel 6766: sub getCODE {
1.620     albertel 6767:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6768:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6769: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6770: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6771: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6772:     }
                   6773:     return undef;
                   6774: }
                   6775: 
1.31      www      6776: sub rndseed {
1.155     albertel 6777:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6778: 
1.790     albertel 6779:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6780:     if (!$symb) {
1.366     albertel 6781: 	unless ($symb=$wsymb) { return time; }
                   6782:     }
                   6783:     if (!$courseid) { $courseid=$wcourseid; }
                   6784:     if (!$domain) { $domain=$wdomain; }
                   6785:     if (!$username) { $username=$wusername }
1.503     albertel 6786:     my $which=&get_rand_alg();
1.803     albertel 6787: 
1.491     albertel 6788:     if (defined(&getCODE())) {
1.675     albertel 6789: 	if ($which eq '64bit5') {
                   6790: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6791: 	} elsif ($which eq '64bit4') {
1.575     albertel 6792: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6793: 	} else {
                   6794: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6795: 	}
1.675     albertel 6796:     } elsif ($which eq '64bit5') {
                   6797: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6798:     } elsif ($which eq '64bit4') {
                   6799: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6800:     } elsif ($which eq '64bit3') {
                   6801: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6802:     } elsif ($which eq '64bit2') {
                   6803: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6804:     } elsif ($which eq '64bit') {
                   6805: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6806:     }
                   6807:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6808: }
                   6809: 
                   6810: sub rndseed_32bit {
                   6811:     my ($symb,$courseid,$domain,$username)=@_;
                   6812:     {
                   6813: 	use integer;
                   6814: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6815: 	my $symbseed=numval($symb) << 22;
                   6816: 	my $namechck=unpack("%32C*",$username) << 17;
                   6817: 	my $nameseed=numval($username) << 12;
                   6818: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6819: 	my $courseseed=unpack("%32C*",$courseid);
                   6820: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6821: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6822: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6823: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6824: 	return $num;
                   6825:     }
                   6826: }
                   6827: 
                   6828: sub rndseed_64bit {
                   6829:     my ($symb,$courseid,$domain,$username)=@_;
                   6830:     {
                   6831: 	use integer;
                   6832: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6833: 	my $symbseed=numval($symb) << 10;
                   6834: 	my $namechck=unpack("%32S*",$username);
                   6835: 	
                   6836: 	my $nameseed=numval($username) << 21;
                   6837: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6838: 	my $courseseed=unpack("%32S*",$courseid);
                   6839: 	
                   6840: 	my $num1=$symbchck+$symbseed+$namechck;
                   6841: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6842: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6843: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6844: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6845: 	return "$num1,$num2";
1.155     albertel 6846:     }
1.366     albertel 6847: }
                   6848: 
1.443     albertel 6849: sub rndseed_64bit2 {
                   6850:     my ($symb,$courseid,$domain,$username)=@_;
                   6851:     {
                   6852: 	use integer;
                   6853: 	# strings need to be an even # of cahracters long, it it is odd the
                   6854:         # last characters gets thrown away
                   6855: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6856: 	my $symbseed=numval($symb) << 10;
                   6857: 	my $namechck=unpack("%32S*",$username.' ');
                   6858: 	
                   6859: 	my $nameseed=numval($username) << 21;
1.501     albertel 6860: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6861: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6862: 	
                   6863: 	my $num1=$symbchck+$symbseed+$namechck;
                   6864: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6865: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6866: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6867: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6868: 	return "$num1,$num2";
                   6869:     }
                   6870: }
                   6871: 
                   6872: sub rndseed_64bit3 {
                   6873:     my ($symb,$courseid,$domain,$username)=@_;
                   6874:     {
                   6875: 	use integer;
                   6876: 	# strings need to be an even # of cahracters long, it it is odd the
                   6877:         # last characters gets thrown away
                   6878: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6879: 	my $symbseed=numval2($symb) << 10;
                   6880: 	my $namechck=unpack("%32S*",$username.' ');
                   6881: 	
                   6882: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6883: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6884: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6885: 	
                   6886: 	my $num1=$symbchck+$symbseed+$namechck;
                   6887: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6888: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6889: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6890: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6891: 	
1.503     albertel 6892: 	return "$num1:$num2";
1.443     albertel 6893:     }
                   6894: }
                   6895: 
1.575     albertel 6896: sub rndseed_64bit4 {
                   6897:     my ($symb,$courseid,$domain,$username)=@_;
                   6898:     {
                   6899: 	use integer;
                   6900: 	# strings need to be an even # of cahracters long, it it is odd the
                   6901:         # last characters gets thrown away
                   6902: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6903: 	my $symbseed=numval3($symb) << 10;
                   6904: 	my $namechck=unpack("%32S*",$username.' ');
                   6905: 	
                   6906: 	my $nameseed=numval3($username) << 21;
                   6907: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6908: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6909: 	
                   6910: 	my $num1=$symbchck+$symbseed+$namechck;
                   6911: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6912: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6913: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6914: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6915: 	
                   6916: 	return "$num1:$num2";
                   6917:     }
                   6918: }
                   6919: 
1.675     albertel 6920: sub rndseed_64bit5 {
                   6921:     my ($symb,$courseid,$domain,$username)=@_;
                   6922:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6923:     return "$num1:$num2";
                   6924: }
                   6925: 
1.366     albertel 6926: sub rndseed_CODE_64bit {
                   6927:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6928:     {
1.366     albertel 6929: 	use integer;
1.443     albertel 6930: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6931: 	my $symbseed=numval2($symb);
1.491     albertel 6932: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6933: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6934: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6935: 	my $num1=$symbseed+$CODEchck;
                   6936: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6937: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6938: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6939: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6940: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6941: 	return "$num1:$num2";
1.366     albertel 6942:     }
                   6943: }
                   6944: 
1.575     albertel 6945: sub rndseed_CODE_64bit4 {
                   6946:     my ($symb,$courseid,$domain,$username)=@_;
                   6947:     {
                   6948: 	use integer;
                   6949: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6950: 	my $symbseed=numval3($symb);
                   6951: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6952: 	my $CODEseed=numval3(&getCODE());
                   6953: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6954: 	my $num1=$symbseed+$CODEchck;
                   6955: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6956: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6957: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6958: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6959: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6960: 	return "$num1:$num2";
                   6961:     }
                   6962: }
                   6963: 
1.675     albertel 6964: sub rndseed_CODE_64bit5 {
                   6965:     my ($symb,$courseid,$domain,$username)=@_;
                   6966:     my $code = &getCODE();
                   6967:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6968:     return "$num1:$num2";
                   6969: }
                   6970: 
1.366     albertel 6971: sub setup_random_from_rndseed {
                   6972:     my ($rndseed)=@_;
1.503     albertel 6973:     if ($rndseed =~/([,:])/) {
                   6974: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6975: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6976:     } else {
                   6977: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6978:     }
1.36      albertel 6979: }
                   6980: 
1.474     albertel 6981: sub latest_receipt_algorithm_id {
                   6982:     return 'receipt2';
                   6983: }
                   6984: 
1.480     www      6985: sub recunique {
                   6986:     my $fucourseid=shift;
                   6987:     my $unique;
1.620     albertel 6988:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6989: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6990:     } else {
                   6991: 	$unique=$perlvar{'lonReceipt'};
                   6992:     }
                   6993:     return unpack("%32C*",$unique);
                   6994: }
                   6995: 
                   6996: sub recprefix {
                   6997:     my $fucourseid=shift;
                   6998:     my $prefix;
1.620     albertel 6999:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7000: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7001:     } else {
                   7002: 	$prefix=$perlvar{'lonHostID'};
                   7003:     }
                   7004:     return unpack("%32C*",$prefix);
                   7005: }
                   7006: 
1.76      www      7007: sub ireceipt {
1.474     albertel 7008:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      7009:     my $cuname=unpack("%32C*",$funame);
                   7010:     my $cudom=unpack("%32C*",$fudom);
                   7011:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7012:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7013:     my $cunique=&recunique($fucourseid);
1.474     albertel 7014:     my $cpart=unpack("%32S*",$part);
1.480     www      7015:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 7016:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7017: 	$env{'request.state'} eq 'construct') {
1.790     albertel 7018: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7019: 			       
                   7020: 	$return.= ($cunique%$cuname+
                   7021: 		   $cunique%$cudom+
                   7022: 		   $cusymb%$cuname+
                   7023: 		   $cusymb%$cudom+
                   7024: 		   $cucourseid%$cuname+
                   7025: 		   $cucourseid%$cudom+
                   7026: 		   $cpart%$cuname+
                   7027: 		   $cpart%$cudom);
                   7028:     } else {
                   7029: 	$return.= ($cunique%$cuname+
                   7030: 		   $cunique%$cudom+
                   7031: 		   $cusymb%$cuname+
                   7032: 		   $cusymb%$cudom+
                   7033: 		   $cucourseid%$cuname+
                   7034: 		   $cucourseid%$cudom);
                   7035:     }
                   7036:     return $return;
1.76      www      7037: }
                   7038: 
                   7039: sub receipt {
1.474     albertel 7040:     my ($part)=@_;
1.790     albertel 7041:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7042:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7043: }
1.260     ng       7044: 
1.790     albertel 7045: sub whichuser {
                   7046:     my ($passedsymb)=@_;
                   7047:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7048:     if (defined($env{'form.grade_symb'})) {
                   7049: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7050: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7051: 	if (!$allowed &&
                   7052: 	    exists($env{'request.course.sec'}) &&
                   7053: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7054: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7055: 			      '/'.$env{'request.course.sec'});
                   7056: 	}
                   7057: 	if ($allowed) {
                   7058: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7059: 	    $courseid=$tmp_courseid;
                   7060: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7061: 	    ($name)=&get_env_multiple('form.grade_username');
                   7062: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7063: 	}
                   7064:     }
                   7065:     if (!$passedsymb) {
                   7066: 	$symb=&symbread();
                   7067:     } else {
                   7068: 	$symb=$passedsymb;
                   7069:     }
                   7070:     $courseid=$env{'request.course.id'};
                   7071:     $domain=$env{'user.domain'};
                   7072:     $name=$env{'user.name'};
                   7073:     if ($name eq 'public' && $domain eq 'public') {
                   7074: 	if (!defined($env{'form.username'})) {
                   7075: 	    $env{'form.username'}.=time.rand(10000000);
                   7076: 	}
                   7077: 	$name.=$env{'form.username'};
                   7078:     }
                   7079:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7080: 
                   7081: }
                   7082: 
1.36      albertel 7083: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7084: # returns either the contents of the file or 
                   7085: # -1 if the file doesn't exist
1.481     raeburn  7086: #
                   7087: # if the target is a file that was uploaded via DOCS, 
                   7088: # a check will be made to see if a current copy exists on the local server,
                   7089: # if it does this will be served, otherwise a copy will be retrieved from
                   7090: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7091: # the local server.   
1.472     albertel 7092: 
1.36      albertel 7093: sub getfile {
1.538     albertel 7094:     my ($file) = @_;
1.609     banghart 7095:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7096:     &repcopy($file);
                   7097:     return &readfile($file);
                   7098: }
                   7099: 
                   7100: sub repcopy_userfile {
                   7101:     my ($file)=@_;
1.609     banghart 7102:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7103:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7104:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7105: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7106:     my ($info,$rtncode);
                   7107:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7108:     if (-e "$file") {
                   7109: 	my @fileinfo = stat($file);
                   7110: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7111: 	if ($lwpresp ne 'ok') {
                   7112: 	    if ($rtncode eq '404') {
1.538     albertel 7113: 		unlink($file);
1.482     albertel 7114: 	    }
1.517     albertel 7115: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7116: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7117: 	    #my $response=$ua->request($request);
                   7118: 	    #if ($response->is_success()) {
                   7119: 	#	return $response->content;
                   7120: 	#    } else {
                   7121: 	#	return -1;
                   7122: 	#    }
1.482     albertel 7123: 	    return -1;
                   7124: 	}
                   7125: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7126: 	    return 'ok';
1.482     albertel 7127: 	}
                   7128: 	$info = '';
1.538     albertel 7129: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7130: 	if ($lwpresp ne 'ok') {
                   7131: 	    return -1;
                   7132: 	}
                   7133:     } else {
1.538     albertel 7134: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7135: 	if ($lwpresp ne 'ok') {
1.517     albertel 7136: 	    my $ua=new LWP::UserAgent;
1.538     albertel 7137: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7138: 	    my $response=$ua->request($request);
                   7139: 	    if ($response->is_success()) {
1.538     albertel 7140: 		$info=$response->content;
1.517     albertel 7141: 	    } else {
                   7142: 		return -1;
                   7143: 	    }
1.482     albertel 7144: 	}
                   7145: 	my @parts = ($cdom,$cnum); 
                   7146: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7147: 	    push @parts, split(/\//,$1);
1.518     albertel 7148: 	}
1.538     albertel 7149: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7150: 	foreach my $part (@parts) {
                   7151: 	    $path .= '/'.$part;
                   7152: 	    if (!-e $path) {
                   7153: 		mkdir($path,0770);
                   7154: 	    }
                   7155: 	}
                   7156:     }
1.538     albertel 7157:     open(FILE,">$file");
1.482     albertel 7158:     print FILE $info;
                   7159:     close(FILE);
1.607     raeburn  7160:     return 'ok';
1.481     raeburn  7161: }
                   7162: 
1.517     albertel 7163: sub tokenwrapper {
                   7164:     my $uri=shift;
1.552     albertel 7165:     $uri=~s|^http\://([^/]+)||;
                   7166:     $uri=~s|^/||;
1.620     albertel 7167:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7168:     my $token=$1;
1.552     albertel 7169:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7170:     if ($udom && $uname && $file) {
                   7171: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7172:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7173:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7174:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7175:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7176:     } else {
                   7177:         return '/adm/notfound.html';
                   7178:     }
                   7179: }
                   7180: 
1.481     raeburn  7181: sub getuploaded {
                   7182:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7183:     $uri=~s/^\///;
                   7184:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7185:     my $ua=new LWP::UserAgent;
                   7186:     my $request=new HTTP::Request($reqtype,$uri);
                   7187:     my $response=$ua->request($request);
                   7188:     $$rtncode = $response->code;
1.482     albertel 7189:     if (! $response->is_success()) {
                   7190: 	return 'failed';
                   7191:     }      
                   7192:     if ($reqtype eq 'HEAD') {
1.486     www      7193: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7194:     } elsif ($reqtype eq 'GET') {
                   7195: 	$$info = $response->content;
1.472     albertel 7196:     }
1.482     albertel 7197:     return 'ok';
1.36      albertel 7198: }
                   7199: 
1.481     raeburn  7200: sub readfile {
                   7201:     my $file = shift;
                   7202:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7203:     my $fh;
                   7204:     open($fh,"<$file");
                   7205:     my $a='';
1.800     albertel 7206:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7207:     return $a;
                   7208: }
                   7209: 
1.36      albertel 7210: sub filelocation {
1.590     banghart 7211:     my ($dir,$file) = @_;
                   7212:     my $location;
                   7213:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7214: 
                   7215:     if ($file =~ m-^/adm/-) {
                   7216: 	$file=~s-^/adm/wrapper/-/-;
                   7217: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7218:     }
1.590     banghart 7219:     if ($file=~m:^/~:) { # is a contruction space reference
                   7220:         $location = $file;
                   7221:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7222:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7223: 	# is a correct contruction space reference
                   7224:         $location = $file;
1.609     banghart 7225:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7226:         my ($udom,$uname,$filename)=
1.811     albertel 7227:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7228:         my $home=&homeserver($uname,$udom);
                   7229:         my $is_me=0;
                   7230:         my @ids=&current_machine_ids();
                   7231:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7232:         if ($is_me) {
1.740     www      7233:   	    $location=&propath($udom,$uname).
1.590     banghart 7234:   	      '/userfiles/'.$filename;
                   7235:         } else {
                   7236:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7237:   	      $udom.'/'.$uname.'/'.$filename;
                   7238:         }
                   7239:     } else {
                   7240:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7241:         $file=~s:^/res/:/:;
                   7242:         if ( !( $file =~ m:^/:) ) {
                   7243:             $location = $dir. '/'.$file;
                   7244:         } else {
                   7245:             $location = '/home/httpd/html/res'.$file;
                   7246:         }
1.59      albertel 7247:     }
1.590     banghart 7248:     $location=~s://+:/:g; # remove duplicate /
                   7249:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7250:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7251:     return $location;
1.46      www      7252: }
1.36      albertel 7253: 
1.46      www      7254: sub hreflocation {
                   7255:     my ($dir,$file)=@_;
1.460     albertel 7256:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7257: 	$file=filelocation($dir,$file);
1.700     albertel 7258:     } elsif ($file=~m-^/adm/-) {
                   7259: 	$file=~s-^/adm/wrapper/-/-;
                   7260: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7261:     }
                   7262:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7263: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7264:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7265: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7266:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7267: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7268: 	    -/uploaded/$1/$2/-x;
1.46      www      7269:     }
1.462     albertel 7270:     return $file;
1.465     albertel 7271: }
                   7272: 
                   7273: sub current_machine_domains {
                   7274:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7275:     my @domains;
                   7276:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7277: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7278: 	if ($hostname eq $name) {
                   7279: 	    push(@domains,$hostdom{$id});
                   7280: 	}
                   7281:     }
                   7282:     return @domains;
                   7283: }
                   7284: 
                   7285: sub current_machine_ids {
                   7286:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7287:     my @ids;
                   7288:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7289: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7290: 	if ($hostname eq $name) {
                   7291: 	    push(@ids,$id);
                   7292: 	}
                   7293:     }
                   7294:     return @ids;
1.31      www      7295: }
                   7296: 
                   7297: # ------------------------------------------------------------- Declutters URLs
                   7298: 
                   7299: sub declutter {
                   7300:     my $thisfn=shift;
1.569     albertel 7301:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7302:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7303:     $thisfn=~s/^\///;
1.697     albertel 7304:     $thisfn=~s|^adm/wrapper/||;
                   7305:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7306:     $thisfn=~s/^res\///;
1.235     www      7307:     $thisfn=~s/\?.+$//;
1.268     www      7308:     return $thisfn;
                   7309: }
                   7310: 
                   7311: # ------------------------------------------------------------- Clutter up URLs
                   7312: 
                   7313: sub clutter {
                   7314:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7315:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7316:        $thisfn='/res'.$thisfn; 
                   7317:     }
1.694     albertel 7318:     if ($thisfn !~m|/adm|) {
1.695     albertel 7319: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7320: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7321: 	} else {
                   7322: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7323: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7324: 	    if ($embstyle eq 'ssi'
                   7325: 		|| ($embstyle eq 'hdn')
                   7326: 		|| ($embstyle eq 'rat')
                   7327: 		|| ($embstyle eq 'prv')
                   7328: 		|| ($embstyle eq 'ign')) {
                   7329: 		#do nothing with these
                   7330: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7331: 		|| ($embstyle eq 'emb')
                   7332: 		|| ($embstyle eq 'wrp')) {
                   7333: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7334: 	    } elsif ($embstyle eq 'unk'
                   7335: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7336: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7337: 	    } else {
1.718     www      7338: #		&logthis("Got a blank emb style");
1.695     albertel 7339: 	    }
1.694     albertel 7340: 	}
                   7341:     }
1.31      www      7342:     return $thisfn;
1.12      www      7343: }
                   7344: 
1.787     albertel 7345: sub clutter_with_no_wrapper {
                   7346:     my $uri = &clutter(shift);
                   7347:     if ($uri =~ m-^/adm/-) {
                   7348: 	$uri =~ s-^/adm/wrapper/-/-;
                   7349: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7350:     }
                   7351:     return $uri;
                   7352: }
                   7353: 
1.557     albertel 7354: sub freeze_escape {
                   7355:     my ($value)=@_;
                   7356:     if (ref($value)) {
                   7357: 	$value=&nfreeze($value);
                   7358: 	return '__FROZEN__'.&escape($value);
                   7359:     }
                   7360:     return &escape($value);
                   7361: }
                   7362: 
1.11      www      7363: 
1.557     albertel 7364: sub thaw_unescape {
                   7365:     my ($value)=@_;
                   7366:     if ($value =~ /^__FROZEN__/) {
                   7367: 	substr($value,0,10,undef);
                   7368: 	$value=&unescape($value);
                   7369: 	return &thaw($value);
                   7370:     }
                   7371:     return &unescape($value);
                   7372: }
                   7373: 
1.436     albertel 7374: sub correct_line_ends {
                   7375:     my ($result)=@_;
                   7376:     $$result =~s/\r\n/\n/mg;
                   7377:     $$result =~s/\r/\n/mg;
1.415     albertel 7378: }
1.1       albertel 7379: # ================================================================ Main Program
                   7380: 
1.184     www      7381: sub goodbye {
1.204     albertel 7382:    &logthis("Starting Shut down");
1.443     albertel 7383: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7384:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7385: #converted
1.599     albertel 7386: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7387:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7388: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7389: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7390: #1.1 only
1.599     albertel 7391: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7392: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7393: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7394: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7395:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7396:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7397:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7398:    &flushcourselogs();
                   7399:    &logthis("Shutting down");
                   7400: }
                   7401: 
1.179     www      7402: BEGIN {
1.228     harris41 7403: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7404:     unless ($readit) {
1.217     harris41 7405: {
1.781     raeburn  7406:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7407:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7408: }
1.1       albertel 7409: 
1.327     albertel 7410: # ------------------------------------------------------------ Read domain file
                   7411: {
                   7412:     %domaindescription = ();
                   7413:     %domain_auth_def = ();
                   7414:     %domain_auth_arg_def = ();
1.448     albertel 7415:     my $fh;
                   7416:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7417: 	while (my $line = <$fh>) {
                   7418:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7419: #           next if /^\#/;
1.801     foxr     7420:            chomp $line;
1.403     www      7421:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7422: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7423: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7424:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7425: 	   $domaindescription{$domain}=$domain_description;
                   7426: 	   $domain_lang_def{$domain}=$def_lang;
                   7427: 	   $domain_city{$domain}=$city;
                   7428: 	   $domain_longi{$domain}=$longi;
                   7429: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7430:            $domain_primary{$domain}=$primary;
1.403     www      7431: 
1.448     albertel 7432:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7433: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7434: 	}
1.327     albertel 7435:     }
1.448     albertel 7436:     close ($fh);
1.327     albertel 7437: }
                   7438: 
                   7439: 
1.1       albertel 7440: # ------------------------------------------------------------- Read hosts file
                   7441: {
1.448     albertel 7442:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7443: 
                   7444:     while (my $configline=<$config>) {
1.303     matthew  7445:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7446:        chomp($configline);
1.595     albertel 7447:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7448:        $name=~s/\s//g;
1.595     albertel 7449:        if ($id && $domain && $role && $name) {
1.252     albertel 7450: 	 $hostname{$id}=$name;
                   7451: 	 $hostdom{$id}=$domain;
                   7452: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7453:        }
1.1       albertel 7454:     }
1.448     albertel 7455:     close($config);
1.619     albertel 7456:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7457:     #&get_iphost();
1.1       albertel 7458: }
                   7459: 
1.598     albertel 7460: sub get_iphost {
                   7461:     if (%iphost) { return %iphost; }
1.653     albertel 7462:     my %name_to_ip;
1.598     albertel 7463:     foreach my $id (keys(%hostname)) {
                   7464: 	my $name=$hostname{$id};
1.653     albertel 7465: 	my $ip;
                   7466: 	if (!exists($name_to_ip{$name})) {
                   7467: 	    $ip = gethostbyname($name);
                   7468: 	    if (!$ip || length($ip) ne 4) {
                   7469: 		&logthis("Skipping host $id name $name no IP found\n");
                   7470: 		next;
                   7471: 	    }
                   7472: 	    $ip=inet_ntoa($ip);
                   7473: 	    $name_to_ip{$name} = $ip;
                   7474: 	} else {
                   7475: 	    $ip = $name_to_ip{$name};
1.598     albertel 7476: 	}
                   7477: 	push(@{$iphost{$ip}},$id);
                   7478:     }
                   7479:     return %iphost;
                   7480: }
                   7481: 
1.1       albertel 7482: # ------------------------------------------------------ Read spare server file
                   7483: {
1.448     albertel 7484:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7485: 
                   7486:     while (my $configline=<$config>) {
                   7487:        chomp($configline);
1.284     matthew  7488:        if ($configline) {
1.784     albertel 7489: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7490: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7491: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7492:        }
                   7493:     }
1.448     albertel 7494:     close($config);
1.1       albertel 7495: }
1.11      www      7496: # ------------------------------------------------------------ Read permissions
                   7497: {
1.448     albertel 7498:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7499: 
                   7500:     while (my $configline=<$config>) {
1.448     albertel 7501: 	chomp($configline);
                   7502: 	if ($configline) {
                   7503: 	    my ($role,$perm)=split(/ /,$configline);
                   7504: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7505: 	}
1.11      www      7506:     }
1.448     albertel 7507:     close($config);
1.11      www      7508: }
                   7509: 
                   7510: # -------------------------------------------- Read plain texts for permissions
                   7511: {
1.448     albertel 7512:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7513: 
                   7514:     while (my $configline=<$config>) {
1.448     albertel 7515: 	chomp($configline);
                   7516: 	if ($configline) {
1.742     raeburn  7517: 	    my ($short,@plain)=split(/:/,$configline);
                   7518:             %{$prp{$short}} = ();
                   7519: 	    if (@plain > 0) {
                   7520:                 $prp{$short}{'std'} = $plain[0];
                   7521:                 for (my $i=1; $i<@plain; $i++) {
                   7522:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7523:                 }
                   7524:             }
1.448     albertel 7525: 	}
1.135     www      7526:     }
1.448     albertel 7527:     close($config);
1.135     www      7528: }
                   7529: 
                   7530: # ---------------------------------------------------------- Read package table
                   7531: {
1.448     albertel 7532:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7533: 
                   7534:     while (my $configline=<$config>) {
1.483     albertel 7535: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7536: 	chomp($configline);
                   7537: 	my ($short,$plain)=split(/:/,$configline);
                   7538: 	my ($pack,$name)=split(/\&/,$short);
                   7539: 	if ($plain ne '') {
                   7540: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7541: 	    $packagetab{$short}=$plain; 
                   7542: 	}
1.11      www      7543:     }
1.448     albertel 7544:     close($config);
1.329     matthew  7545: }
                   7546: 
                   7547: # ------------- set up temporary directory
                   7548: {
                   7549:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7550: 
1.11      www      7551: }
                   7552: 
1.794     albertel 7553: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7554: 				'compress_threshold'=> 20_000,
                   7555:  			        });
1.185     www      7556: 
1.281     www      7557: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7558: $dumpcount=0;
1.22      www      7559: 
1.163     harris41 7560: &logtouch();
1.672     albertel 7561: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7562: $readit=1;
1.564     albertel 7563:     {
                   7564: 	use integer;
                   7565: 	my $test=(2**32)+1;
1.568     albertel 7566: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7567: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7568:     }
1.195     www      7569: }
1.1       albertel 7570: }
1.179     www      7571: 
1.1       albertel 7572: 1;
1.191     harris41 7573: __END__
                   7574: 
1.243     albertel 7575: =pod
                   7576: 
1.191     harris41 7577: =head1 NAME
                   7578: 
1.243     albertel 7579: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7580: 
                   7581: =head1 SYNOPSIS
                   7582: 
1.243     albertel 7583: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7584: 
                   7585:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7586: 
1.243     albertel 7587: Common parameters:
                   7588: 
                   7589: =over 4
                   7590: 
                   7591: =item *
                   7592: 
                   7593: $uname : an internal username (if $cname expecting a course Id specifically)
                   7594: 
                   7595: =item *
                   7596: 
                   7597: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7598: 
                   7599: =item *
                   7600: 
                   7601: $symb : a resource instance identifier
                   7602: 
                   7603: =item *
                   7604: 
                   7605: $namespace : the name of a .db file that contains the data needed or
                   7606: being set.
                   7607: 
                   7608: =back
                   7609: 
1.394     bowersj2 7610: =head1 OVERVIEW
1.191     harris41 7611: 
1.394     bowersj2 7612: lonnet provides subroutines which interact with the
                   7613: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7614: about classes, users, and resources.
1.243     albertel 7615: 
                   7616: For many of these objects you can also use this to store data about
                   7617: them or modify them in various ways.
1.191     harris41 7618: 
1.394     bowersj2 7619: =head2 Symbs
1.191     harris41 7620: 
1.394     bowersj2 7621: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7622: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7623: map, the resource number of the resource in the map, and the URL of
                   7624: the resource itself. The latter is somewhat redundant, but might help
                   7625: if maps change.
                   7626: 
                   7627: An example is
                   7628: 
                   7629:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7630: 
                   7631: The respective map entry is
                   7632: 
                   7633:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7634:   title="Problem 2">
                   7635:  </resource>
                   7636: 
                   7637: Symbs are used by the random number generator, as well as to store and
                   7638: restore data specific to a certain instance of for example a problem.
                   7639: 
                   7640: =head2 Storing And Retrieving Data
                   7641: 
                   7642: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7643: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7644: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7645: is is the non-critical message twin of cstore. These functions are for
                   7646: handlers to store a perl hash to a user's permanent data space in an
                   7647: easy manner, and to retrieve it again on another call. It is expected
                   7648: that a handler would use this once at the beginning to retrieve data,
                   7649: and then again once at the end to send only the new data back.
                   7650: 
                   7651: The data is stored in the user's data directory on the user's
                   7652: homeserver under the ID of the course.
                   7653: 
                   7654: The hash that is returned by restore will have all of the previous
                   7655: value for all of the elements of the hash.
                   7656: 
                   7657: Example:
                   7658: 
                   7659:  #creating a hash
                   7660:  my %hash;
                   7661:  $hash{'foo'}='bar';
                   7662: 
                   7663:  #storing it
                   7664:  &Apache::lonnet::cstore(\%hash);
                   7665: 
                   7666:  #changing a value
                   7667:  $hash{'foo'}='notbar';
                   7668: 
                   7669:  #adding a new value
                   7670:  $hash{'bar'}='foo';
                   7671:  &Apache::lonnet::cstore(\%hash);
                   7672: 
                   7673:  #retrieving the hash
                   7674:  my %history=&Apache::lonnet::restore();
                   7675: 
                   7676:  #print the hash
                   7677:  foreach my $key (sort(keys(%history))) {
                   7678:    print("\%history{$key} = $history{$key}");
                   7679:  }
                   7680: 
                   7681: Will print out:
1.191     harris41 7682: 
1.394     bowersj2 7683:  %history{1:foo} = bar
                   7684:  %history{1:keys} = foo:timestamp
                   7685:  %history{1:timestamp} = 990455579
                   7686:  %history{2:bar} = foo
                   7687:  %history{2:foo} = notbar
                   7688:  %history{2:keys} = foo:bar:timestamp
                   7689:  %history{2:timestamp} = 990455580
                   7690:  %history{bar} = foo
                   7691:  %history{foo} = notbar
                   7692:  %history{timestamp} = 990455580
                   7693:  %history{version} = 2
                   7694: 
                   7695: Note that the special hash entries C<keys>, C<version> and
                   7696: C<timestamp> were added to the hash. C<version> will be equal to the
                   7697: total number of versions of the data that have been stored. The
                   7698: C<timestamp> attribute will be the UNIX time the hash was
                   7699: stored. C<keys> is available in every historical section to list which
                   7700: keys were added or changed at a specific historical revision of a
                   7701: hash.
                   7702: 
                   7703: B<Warning>: do not store the hash that restore returns directly. This
                   7704: will cause a mess since it will restore the historical keys as if the
                   7705: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7706: 
1.394     bowersj2 7707: Calling convention:
1.191     harris41 7708: 
1.394     bowersj2 7709:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7710:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7711: 
1.394     bowersj2 7712: For more detailed information, see lonnet specific documentation.
1.191     harris41 7713: 
1.394     bowersj2 7714: =head1 RETURN MESSAGES
1.191     harris41 7715: 
1.394     bowersj2 7716: =over 4
1.191     harris41 7717: 
1.394     bowersj2 7718: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7719: 
1.394     bowersj2 7720: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7721: when the connection is brought back up
1.191     harris41 7722: 
1.394     bowersj2 7723: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7724: for later delivery
1.191     harris41 7725: 
1.394     bowersj2 7726: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7727: 
1.394     bowersj2 7728: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7729: that was requested
1.191     harris41 7730: 
1.243     albertel 7731: =back
1.191     harris41 7732: 
1.243     albertel 7733: =head1 PUBLIC SUBROUTINES
1.191     harris41 7734: 
1.243     albertel 7735: =head2 Session Environment Functions
1.191     harris41 7736: 
1.243     albertel 7737: =over 4
1.191     harris41 7738: 
1.394     bowersj2 7739: =item * 
                   7740: X<appenv()>
                   7741: B<appenv(%hash)>: the value of %hash is written to
                   7742: the user envirnoment file, and will be restored for each access this
1.620     albertel 7743: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7744: process
1.191     harris41 7745: 
                   7746: =item *
1.394     bowersj2 7747: X<delenv()>
                   7748: B<delenv($regexp)>: removes all items from the session
                   7749: environment file that matches the regular expression in $regexp. The
1.620     albertel 7750: values are also delted from the current processes %env.
1.191     harris41 7751: 
1.795     albertel 7752: =item * get_env_multiple($name) 
                   7753: 
                   7754: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7755: values may be defined and end up as an array ref.
                   7756: 
                   7757: returns an array of values
                   7758: 
1.243     albertel 7759: =back
                   7760: 
                   7761: =head2 User Information
1.191     harris41 7762: 
1.243     albertel 7763: =over 4
1.191     harris41 7764: 
                   7765: =item *
1.394     bowersj2 7766: X<queryauthenticate()>
                   7767: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7768: authentication scheme
                   7769: 
                   7770: =item *
1.394     bowersj2 7771: X<authenticate()>
                   7772: B<authenticate($uname,$upass,$udom)>: try to
                   7773: authenticate user from domain's lib servers (first use the current
                   7774: one). C<$upass> should be the users password.
1.191     harris41 7775: 
                   7776: =item *
1.394     bowersj2 7777: X<homeserver()>
                   7778: B<homeserver($uname,$udom)>: find the server which has
                   7779: the user's directory and files (there must be only one), this caches
                   7780: the answer, and also caches if there is a borken connection.
1.191     harris41 7781: 
                   7782: =item *
1.394     bowersj2 7783: X<idget()>
                   7784: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7785: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7786: username, and only 1 username per ID in a specific domain) (returns
                   7787: hash: id=>name,id=>name)
1.191     harris41 7788: 
                   7789: =item *
1.394     bowersj2 7790: X<idrget()>
                   7791: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7792: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7793: 
                   7794: =item *
1.394     bowersj2 7795: X<idput()>
                   7796: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7797: 
                   7798: =item *
1.394     bowersj2 7799: X<rolesinit()>
                   7800: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7801: 
                   7802: =item *
1.551     albertel 7803: X<getsection()>
                   7804: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7805: course $cname, return section name/number or '' for "not in course"
                   7806: and '-1' for "no section"
                   7807: 
                   7808: =item *
1.394     bowersj2 7809: X<userenvironment()>
                   7810: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7811: passed in @what from the requested user's environment, returns a hash
                   7812: 
                   7813: =back
                   7814: 
                   7815: =head2 User Roles
                   7816: 
                   7817: =over 4
                   7818: 
                   7819: =item *
                   7820: 
1.810     raeburn  7821: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7822:  F: full access
                   7823:  U,I,K: authentication modes (cxx only)
                   7824:  '': forbidden
                   7825:  1: user needs to choose course
                   7826:  2: browse allowed
1.766     albertel 7827:  A: passphrase authentication needed
1.243     albertel 7828: 
                   7829: =item *
                   7830: 
                   7831: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7832: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7833: and course level
                   7834: 
                   7835: =item *
                   7836: 
                   7837: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7838: explanation of a user role term
                   7839: 
                   7840: =back
                   7841: 
                   7842: =head2 User Modification
                   7843: 
                   7844: =over 4
                   7845: 
                   7846: =item *
                   7847: 
                   7848: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7849: user for the level given by URL.  Optional start and end dates (leave empty
                   7850: string or zero for "no date")
1.191     harris41 7851: 
                   7852: =item *
                   7853: 
1.243     albertel 7854: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7855: change a users, password, possible return values are: ok,
                   7856: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7857: refused
1.191     harris41 7858: 
                   7859: =item *
                   7860: 
1.243     albertel 7861: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7862: 
                   7863: =item *
                   7864: 
1.243     albertel 7865: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7866: modify user
1.191     harris41 7867: 
                   7868: =item *
                   7869: 
1.286     matthew  7870: modifystudent
                   7871: 
                   7872: modify a students enrollment and identification information.
                   7873: The course id is resolved based on the current users environment.  
                   7874: This means the envoking user must be a course coordinator or otherwise
                   7875: associated with a course.
                   7876: 
1.297     matthew  7877: This call is essentially a wrapper for lonnet::modifyuser and
                   7878: lonnet::modify_student_enrollment
1.286     matthew  7879: 
                   7880: Inputs: 
                   7881: 
                   7882: =over 4
                   7883: 
                   7884: =item B<$udom> Students loncapa domain
                   7885: 
                   7886: =item B<$uname> Students loncapa login name
                   7887: 
                   7888: =item B<$uid> Students id/student number
                   7889: 
                   7890: =item B<$umode> Students authentication mode
                   7891: 
                   7892: =item B<$upass> Students password
                   7893: 
                   7894: =item B<$first> Students first name
                   7895: 
                   7896: =item B<$middle> Students middle name
                   7897: 
                   7898: =item B<$last> Students last name
                   7899: 
                   7900: =item B<$gene> Students generation
                   7901: 
                   7902: =item B<$usec> Students section in course
                   7903: 
                   7904: =item B<$end> Unix time of the roles expiration
                   7905: 
                   7906: =item B<$start> Unix time of the roles start date
                   7907: 
                   7908: =item B<$forceid> If defined, allow $uid to be changed
                   7909: 
                   7910: =item B<$desiredhome> server to use as home server for student
                   7911: 
                   7912: =back
1.297     matthew  7913: 
                   7914: =item *
                   7915: 
                   7916: modify_student_enrollment
                   7917: 
                   7918: Change a students enrollment status in a class.  The environment variable
                   7919: 'role.request.course' must be defined for this function to proceed.
                   7920: 
                   7921: Inputs:
                   7922: 
                   7923: =over 4
                   7924: 
                   7925: =item $udom, students domain
                   7926: 
                   7927: =item $uname, students name
                   7928: 
                   7929: =item $uid, students user id
                   7930: 
                   7931: =item $first, students first name
                   7932: 
                   7933: =item $middle
                   7934: 
                   7935: =item $last
                   7936: 
                   7937: =item $gene
                   7938: 
                   7939: =item $usec
                   7940: 
                   7941: =item $end
                   7942: 
                   7943: =item $start
                   7944: 
                   7945: =back
                   7946: 
1.191     harris41 7947: 
                   7948: =item *
                   7949: 
1.243     albertel 7950: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7951: custom role; give a custom role to a user for the level given by URL.  Specify
                   7952: name and domain of role author, and role name
1.191     harris41 7953: 
                   7954: =item *
                   7955: 
1.243     albertel 7956: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7957: 
                   7958: =item *
                   7959: 
1.243     albertel 7960: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7961: 
                   7962: =back
                   7963: 
                   7964: =head2 Course Infomation
                   7965: 
                   7966: =over 4
1.191     harris41 7967: 
                   7968: =item *
                   7969: 
1.631     albertel 7970: coursedescription($courseid) : returns a hash of information about the
                   7971: specified course id, including all environment settings for the
                   7972: course, the description of the course will be in the hash under the
                   7973: key 'description'
1.191     harris41 7974: 
                   7975: =item *
                   7976: 
1.624     albertel 7977: resdata($name,$domain,$type,@which) : request for current parameter
                   7978: setting for a specific $type, where $type is either 'course' or 'user',
                   7979: @what should be a list of parameters to ask about. This routine caches
                   7980: answers for 5 minutes.
1.243     albertel 7981: 
                   7982: =back
                   7983: 
                   7984: =head2 Course Modification
                   7985: 
                   7986: =over 4
1.191     harris41 7987: 
                   7988: =item *
                   7989: 
1.243     albertel 7990: writecoursepref($courseid,%prefs) : write preferences (environment
                   7991: database) for a course
1.191     harris41 7992: 
                   7993: =item *
                   7994: 
1.243     albertel 7995: createcourse($udom,$description,$url) : make/modify course
                   7996: 
                   7997: =back
                   7998: 
                   7999: =head2 Resource Subroutines
                   8000: 
                   8001: =over 4
1.191     harris41 8002: 
                   8003: =item *
                   8004: 
1.243     albertel 8005: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8006: 
                   8007: =item *
                   8008: 
1.243     albertel 8009: repcopy($filename) : subscribes to the requested file, and attempts to
                   8010: replicate from the owning library server, Might return
1.607     raeburn  8011: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8012: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8013: resource. Expects the local filesystem pathname
                   8014: (/home/httpd/html/res/....)
                   8015: 
                   8016: =back
                   8017: 
                   8018: =head2 Resource Information
                   8019: 
                   8020: =over 4
1.191     harris41 8021: 
                   8022: =item *
                   8023: 
1.243     albertel 8024: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8025: a vairety of different possible values, $varname should be a request
                   8026: string, and the other parameters can be used to specify who and what
                   8027: one is asking about.
                   8028: 
                   8029: Possible values for $varname are environment.lastname (or other item
                   8030: from the envirnment hash), user.name (or someother aspect about the
                   8031: user), resource.0.maxtries (or some other part and parameter of a
                   8032: resource)
1.204     albertel 8033: 
                   8034: =item *
                   8035: 
1.243     albertel 8036: directcondval($number) : get current value of a condition; reads from a state
                   8037: string
1.204     albertel 8038: 
                   8039: =item *
                   8040: 
1.243     albertel 8041: condval($condidx) : value of condition index based on state
1.204     albertel 8042: 
                   8043: =item *
                   8044: 
1.243     albertel 8045: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8046: resource's metadata, $what should be either a specific key, or either
                   8047: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8048: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8049: 
                   8050: this function automatically caches all requests
1.191     harris41 8051: 
                   8052: =item *
                   8053: 
1.243     albertel 8054: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8055: network of library servers; returns file handle of where SQL and regex results
                   8056: will be stored for query
1.191     harris41 8057: 
                   8058: =item *
                   8059: 
1.243     albertel 8060: symbread($filename) : return symbolic list entry (filename argument optional);
                   8061: returns the data handle
1.191     harris41 8062: 
                   8063: =item *
                   8064: 
1.243     albertel 8065: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8066: a possible symb for the URL in $thisfn, and if is an encryypted
                   8067: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8068: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8069: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8070: 
1.191     harris41 8071: 
                   8072: =item *
                   8073: 
1.243     albertel 8074: symbclean($symb) : removes versions numbers from a symb, returns the
                   8075: cleaned symb
1.191     harris41 8076: 
                   8077: =item *
                   8078: 
1.243     albertel 8079: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8080: course map, user must be in a course for it to work.
1.191     harris41 8081: 
                   8082: =item *
                   8083: 
1.243     albertel 8084: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8085: 
                   8086: =item *
                   8087: 
1.243     albertel 8088: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8089: a random seed, all arguments are optional, if they aren't sent it uses the
                   8090: environment to derive them. Note: if symb isn't sent and it can't get one
                   8091: from &symbread it will use the current time as its return value
1.191     harris41 8092: 
                   8093: =item *
                   8094: 
1.243     albertel 8095: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8096: unfakeable, receipt
1.191     harris41 8097: 
                   8098: =item *
                   8099: 
1.620     albertel 8100: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8101: 
                   8102: =item *
                   8103: 
1.243     albertel 8104: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8105: 
                   8106: =item *
                   8107: 
1.243     albertel 8108: 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 8109: 
                   8110: =item *
                   8111: 
1.243     albertel 8112: 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 8113: 
                   8114: =item *
                   8115: 
1.243     albertel 8116: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8117: 
                   8118: =item *
                   8119: 
1.243     albertel 8120: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8121: forcing spreadsheet to reevaluate the resource scores next time.
                   8122: 
                   8123: =back
                   8124: 
                   8125: =head2 Storing/Retreiving Data
                   8126: 
                   8127: =over 4
1.191     harris41 8128: 
                   8129: =item *
                   8130: 
1.243     albertel 8131: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8132: for this url; hashref needs to be given and should be a \%hashname; the
                   8133: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8134: be derived from the env
1.191     harris41 8135: 
                   8136: =item *
                   8137: 
1.243     albertel 8138: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8139: uses critical subroutine
1.191     harris41 8140: 
                   8141: =item *
                   8142: 
1.243     albertel 8143: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8144: all args are optional
1.191     harris41 8145: 
                   8146: =item *
                   8147: 
1.717     albertel 8148: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8149: dumps the complete (or key matching regexp) namespace into a hash
                   8150: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8151: normally &store()ed into
                   8152: 
                   8153: $range should be either an integer '100' (give me the first 100
                   8154:                                            matching records)
                   8155:               or be  two integers sperated by a - with no spaces
                   8156:                  '30-50' (give me the 30th through the 50th matching
                   8157:                           records)
                   8158: 
                   8159: 
                   8160: =item *
                   8161: 
                   8162: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8163: replaces a &store() version of data with a replacement set of data
                   8164: for a particular resource in a namespace passed in the $storehash hash 
                   8165: reference
                   8166: 
                   8167: =item *
                   8168: 
1.243     albertel 8169: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8170: works very similar to store/cstore, but all data is stored in a
                   8171: temporary location and can be reset using tmpreset, $storehash should
                   8172: be a hash reference, returns nothing on success
1.191     harris41 8173: 
                   8174: =item *
                   8175: 
1.243     albertel 8176: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8177: similar to restore, but all data is stored in a temporary location and
                   8178: can be reset using tmpreset. Returns a hash of values on success,
                   8179: error string otherwise.
1.191     harris41 8180: 
                   8181: =item *
                   8182: 
1.243     albertel 8183: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8184: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8185: 
                   8186: =item *
                   8187: 
1.243     albertel 8188: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8189: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8190: 
                   8191: =item *
                   8192: 
1.243     albertel 8193: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8194: namesp ($udom and $uname are optional)
1.191     harris41 8195: 
                   8196: =item *
                   8197: 
1.702     albertel 8198: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8199: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8200: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8201: 
1.702     albertel 8202: $range should be either an integer '100' (give me the first 100
                   8203:                                            matching records)
                   8204:               or be  two integers sperated by a - with no spaces
                   8205:                  '30-50' (give me the 30th through the 50th matching
                   8206:                           records)
1.449     matthew  8207: =item *
                   8208: 
                   8209: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8210: $store can be a scalar, an array reference, or if the amount to be 
                   8211: incremented is > 1, a hash reference.
                   8212: 
                   8213: ($udom and $uname are optional)
1.191     harris41 8214: 
                   8215: =item *
                   8216: 
1.243     albertel 8217: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8218: ($udom and $uname are optional)
1.191     harris41 8219: 
                   8220: =item *
                   8221: 
1.243     albertel 8222: cput($namespace,$storehash,$udom,$uname) : critical put
                   8223: ($udom and $uname are optional)
1.191     harris41 8224: 
                   8225: =item *
                   8226: 
1.748     albertel 8227: newput($namespace,$storehash,$udom,$uname) :
                   8228: 
                   8229: Attempts to store the items in the $storehash, but only if they don't
                   8230: currently exist, if this succeeds you can be certain that you have 
                   8231: successfully created a new key value pair in the $namespace db.
                   8232: 
                   8233: 
                   8234: Args:
                   8235:  $namespace: name of database to store values to
                   8236:  $storehash: hashref to store to the db
                   8237:  $udom: (optional) domain of user containing the db
                   8238:  $uname: (optional) name of user caontaining the db
                   8239: 
                   8240: Returns:
                   8241:  'ok' -> succeeded in storing all keys of $storehash
                   8242:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8243:                         least <key> already existed in the db (other
                   8244:                         requested keys may also already exist)
                   8245:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8246:  'con_lost' -> unable to contact request server
                   8247:  'refused' -> action was not allowed by remote machine
                   8248: 
                   8249: 
                   8250: =item *
                   8251: 
1.243     albertel 8252: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8253: reference filled in from namesp (encrypts the return communication)
                   8254: ($udom and $uname are optional)
1.191     harris41 8255: 
                   8256: =item *
                   8257: 
1.243     albertel 8258: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8259: critical subroutine
                   8260: 
1.806     raeburn  8261: =item *
                   8262: 
                   8263: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8264: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8265: 
                   8266: =item *
                   8267: 
                   8268: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8269: 
1.243     albertel 8270: =back
                   8271: 
                   8272: =head2 Network Status Functions
                   8273: 
                   8274: =over 4
1.191     harris41 8275: 
                   8276: =item *
                   8277: 
                   8278: dirlist($uri) : return directory list based on URI
                   8279: 
                   8280: =item *
                   8281: 
1.243     albertel 8282: spareserver() : find server with least workload from spare.tab
                   8283: 
                   8284: =back
                   8285: 
                   8286: =head2 Apache Request
                   8287: 
                   8288: =over 4
1.191     harris41 8289: 
                   8290: =item *
                   8291: 
1.243     albertel 8292: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8293: localhost, posts hash
                   8294: 
                   8295: =back
                   8296: 
                   8297: =head2 Data to String to Data
                   8298: 
                   8299: =over 4
1.191     harris41 8300: 
                   8301: =item *
                   8302: 
1.243     albertel 8303: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8304: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8305: 
                   8306: =item *
                   8307: 
1.243     albertel 8308: hashref2str($hashref) : convert a hashref into a string complete with
                   8309: escaping and '=' and '&' separators, supports elements that are
                   8310: arrayrefs and hashrefs
1.191     harris41 8311: 
                   8312: =item *
                   8313: 
1.243     albertel 8314: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8315: with escaping and '&' separators, supports elements that are arrayrefs
                   8316: and hashrefs
1.191     harris41 8317: 
                   8318: =item *
                   8319: 
1.243     albertel 8320: str2hash($string) : convert string to hash using unescaping and
                   8321: splitting on '=' and '&', supports elements that are arrayrefs and
                   8322: hashrefs
1.191     harris41 8323: 
                   8324: =item *
                   8325: 
1.243     albertel 8326: str2array($string) : convert string to hash using unescaping and
                   8327: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8328: 
                   8329: =back
                   8330: 
                   8331: =head2 Logging Routines
                   8332: 
                   8333: =over 4
                   8334: 
                   8335: These routines allow one to make log messages in the lonnet.log and
                   8336: lonnet.perm logfiles.
1.191     harris41 8337: 
                   8338: =item *
                   8339: 
1.243     albertel 8340: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8341: 
                   8342: =item *
                   8343: 
1.243     albertel 8344: logthis() : append message to the normal lonnet.log file, it gets
                   8345: preiodically rolled over and deleted.
1.191     harris41 8346: 
                   8347: =item *
                   8348: 
1.243     albertel 8349: logperm() : append a permanent message to lonnet.perm.log, this log
                   8350: file never gets deleted by any automated portion of the system, only
                   8351: messages of critical importance should go in here.
                   8352: 
                   8353: =back
                   8354: 
                   8355: =head2 General File Helper Routines
                   8356: 
                   8357: =over 4
1.191     harris41 8358: 
                   8359: =item *
                   8360: 
1.481     raeburn  8361: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8362: (a) files in /uploaded
                   8363:   (i) If a local copy of the file exists - 
                   8364:       compares modification date of local copy with last-modified date for 
                   8365:       definitive version stored on home server for course. If local copy is 
                   8366:       stale, requests a new version from the home server and stores it. 
                   8367:       If the original has been removed from the home server, then local copy 
                   8368:       is unlinked.
                   8369:   (ii) If local copy does not exist -
                   8370:       requests the file from the home server and stores it. 
                   8371:   
                   8372:   If $caller is 'uploadrep':  
                   8373:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8374:     for request for files originally uploaded via DOCS. 
                   8375:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8376:   
                   8377:   Otherwise:
                   8378:      This indicates a call from the content generation phase of the request.
                   8379:      -  returns the entire contents of the file or -1.
                   8380:      
                   8381: (b) files in /res
                   8382:    - returns the entire contents of a file or -1; 
                   8383:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8384: 
1.712     albertel 8385: 
                   8386: =item *
                   8387: 
                   8388: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8389:                   reference
                   8390: 
                   8391: returns either a stat() list of data about the file or an empty list
                   8392: if the file doesn't exist or couldn't find out about it (connection
                   8393: problems or user unknown)
                   8394: 
1.191     harris41 8395: =item *
                   8396: 
1.243     albertel 8397: filelocation($dir,$file) : returns file system location of a file
                   8398: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8399: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8400: and a file of ../bob will become /a/bob)
1.191     harris41 8401: 
                   8402: =item *
                   8403: 
                   8404: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8405: filelocation except for hrefs
                   8406: 
                   8407: =item *
                   8408: 
                   8409: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8410: 
1.243     albertel 8411: =back
                   8412: 
1.608     albertel 8413: =head2 Usererfile file routines (/uploaded*)
                   8414: 
                   8415: =over 4
                   8416: 
                   8417: =item *
                   8418: 
                   8419: userfileupload(): main rotine for putting a file in a user or course's
                   8420:                   filespace, arguments are,
                   8421: 
1.620     albertel 8422:  formname - required - this is the name of the element in $env where the
1.608     albertel 8423:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8424:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8425:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8426:  coursedoc - if true, store the file in the course of the active role
                   8427:              of the current user
                   8428:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8429:          if undefined, it will be placed in "unknown"
                   8430: 
                   8431:  (This routine calls clean_filename() to remove any dangerous
                   8432:  characters from the filename, and then calls finuserfileupload() to
                   8433:  complete the transaction)
                   8434: 
                   8435:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8436:  and /adm/notfound.html if unsuccessful
                   8437: 
                   8438: =item *
                   8439: 
                   8440: clean_filename(): routine for cleaing a filename up for storage in
                   8441:                  userfile space, argument is:
                   8442: 
                   8443:  filename - proposed filename
                   8444: 
                   8445: returns: the new clean filename
                   8446: 
                   8447: =item *
                   8448: 
                   8449: finishuserfileupload(): routine that creaes and sends the file to
                   8450: userspace, probably shouldn't be called directly
                   8451: 
                   8452:   docuname: username or courseid of destination for the file
                   8453:   docudom: domain of user/course of destination for the file
                   8454:   formname: same as for userfileupload()
                   8455:   fname: filename (inculding subdirectories) for the file
                   8456: 
                   8457:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8458:  and /adm/notfound.html if unsuccessful
                   8459: 
                   8460: =item *
                   8461: 
                   8462: renameuserfile(): renames an existing userfile to a new name
                   8463: 
                   8464:   Args:
                   8465:    docuname: username or courseid of destination for the file
                   8466:    docudom: domain of user/course of destination for the file
                   8467:    old: current file name (including any subdirs under userfiles)
                   8468:    new: desired file name (including any subdirs under userfiles)
                   8469: 
                   8470: =item *
                   8471: 
                   8472: mkdiruserfile(): creates a directory is a userfiles dir
                   8473: 
                   8474:   Args:
                   8475:    docuname: username or courseid of destination for the file
                   8476:    docudom: domain of user/course of destination for the file
                   8477:    dir: dir to create (including any subdirs under userfiles)
                   8478: 
                   8479: =item *
                   8480: 
                   8481: removeuserfile(): removes a file that exists in userfiles
                   8482: 
                   8483:   Args:
                   8484:    docuname: username or courseid of destination for the file
                   8485:    docudom: domain of user/course of destination for the file
                   8486:    fname: filname to delete (including any subdirs under userfiles)
                   8487: 
                   8488: =item *
                   8489: 
                   8490: removeuploadedurl(): convience function for removeuserfile()
                   8491: 
                   8492:   Args:
                   8493:    url:  a full /uploaded/... url to delete
                   8494: 
1.747     albertel 8495: =item * 
                   8496: 
                   8497: get_portfile_permissions():
                   8498:   Args:
                   8499:     domain: domain of user or course contain the portfolio files
                   8500:     user: name of user or num of course contain the portfolio files
                   8501:   Returns:
                   8502:     hashref of a dump of the proper file_permissions.db
                   8503:    
                   8504: 
                   8505: =item * 
                   8506: 
                   8507: get_access_controls():
                   8508: 
                   8509: Args:
                   8510:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8511:   group: (optional) the group you want the files associated with
                   8512:   file: (optional) the file you want access info on
                   8513: 
                   8514: Returns:
1.749     raeburn  8515:     a hash (keys are file names) of hashes containing
                   8516:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8517:         values are XML containing access control settings (see below) 
1.747     albertel 8518: 
                   8519: Internal notes:
                   8520: 
1.749     raeburn  8521:  access controls are stored in file_permissions.db as key=value pairs.
                   8522:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8523:         where scope -> public,guest,course,group,domains or users.
                   8524:               end -> UNIX time for end of access (0 -> no end date)
                   8525:               start -> UNIX time for start of access
                   8526: 
                   8527:     value -> XML description of access control
                   8528:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8529:             <start></start>
                   8530:             <end></end>
                   8531: 
                   8532:             <password></password>  for scope type = guest
                   8533: 
                   8534:             <domain></domain>     for scope type = course or group
                   8535:             <number></number>
                   8536:             <roles id="">
                   8537:              <role></role>
                   8538:              <access></access>
                   8539:              <section></section>
                   8540:              <group></group>
                   8541:             </roles>
                   8542: 
                   8543:             <dom></dom>         for scope type = domains
                   8544: 
                   8545:             <users>             for scope type = users
                   8546:              <user>
                   8547:               <uname></uname>
                   8548:               <udom></udom>
                   8549:              </user>
                   8550:             </users>
                   8551:            </scope> 
                   8552:               
                   8553:  Access data is also aggregated for each file in an additional key=value pair:
                   8554:  key -> path to file/file_name\0accesscontrol 
                   8555:  value -> reference to hash
                   8556:           hash contains key = value pairs
                   8557:           where key = uniqueID:scope_end_start
                   8558:                 value = UNIX time record was last updated
                   8559: 
                   8560:           Used to improve speed of look-ups of access controls for each file.  
                   8561:  
                   8562:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8563: 
                   8564: modify_access_controls():
                   8565: 
                   8566: Modifies access controls for a portfolio file
                   8567: Args
                   8568: 1. file name
                   8569: 2. reference to hash of required changes,
                   8570: 3. domain
                   8571: 4. username
                   8572:   where domain,username are the domain of the portfolio owner 
                   8573:   (either a user or a course) 
                   8574: 
                   8575: Returns:
                   8576: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8577: 2. result of deletions ('ok' or 'error', with error message).
                   8578: 3. reference to hash of any new or updated access controls.
                   8579: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8580:    key = integer (inbound ID)
                   8581:    value = uniqueID  
1.747     albertel 8582: 
1.608     albertel 8583: =back
                   8584: 
1.243     albertel 8585: =head2 HTTP Helper Routines
                   8586: 
                   8587: =over 4
                   8588: 
1.191     harris41 8589: =item *
                   8590: 
                   8591: escape() : unpack non-word characters into CGI-compatible hex codes
                   8592: 
                   8593: =item *
                   8594: 
                   8595: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8596: 
1.243     albertel 8597: =back
                   8598: 
                   8599: =head1 PRIVATE SUBROUTINES
                   8600: 
                   8601: =head2 Underlying communication routines (Shouldn't call)
                   8602: 
                   8603: =over 4
                   8604: 
                   8605: =item *
                   8606: 
                   8607: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8608: 
                   8609: =item *
                   8610: 
                   8611: reply() : uses subreply to send a message to remote machine, logs all failures
                   8612: 
                   8613: =item *
                   8614: 
                   8615: critical() : passes a critical message to another server; if cannot
                   8616: get through then place message in connection buffer directory and
                   8617: returns con_delayed, if incapable of saving message, returns
                   8618: con_failed
                   8619: 
                   8620: =item *
                   8621: 
                   8622: reconlonc() : tries to reconnect lonc client processes.
                   8623: 
                   8624: =back
                   8625: 
                   8626: =head2 Resource Access Logging
                   8627: 
                   8628: =over 4
                   8629: 
                   8630: =item *
                   8631: 
                   8632: flushcourselogs() : flush (save) buffer logs and access logs
                   8633: 
                   8634: =item *
                   8635: 
                   8636: courselog($what) : save message for course in hash
                   8637: 
                   8638: =item *
                   8639: 
                   8640: courseacclog($what) : save message for course using &courselog().  Perform
                   8641: special processing for specific resource types (problems, exams, quizzes, etc).
                   8642: 
1.191     harris41 8643: =item *
                   8644: 
                   8645: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8646: as a PerlChildExitHandler
1.243     albertel 8647: 
                   8648: =back
                   8649: 
                   8650: =head2 Other
                   8651: 
                   8652: =over 4
                   8653: 
                   8654: =item *
                   8655: 
                   8656: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8657: 
                   8658: =back
                   8659: 
                   8660: =cut

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