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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.823   ! albertel    4: # $Id: lonnet.pm,v 1.822 2007/01/11 21:09:10 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.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.823   ! albertel 1704: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
        !          1705:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1706:             my $sqlresult = 
1.823   ! albertel 1707:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1708:                                         'portfolio_metadata',$group,
                   1709:                                         'delete');
1.798     raeburn  1710:         }
                   1711:     }
                   1712:     return $result;
1.257     www      1713: }
1.15      www      1714: 
1.530     albertel 1715: sub mkdiruserfile {
                   1716:     my ($docuname,$docudom,$dir)=@_;
                   1717:     my $home=&homeserver($docuname,$docudom);
                   1718:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1719: }
                   1720: 
1.531     albertel 1721: sub renameuserfile {
                   1722:     my ($docuname,$docudom,$old,$new)=@_;
                   1723:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1724:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1725:                         &escape("$old").':'.&escape("$new"),$home);
                   1726:     if ($result eq 'ok') {
                   1727:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1728:             my $oldmeta = $old.'.meta';
                   1729:             my $newmeta = $new.'.meta';
                   1730:             my $metaresult = 
                   1731:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823   ! albertel 1732: 	    my $url = "/uploaded/$docudom/$docuname/$old";
        !          1733:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1734:             my $sqlresult = 
1.823   ! albertel 1735:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1736:                                         'portfolio_metadata',$group,
                   1737:                                         'delete');
1.798     raeburn  1738:         }
                   1739:     }
                   1740:     return $result;
1.531     albertel 1741: }
                   1742: 
1.14      www      1743: # ------------------------------------------------------------------------- Log
                   1744: 
                   1745: sub log {
                   1746:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1747:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1748: }
                   1749: 
                   1750: # ------------------------------------------------------------------ Course Log
1.352     www      1751: #
                   1752: # This routine flushes several buffers of non-mission-critical nature
                   1753: #
1.157     www      1754: 
                   1755: sub flushcourselogs {
1.352     www      1756:     &logthis('Flushing log buffers');
                   1757: #
                   1758: # course logs
                   1759: # This is a log of all transactions in a course, which can be used
                   1760: # for data mining purposes
                   1761: #
                   1762: # It also collects the courseid database, which lists last transaction
                   1763: # times and course titles for all courseids
                   1764: #
                   1765:     my %courseidbuffer=();
1.800     albertel 1766:     foreach my $crsid (keys %courselogs) {
1.352     www      1767:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1768: 		          &escape($courselogs{$crsid}),
                   1769: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1770: 	    delete $courselogs{$crsid};
                   1771:         } else {
                   1772:             &logthis('Failed to flush log buffer for '.$crsid);
                   1773:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1774:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1775:                         " exceeded maximum size, deleting.</font>");
                   1776:                delete $courselogs{$crsid};
                   1777:             }
1.352     www      1778:         }
                   1779:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1780:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1781: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1782:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1783:         } else {
                   1784:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1785: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1786:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1787:         }
1.191     harris41 1788:     }
1.352     www      1789: #
                   1790: # Write course id database (reverse lookup) to homeserver of courses 
                   1791: # Is used in pickcourse
                   1792: #
1.800     albertel 1793:     foreach my $crsid (keys(%courseidbuffer)) {
                   1794:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1795:     }
                   1796: #
                   1797: # File accesses
                   1798: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1799: #
1.449     matthew  1800:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1801:         if ($entry =~ /___count$/) {
                   1802:             my ($dom,$name);
1.807     albertel 1803:             ($dom,$name,undef)=
1.811     albertel 1804: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1805:             if (! defined($dom) || $dom eq '' || 
                   1806:                 ! defined($name) || $name eq '') {
1.620     albertel 1807:                 my $cid = $env{'request.course.id'};
                   1808:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1809:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1810:             }
1.450     matthew  1811:             my $value = $accesshash{$entry};
                   1812:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1813:             my %temphash=($url => $value);
1.449     matthew  1814:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1815:             if ($result eq 'ok') {
                   1816:                 delete $accesshash{$entry};
                   1817:             } elsif ($result eq 'unknown_cmd') {
                   1818:                 # Target server has old code running on it.
1.450     matthew  1819:                 my %temphash=($entry => $value);
1.449     matthew  1820:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1821:                     delete $accesshash{$entry};
                   1822:                 }
                   1823:             }
                   1824:         } else {
1.811     albertel 1825:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1826:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1827:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1828:                 delete $accesshash{$entry};
                   1829:             }
1.185     www      1830:         }
1.191     harris41 1831:     }
1.352     www      1832: #
                   1833: # Roles
                   1834: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1835: #
1.800     albertel 1836:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1837:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1838: 	    split(/\:/,$entry);
                   1839:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1840:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1841:                 $rudom,$runame) eq 'ok') {
                   1842: 	    delete $userrolehash{$entry};
                   1843:         }
                   1844:     }
1.662     raeburn  1845: #
                   1846: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1847: #
                   1848:     my %domrolebuffer = ();
                   1849:     foreach my $entry (keys %domainrolehash) {
                   1850:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1851:         if ($domrolebuffer{$rudom}) {
                   1852:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1853:                       '='.&escape($domainrolehash{$entry});
                   1854:         } else {
                   1855:             $domrolebuffer{$rudom}.=&escape($entry).
                   1856:                       '='.&escape($domainrolehash{$entry});
                   1857:         }
                   1858:         delete $domainrolehash{$entry};
                   1859:     }
                   1860:     foreach my $dom (keys(%domrolebuffer)) {
                   1861:         foreach my $tryserver (keys %libserv) {
                   1862:             if ($hostdom{$tryserver} eq $dom) {
                   1863:                 unless (&reply('domroleput:'.$dom.':'.
                   1864:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1865:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1866:                 }
                   1867:             }
                   1868:         }
                   1869:     }
1.186     www      1870:     $dumpcount++;
1.157     www      1871: }
                   1872: 
                   1873: sub courselog {
                   1874:     my $what=shift;
1.158     www      1875:     $what=time.':'.$what;
1.620     albertel 1876:     unless ($env{'request.course.id'}) { return ''; }
                   1877:     $coursedombuf{$env{'request.course.id'}}=
                   1878:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1879:     $coursenumbuf{$env{'request.course.id'}}=
                   1880:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1881:     $coursehombuf{$env{'request.course.id'}}=
                   1882:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1883:     $coursedescrbuf{$env{'request.course.id'}}=
                   1884:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1885:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1886:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1887:     $courseownerbuf{$env{'request.course.id'}}=
                   1888:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1889:     $coursetypebuf{$env{'request.course.id'}}=
                   1890:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1891:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1892: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1893:     } else {
1.620     albertel 1894: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1895:     }
1.620     albertel 1896:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1897: 	&flushcourselogs();
                   1898:     }
1.158     www      1899: }
                   1900: 
                   1901: sub courseacclog {
                   1902:     my $fnsymb=shift;
1.620     albertel 1903:     unless ($env{'request.course.id'}) { return ''; }
                   1904:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1905:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1906:         $what.=':POST';
1.583     matthew  1907:         # FIXME: Probably ought to escape things....
1.800     albertel 1908: 	foreach my $key (keys(%env)) {
                   1909:             if ($key=~/^form\.(.*)/) {
                   1910: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1911:             }
1.191     harris41 1912:         }
1.583     matthew  1913:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1914:         # FIXME: We should not be depending on a form parameter that someone
                   1915:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1916:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1917:             $what.= ':POST';
                   1918:             # FIXME: Probably ought to escape things....
                   1919:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1920:                                  'crsdiscuss') {
1.620     albertel 1921:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1922:             }
                   1923:         }
1.158     www      1924:     }
                   1925:     &courselog($what);
1.149     www      1926: }
                   1927: 
1.185     www      1928: sub countacc {
                   1929:     my $url=&declutter(shift);
1.458     matthew  1930:     return if (! defined($url) || $url eq '');
1.620     albertel 1931:     unless ($env{'request.course.id'}) { return ''; }
                   1932:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1933:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1934:     $accesshash{$key}++;
1.185     www      1935: }
1.349     www      1936: 
1.361     www      1937: sub linklog {
                   1938:     my ($from,$to)=@_;
                   1939:     $from=&declutter($from);
                   1940:     $to=&declutter($to);
                   1941:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1942:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1943: }
                   1944:   
1.349     www      1945: sub userrolelog {
                   1946:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1947:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1948:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1949:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1950:         ($trole=~/^ta/)) {
1.350     www      1951:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1952:        $userrolehash
                   1953:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1954:                     =$tend.':'.$tstart;
1.662     raeburn  1955:     }
                   1956:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1957:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1958:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1959:         ($trole=~/^sc/)) {
                   1960:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1961:        $domainrolehash
                   1962:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1963:                     = $tend.':'.$tstart;
                   1964:     }
1.351     www      1965: }
                   1966: 
                   1967: sub get_course_adv_roles {
                   1968:     my $cid=shift;
1.620     albertel 1969:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1970:     my %coursehash=&coursedescription($cid);
1.470     www      1971:     my %nothide=();
1.800     albertel 1972:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1973: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      1974:     }
1.351     www      1975:     my %returnhash=();
                   1976:     my %dumphash=
                   1977:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1978:     my $now=time;
1.800     albertel 1979:     foreach my $entry (keys %dumphash) {
                   1980: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      1981:         if (($tstart) && ($tstart<0)) { next; }
                   1982:         if (($tend) && ($tend<$now)) { next; }
                   1983:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1984:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 1985: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1986: 	if ((&privileged($username,$domain)) && 
                   1987: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1988: 	if ($role eq 'cr') { next; }
1.351     www      1989:         my $key=&plaintext($role);
                   1990:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1991:         if ($returnhash{$key}) {
                   1992: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1993:         } else {
                   1994:             $returnhash{$key}=$username.':'.$domain;
                   1995:         }
1.400     www      1996:      }
                   1997:     return %returnhash;
                   1998: }
                   1999: 
                   2000: sub get_my_roles {
                   2001:     my ($uname,$udom)=@_;
1.620     albertel 2002:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2003:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2004:     my %dumphash=
                   2005:             &dump('nohist_userroles',$udom,$uname);
                   2006:     my %returnhash=();
                   2007:     my $now=time;
1.800     albertel 2008:     foreach my $entry (keys(%dumphash)) {
                   2009: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2010:         if (($tstart) && ($tstart<0)) { next; }
                   2011:         if (($tend) && ($tend<$now)) { next; }
                   2012:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2013:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2014: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2015:      }
                   2016:     return %returnhash;
1.399     www      2017: }
                   2018: 
                   2019: # ----------------------------------------------------- Frontpage Announcements
                   2020: #
                   2021: #
                   2022: 
                   2023: sub postannounce {
                   2024:     my ($server,$text)=@_;
                   2025:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2026:     unless ($text=~/\w/) { $text=''; }
                   2027:     return &reply('setannounce:'.&escape($text),$server);
                   2028: }
                   2029: 
                   2030: sub getannounce {
1.448     albertel 2031: 
                   2032:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2033: 	my $announcement='';
1.800     albertel 2034: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2035: 	close($fh);
1.399     www      2036: 	if ($announcement=~/\w/) { 
                   2037: 	    return 
                   2038:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2039:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2040: 	} else {
                   2041: 	    return '';
                   2042: 	}
                   2043:     } else {
                   2044: 	return '';
                   2045:     }
1.351     www      2046: }
1.353     www      2047: 
                   2048: # ---------------------------------------------------------- Course ID routines
                   2049: # Deal with domain's nohist_courseid.db files
                   2050: #
                   2051: 
                   2052: sub courseidput {
                   2053:     my ($domain,$what,$coursehome)=@_;
                   2054:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2055: }
                   2056: 
                   2057: sub courseiddump {
1.791     raeburn  2058:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2059:     my %returnhash=();
1.355     www      2060:     unless ($domfilter) { $domfilter=''; }
1.353     www      2061:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2062:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2063: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2064: 	        foreach my $line (
1.506     raeburn  2065:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2066: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2067:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2068:                                $tryserver))) {
1.800     albertel 2069: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2070:                     if (($key) && ($value)) {
1.516     raeburn  2071: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2072:                     }
1.353     www      2073:                 }
                   2074:             }
                   2075:         }
                   2076:     }
                   2077:     return %returnhash;
                   2078: }
                   2079: 
1.658     raeburn  2080: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2081: 
                   2082: sub dcmailput {
1.685     raeburn  2083:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2084:     my $status = &Apache::lonnet::critical(
1.740     www      2085:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2086:        &escape($message),$server);
1.662     raeburn  2087:     return $status;
                   2088: }
                   2089: 
1.658     raeburn  2090: sub dcmaildump {
                   2091:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2092:     my %returnhash=();
                   2093:     if (exists($domain_primary{$dom})) {
                   2094:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2095:                                                          &escape($enddate).':';
                   2096: 	my @esc_senders=map { &escape($_)} @$senders;
                   2097: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2098: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2099:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2100:             if (($key) && ($value)) {
                   2101:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2102:             }
                   2103:         }
                   2104:     }
                   2105:     return %returnhash;
                   2106: }
1.662     raeburn  2107: # ---------------------------------------------------------- Domain roles
                   2108: 
                   2109: sub get_domain_roles {
                   2110:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2111:     if (undef($startdate) || $startdate eq '') {
                   2112:         $startdate = '.';
                   2113:     }
                   2114:     if (undef($enddate) || $enddate eq '') {
                   2115:         $enddate = '.';
                   2116:     }
                   2117:     my $rolelist = join(':',@{$roles});
                   2118:     my %personnel = ();
                   2119:     foreach my $tryserver (keys(%libserv)) {
                   2120:         if ($hostdom{$tryserver} eq $dom) {
                   2121:             %{$personnel{$tryserver}}=();
1.800     albertel 2122:             foreach my $line (
1.662     raeburn  2123:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2124:                    &escape($startdate).':'.&escape($enddate).':'.
                   2125:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2126:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2127:                 if (($key) && ($value)) {
                   2128:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2129:                 }
                   2130:             }
                   2131:         }
                   2132:     }
                   2133:     return %personnel;
                   2134: }
1.658     raeburn  2135: 
1.149     www      2136: # ----------------------------------------------------------- Check out an item
                   2137: 
1.504     albertel 2138: sub get_first_access {
                   2139:     my ($type,$argsymb)=@_;
1.790     albertel 2140:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2141:     if ($argsymb) { $symb=$argsymb; }
                   2142:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2143:     if ($type eq 'map') {
                   2144: 	$res=&symbread($map);
                   2145:     } else {
                   2146: 	$res=$symb;
                   2147:     }
                   2148:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2149:     return $times{"$courseid\0$res"};
1.504     albertel 2150: }
                   2151: 
                   2152: sub set_first_access {
                   2153:     my ($type)=@_;
1.790     albertel 2154:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2155:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2156:     if ($type eq 'map') {
                   2157: 	$res=&symbread($map);
                   2158:     } else {
                   2159: 	$res=$symb;
                   2160:     }
                   2161:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2162:     if (!$firstaccess) {
1.588     albertel 2163: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2164:     }
                   2165:     return 'already_set';
1.504     albertel 2166: }
                   2167: 
1.149     www      2168: sub checkout {
                   2169:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2170:     my $now=time;
                   2171:     my $lonhost=$perlvar{'lonHostID'};
                   2172:     my $infostr=&escape(
1.234     www      2173:                  'CHECKOUTTOKEN&'.
1.149     www      2174:                  $tuname.'&'.
                   2175:                  $tudom.'&'.
                   2176:                  $tcrsid.'&'.
                   2177:                  $symb.'&'.
                   2178: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2179:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2180:     if ($token=~/^error\:/) { 
1.672     albertel 2181:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2182:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2183:                  "</font>");
                   2184:         return ''; 
                   2185:     }
                   2186: 
1.149     www      2187:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2188:     $token=~tr/a-z/A-Z/;
                   2189: 
1.153     www      2190:     my %infohash=('resource.0.outtoken' => $token,
                   2191:                   'resource.0.checkouttime' => $now,
                   2192:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2193: 
                   2194:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2195:        return '';
1.151     www      2196:     } else {
1.672     albertel 2197:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2198:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2199:                  "</font>");
1.149     www      2200:     }    
                   2201: 
                   2202:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2203:                          &escape('Checkout '.$infostr.' - '.
                   2204:                                                  $token)) ne 'ok') {
                   2205: 	return '';
1.151     www      2206:     } else {
1.672     albertel 2207:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2208:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2209:                  "</font>");
1.149     www      2210:     }
1.151     www      2211:     return $token;
1.149     www      2212: }
                   2213: 
                   2214: # ------------------------------------------------------------ Check in an item
                   2215: 
                   2216: sub checkin {
                   2217:     my $token=shift;
1.150     www      2218:     my $now=time;
                   2219:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2220:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2221:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2222:     $dtoken=~s/\W/\_/g;
1.234     www      2223:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2224:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2225: 
1.154     www      2226:     unless (($tuname) && ($tudom)) {
                   2227:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2228:         return '';
                   2229:     }
                   2230:     
                   2231:     unless (&allowed('mgr',$tcrsid)) {
                   2232:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2233:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2234:         return '';
                   2235:     }
                   2236: 
1.153     www      2237:     my %infohash=('resource.0.intoken' => $token,
                   2238:                   'resource.0.checkintime' => $now,
                   2239:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2240: 
                   2241:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2242:        return '';
                   2243:     }    
                   2244: 
                   2245:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2246:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2247: 	return '';
                   2248:     }
                   2249: 
                   2250:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2251: }
                   2252: 
                   2253: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2254: 
                   2255: sub expirespread {
                   2256:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2257:     my $cid=$env{'request.course.id'}; 
1.110     www      2258:     if ($cid) {
                   2259:        my $now=time;
                   2260:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2261:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2262:                             $env{'course.'.$cid.'.num'}.
1.110     www      2263: 	        	    ':nohist_expirationdates:'.
                   2264:                             &escape($key).'='.$now,
1.620     albertel 2265:                             $env{'course.'.$cid.'.home'})
1.110     www      2266:     }
                   2267:     return 'ok';
1.14      www      2268: }
                   2269: 
1.109     www      2270: # ----------------------------------------------------- Devalidate Spreadsheets
                   2271: 
                   2272: sub devalidate {
1.325     www      2273:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2274:     my $cid=$env{'request.course.id'}; 
1.109     www      2275:     if ($cid) {
1.391     matthew  2276:         # delete the stored spreadsheets for
                   2277:         # - the student level sheet of this user in course's homespace
                   2278:         # - the assessment level sheet for this resource 
                   2279:         #   for this user in user's homespace
1.553     albertel 2280: 	# - current conditional state info
1.325     www      2281: 	my $key=$uname.':'.$udom.':';
1.109     www      2282:         my $status=
1.299     matthew  2283: 	    &del('nohist_calculatedsheets',
1.391     matthew  2284: 		 [$key.'studentcalc:'],
1.620     albertel 2285: 		 $env{'course.'.$cid.'.domain'},
                   2286: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2287: 		.' '.
                   2288: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2289: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2290:         unless ($status eq 'ok ok') {
                   2291:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2292:                     $uname.' at '.$udom.' for '.
1.109     www      2293: 		    $symb.': '.$status);
1.133     albertel 2294:         }
1.553     albertel 2295: 	&delenv('user.state.'.$cid);
1.109     www      2296:     }
                   2297: }
                   2298: 
1.265     albertel 2299: sub get_scalar {
                   2300:     my ($string,$end) = @_;
                   2301:     my $value;
                   2302:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2303: 	$value = $1;
                   2304:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2305: 	$value = $1;
                   2306:     }
                   2307:     return &unescape($value);
                   2308: }
                   2309: 
                   2310: sub array2str {
                   2311:   my (@array) = @_;
                   2312:   my $result=&arrayref2str(\@array);
                   2313:   $result=~s/^__ARRAY_REF__//;
                   2314:   $result=~s/__END_ARRAY_REF__$//;
                   2315:   return $result;
                   2316: }
                   2317: 
1.204     albertel 2318: sub arrayref2str {
                   2319:   my ($arrayref) = @_;
1.265     albertel 2320:   my $result='__ARRAY_REF__';
1.204     albertel 2321:   foreach my $elem (@$arrayref) {
1.265     albertel 2322:     if(ref($elem) eq 'ARRAY') {
                   2323:       $result.=&arrayref2str($elem).'&';
                   2324:     } elsif(ref($elem) eq 'HASH') {
                   2325:       $result.=&hashref2str($elem).'&';
                   2326:     } elsif(ref($elem)) {
                   2327:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2328:     } else {
                   2329:       $result.=&escape($elem).'&';
                   2330:     }
                   2331:   }
                   2332:   $result=~s/\&$//;
1.265     albertel 2333:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2334:   return $result;
                   2335: }
                   2336: 
1.168     albertel 2337: sub hash2str {
1.204     albertel 2338:   my (%hash) = @_;
                   2339:   my $result=&hashref2str(\%hash);
1.265     albertel 2340:   $result=~s/^__HASH_REF__//;
                   2341:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2342:   return $result;
                   2343: }
                   2344: 
                   2345: sub hashref2str {
                   2346:   my ($hashref)=@_;
1.265     albertel 2347:   my $result='__HASH_REF__';
1.800     albertel 2348:   foreach my $key (sort(keys(%$hashref))) {
                   2349:     if (ref($key) eq 'ARRAY') {
                   2350:       $result.=&arrayref2str($key).'=';
                   2351:     } elsif (ref($key) eq 'HASH') {
                   2352:       $result.=&hashref2str($key).'=';
                   2353:     } elsif (ref($key)) {
1.265     albertel 2354:       $result.='=';
1.800     albertel 2355:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2356:     } else {
1.800     albertel 2357: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2358:     }
                   2359: 
1.800     albertel 2360:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2361:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2362:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2363:       $result.=&hashref2str($hashref->{$key}).'&';
                   2364:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2365:        $result.='&';
1.800     albertel 2366:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2367:     } else {
1.800     albertel 2368:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2369:     }
                   2370:   }
1.168     albertel 2371:   $result=~s/\&$//;
1.265     albertel 2372:   $result .= '__END_HASH_REF__';
1.168     albertel 2373:   return $result;
                   2374: }
                   2375: 
                   2376: sub str2hash {
1.265     albertel 2377:     my ($string)=@_;
                   2378:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2379:     return %$hash;
                   2380: }
                   2381: 
                   2382: sub str2hashref {
1.168     albertel 2383:   my ($string) = @_;
1.265     albertel 2384: 
                   2385:   my %hash;
                   2386: 
                   2387:   if($string !~ /^__HASH_REF__/) {
                   2388:       if (! ($string eq '' || !defined($string))) {
                   2389: 	  $hash{'error'}='Not hash reference';
                   2390:       }
                   2391:       return (\%hash, $string);
                   2392:   }
                   2393: 
                   2394:   $string =~ s/^__HASH_REF__//;
                   2395: 
                   2396:   while($string !~ /^__END_HASH_REF__/) {
                   2397:       #key
                   2398:       my $key='';
                   2399:       if($string =~ /^__HASH_REF__/) {
                   2400:           ($key, $string)=&str2hashref($string);
                   2401:           if(defined($key->{'error'})) {
                   2402:               $hash{'error'}='Bad data';
                   2403:               return (\%hash, $string);
                   2404:           }
                   2405:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2406:           ($key, $string)=&str2arrayref($string);
                   2407:           if($key->[0] eq 'Array reference error') {
                   2408:               $hash{'error'}='Bad data';
                   2409:               return (\%hash, $string);
                   2410:           }
                   2411:       } else {
                   2412:           $string =~ s/^(.*?)=//;
1.267     albertel 2413: 	  $key=&unescape($1);
1.265     albertel 2414:       }
                   2415:       $string =~ s/^=//;
                   2416: 
                   2417:       #value
                   2418:       my $value='';
                   2419:       if($string =~ /^__HASH_REF__/) {
                   2420:           ($value, $string)=&str2hashref($string);
                   2421:           if(defined($value->{'error'})) {
                   2422:               $hash{'error'}='Bad data';
                   2423:               return (\%hash, $string);
                   2424:           }
                   2425:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2426:           ($value, $string)=&str2arrayref($string);
                   2427:           if($value->[0] eq 'Array reference error') {
                   2428:               $hash{'error'}='Bad data';
                   2429:               return (\%hash, $string);
                   2430:           }
                   2431:       } else {
                   2432: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2433:       }
                   2434:       $string =~ s/^&//;
                   2435: 
                   2436:       $hash{$key}=$value;
1.204     albertel 2437:   }
1.265     albertel 2438: 
                   2439:   $string =~ s/^__END_HASH_REF__//;
                   2440: 
                   2441:   return (\%hash, $string);
1.204     albertel 2442: }
                   2443: 
                   2444: sub str2array {
1.265     albertel 2445:     my ($string)=@_;
                   2446:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2447:     return @$array;
                   2448: }
                   2449: 
                   2450: sub str2arrayref {
1.204     albertel 2451:   my ($string) = @_;
1.265     albertel 2452:   my @array;
                   2453: 
                   2454:   if($string !~ /^__ARRAY_REF__/) {
                   2455:       if (! ($string eq '' || !defined($string))) {
                   2456: 	  $array[0]='Array reference error';
                   2457:       }
                   2458:       return (\@array, $string);
                   2459:   }
                   2460: 
                   2461:   $string =~ s/^__ARRAY_REF__//;
                   2462: 
                   2463:   while($string !~ /^__END_ARRAY_REF__/) {
                   2464:       my $value='';
                   2465:       if($string =~ /^__HASH_REF__/) {
                   2466:           ($value, $string)=&str2hashref($string);
                   2467:           if(defined($value->{'error'})) {
                   2468:               $array[0] ='Array reference error';
                   2469:               return (\@array, $string);
                   2470:           }
                   2471:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2472:           ($value, $string)=&str2arrayref($string);
                   2473:           if($value->[0] eq 'Array reference error') {
                   2474:               $array[0] ='Array reference error';
                   2475:               return (\@array, $string);
                   2476:           }
                   2477:       } else {
                   2478: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2479:       }
                   2480:       $string =~ s/^&//;
                   2481: 
                   2482:       push(@array, $value);
1.191     harris41 2483:   }
1.265     albertel 2484: 
                   2485:   $string =~ s/^__END_ARRAY_REF__//;
                   2486: 
                   2487:   return (\@array, $string);
1.168     albertel 2488: }
                   2489: 
1.167     albertel 2490: # -------------------------------------------------------------------Temp Store
                   2491: 
1.168     albertel 2492: sub tmpreset {
                   2493:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2494:   if (!$symb) {
                   2495:     $symb=&symbread();
1.620     albertel 2496:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2497:   }
                   2498:   $symb=escape($symb);
                   2499: 
1.620     albertel 2500:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2501:   $namespace=~s/\//\_/g;
                   2502:   $namespace=~s/\W//g;
                   2503: 
1.620     albertel 2504:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2505:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2506:   if ($domain eq 'public' && $stuname eq 'public') {
                   2507:       $stuname=$ENV{'REMOTE_ADDR'};
                   2508:   }
1.168     albertel 2509:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2510:   my %hash;
                   2511:   if (tie(%hash,'GDBM_File',
                   2512: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2513: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2514:     foreach my $key (keys %hash) {
1.180     albertel 2515:       if ($key=~ /:$symb/) {
1.168     albertel 2516: 	delete($hash{$key});
                   2517:       }
                   2518:     }
                   2519:   }
                   2520: }
                   2521: 
1.167     albertel 2522: sub tmpstore {
1.168     albertel 2523:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2524: 
                   2525:   if (!$symb) {
                   2526:     $symb=&symbread();
1.620     albertel 2527:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2528:   }
                   2529:   $symb=escape($symb);
                   2530: 
                   2531:   if (!$namespace) {
                   2532:     # I don't think we would ever want to store this for a course.
                   2533:     # it seems this will only be used if we don't have a course.
1.620     albertel 2534:     #$namespace=$env{'request.course.id'};
1.168     albertel 2535:     #if (!$namespace) {
1.620     albertel 2536:       $namespace=$env{'request.state'};
1.168     albertel 2537:     #}
                   2538:   }
                   2539:   $namespace=~s/\//\_/g;
                   2540:   $namespace=~s/\W//g;
1.620     albertel 2541:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2542:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2543:   if ($domain eq 'public' && $stuname eq 'public') {
                   2544:       $stuname=$ENV{'REMOTE_ADDR'};
                   2545:   }
1.168     albertel 2546:   my $now=time;
                   2547:   my %hash;
                   2548:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2549:   if (tie(%hash,'GDBM_File',
                   2550: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2551: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2552:     $hash{"version:$symb"}++;
                   2553:     my $version=$hash{"version:$symb"};
                   2554:     my $allkeys=''; 
                   2555:     foreach my $key (keys(%$storehash)) {
                   2556:       $allkeys.=$key.':';
1.591     albertel 2557:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2558:     }
                   2559:     $hash{"$version:$symb:timestamp"}=$now;
                   2560:     $allkeys.='timestamp';
                   2561:     $hash{"$version:keys:$symb"}=$allkeys;
                   2562:     if (untie(%hash)) {
                   2563:       return 'ok';
                   2564:     } else {
                   2565:       return "error:$!";
                   2566:     }
                   2567:   } else {
                   2568:     return "error:$!";
                   2569:   }
                   2570: }
1.167     albertel 2571: 
1.168     albertel 2572: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2573: 
1.168     albertel 2574: sub tmprestore {
                   2575:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2576: 
1.168     albertel 2577:   if (!$symb) {
                   2578:     $symb=&symbread();
1.620     albertel 2579:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2580:   }
                   2581:   $symb=escape($symb);
                   2582: 
1.620     albertel 2583:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2584: 
1.620     albertel 2585:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2586:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2587:   if ($domain eq 'public' && $stuname eq 'public') {
                   2588:       $stuname=$ENV{'REMOTE_ADDR'};
                   2589:   }
1.168     albertel 2590:   my %returnhash;
                   2591:   $namespace=~s/\//\_/g;
                   2592:   $namespace=~s/\W//g;
                   2593:   my %hash;
                   2594:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2595:   if (tie(%hash,'GDBM_File',
                   2596: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2597: 	  &GDBM_READER(),0640)) {
1.168     albertel 2598:     my $version=$hash{"version:$symb"};
                   2599:     $returnhash{'version'}=$version;
                   2600:     my $scope;
                   2601:     for ($scope=1;$scope<=$version;$scope++) {
                   2602:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2603:       my @keys=split(/:/,$vkeys);
                   2604:       my $key;
                   2605:       $returnhash{"$scope:keys"}=$vkeys;
                   2606:       foreach $key (@keys) {
1.591     albertel 2607: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2608: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2609:       }
                   2610:     }
1.168     albertel 2611:     if (!(untie(%hash))) {
                   2612:       return "error:$!";
                   2613:     }
                   2614:   } else {
                   2615:     return "error:$!";
                   2616:   }
                   2617:   return %returnhash;
1.167     albertel 2618: }
                   2619: 
1.9       www      2620: # ----------------------------------------------------------------------- Store
                   2621: 
                   2622: sub store {
1.124     www      2623:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2624:     my $home='';
                   2625: 
1.168     albertel 2626:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2627: 
1.213     www      2628:     $symb=&symbclean($symb);
1.122     albertel 2629:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2630: 
1.620     albertel 2631:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2632:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2633: 
                   2634:     &devalidate($symb,$stuname,$domain);
1.109     www      2635: 
                   2636:     $symb=escape($symb);
1.187     www      2637:     if (!$namespace) { 
1.620     albertel 2638:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2639:           return ''; 
                   2640:        } 
                   2641:     }
1.620     albertel 2642:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2643: 
                   2644:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2645:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2646: 
1.12      www      2647:     my $namevalue='';
1.800     albertel 2648:     foreach my $key (keys(%$storehash)) {
                   2649:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2650:     }
1.12      www      2651:     $namevalue=~s/\&$//;
1.187     www      2652:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2653:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2654: }
                   2655: 
1.47      www      2656: # -------------------------------------------------------------- Critical Store
                   2657: 
                   2658: sub cstore {
1.124     www      2659:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2660:     my $home='';
                   2661: 
1.168     albertel 2662:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2663: 
1.213     www      2664:     $symb=&symbclean($symb);
1.122     albertel 2665:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2666: 
1.620     albertel 2667:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2668:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2669: 
                   2670:     &devalidate($symb,$stuname,$domain);
1.109     www      2671: 
                   2672:     $symb=escape($symb);
1.187     www      2673:     if (!$namespace) { 
1.620     albertel 2674:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2675:           return ''; 
                   2676:        } 
                   2677:     }
1.620     albertel 2678:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2679: 
                   2680:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2681:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2682: 
1.47      www      2683:     my $namevalue='';
1.800     albertel 2684:     foreach my $key (keys(%$storehash)) {
                   2685:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2686:     }
1.47      www      2687:     $namevalue=~s/\&$//;
1.187     www      2688:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2689:     return critical
                   2690:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2691: }
                   2692: 
1.9       www      2693: # --------------------------------------------------------------------- Restore
                   2694: 
                   2695: sub restore {
1.124     www      2696:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2697:     my $home='';
                   2698: 
1.168     albertel 2699:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2700: 
1.122     albertel 2701:     if (!$symb) {
                   2702:       unless ($symb=escape(&symbread())) { return ''; }
                   2703:     } else {
1.213     www      2704:       $symb=&escape(&symbclean($symb));
1.122     albertel 2705:     }
1.188     www      2706:     if (!$namespace) { 
1.620     albertel 2707:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2708:           return ''; 
                   2709:        } 
                   2710:     }
1.620     albertel 2711:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2712:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2713:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2714:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2715: 
1.12      www      2716:     my %returnhash=();
1.800     albertel 2717:     foreach my $line (split(/\&/,$answer)) {
                   2718: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2719:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2720:     }
1.75      www      2721:     my $version;
                   2722:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2723:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2724:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2725:        }
1.75      www      2726:     }
1.13      www      2727:     return %returnhash;
1.34      www      2728: }
                   2729: 
                   2730: # ---------------------------------------------------------- Course Description
                   2731: 
                   2732: sub coursedescription {
1.731     albertel 2733:     my ($courseid,$args)=@_;
1.34      www      2734:     $courseid=~s/^\///;
1.49      www      2735:     $courseid=~s/\_/\//g;
1.34      www      2736:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2737:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2738:     my $normalid=$cdomain.'_'.$cnum;
                   2739:     # need to always cache even if we get errors otherwise we keep 
                   2740:     # trying and trying and trying to get the course description.
                   2741:     my %envhash=();
                   2742:     my %returnhash=();
1.731     albertel 2743:     
                   2744:     my $expiretime=600;
                   2745:     if ($env{'request.course.id'} eq $normalid) {
                   2746: 	$expiretime=120;
                   2747:     }
                   2748: 
                   2749:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2750:     if (!$args->{'freshen_cache'}
                   2751: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2752: 	foreach my $key (keys(%env)) {
                   2753: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2754: 	    my ($setting) = $1;
                   2755: 	    $returnhash{$setting} = $env{$key};
                   2756: 	}
                   2757: 	return %returnhash;
                   2758:     }
                   2759: 
                   2760:     # get the data agin
                   2761:     if (!$args->{'one_time'}) {
                   2762: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2763:     }
1.811     albertel 2764: 
1.34      www      2765:     if ($chome ne 'no_host') {
1.302     albertel 2766:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2767:        if (!exists($returnhash{'con_lost'})) {
                   2768:            $returnhash{'home'}= $chome;
                   2769: 	   $returnhash{'domain'} = $cdomain;
                   2770: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2771:            if (!defined($returnhash{'type'})) {
                   2772:                $returnhash{'type'} = 'Course';
                   2773:            }
1.130     albertel 2774:            while (my ($name,$value) = each %returnhash) {
1.53      www      2775:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2776:            }
1.270     www      2777:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2778:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2779: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2780:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2781:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2782:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2783:        }
                   2784:     }
1.731     albertel 2785:     if (!$args->{'one_time'}) {
                   2786: 	&appenv(%envhash);
                   2787:     }
1.302     albertel 2788:     return %returnhash;
1.461     www      2789: }
                   2790: 
                   2791: # -------------------------------------------------See if a user is privileged
                   2792: 
                   2793: sub privileged {
                   2794:     my ($username,$domain)=@_;
                   2795:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2796: 			&homeserver($username,$domain));
                   2797:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2798:     my $now=time;
                   2799:     if ($rolesdump ne '') {
1.800     albertel 2800:         foreach my $entry (split(/&/,$rolesdump)) {
                   2801: 	    if ($entry!~/^rolesdef_/) {
                   2802: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2803: 		$area=~s/\_\w\w$//;
                   2804: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2805: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2806: 		    my $active=1;
                   2807: 		    if ($tend) {
                   2808: 			if ($tend<$now) { $active=0; }
                   2809: 		    }
                   2810: 		    if ($tstart) {
                   2811: 			if ($tstart>$now) { $active=0; }
                   2812: 		    }
                   2813: 		    if ($active) { return 1; }
                   2814: 		}
                   2815: 	    }
                   2816: 	}
                   2817:     }
                   2818:     return 0;
1.9       www      2819: }
1.1       albertel 2820: 
1.103     harris41 2821: # -------------------------------------------------------- Get user privileges
1.11      www      2822: 
                   2823: sub rolesinit {
                   2824:     my ($domain,$username,$authhost)=@_;
                   2825:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2826:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2827:     my %allroles=();
1.678     raeburn  2828:     my %allgroups=();   
1.11      www      2829:     my $now=time;
1.743     albertel 2830:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2831:     my $group_privs;
1.11      www      2832: 
                   2833:     if ($rolesdump ne '') {
1.800     albertel 2834:         foreach my $entry (split(/&/,$rolesdump)) {
                   2835: 	  if ($entry!~/^rolesdef_/) {
                   2836:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2837: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2838:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2839: 	    if ($role=~/^cr/) { 
1.807     albertel 2840: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2841: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2842: 		    ($tend,$tstart)=split('_',$trest);
                   2843: 		} else {
                   2844: 		    $trole=$role;
                   2845: 		}
1.678     raeburn  2846:             } elsif ($role =~ m|^gr/|) {
                   2847:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2848:                 ($trole,$group_privs) = split(/\//,$trole);
                   2849:                 $group_privs = &unescape($group_privs);
1.587     albertel 2850: 	    } else {
                   2851: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2852: 	    }
1.743     albertel 2853: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2854: 					 $username);
                   2855: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2856:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2857:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2858:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2859: 		my $spec=$trole.'.'.$area;
                   2860: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2861: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2862:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2863:                 } elsif ($trole eq 'gr') {
                   2864:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2865: 		} else {
1.567     raeburn  2866:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2867: 		}
1.12      www      2868:             }
1.662     raeburn  2869:           }
1.191     harris41 2870:         }
1.743     albertel 2871:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2872:         $userroles{'user.adv'}    = $adv;
                   2873: 	$userroles{'user.author'} = $author;
1.620     albertel 2874:         $env{'user.adv'}=$adv;
1.11      www      2875:     }
1.743     albertel 2876:     return \%userroles;  
1.11      www      2877: }
                   2878: 
1.567     raeburn  2879: sub set_arearole {
                   2880:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2881: # log the associated role with the area
                   2882:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2883:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2884: }
                   2885: 
                   2886: sub custom_roleprivs {
                   2887:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2888:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2889:     my $homsvr=homeserver($rauthor,$rdomain);
                   2890:     if ($hostname{$homsvr} ne '') {
                   2891:         my ($rdummy,$roledef)=
                   2892:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2893:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2894:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2895:             if (defined($syspriv)) {
                   2896:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2897:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2898:             }
                   2899:             if ($tdomain ne '') {
                   2900:                 if (defined($dompriv)) {
                   2901:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2902:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2903:                 }
                   2904:                 if (($trest ne '') && (defined($coursepriv))) {
                   2905:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2906:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2907:                 }
                   2908:             }
                   2909:         }
                   2910:     }
                   2911: }
                   2912: 
1.678     raeburn  2913: sub group_roleprivs {
                   2914:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2915:     my $access = 1;
                   2916:     my $now = time;
                   2917:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2918:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2919:     if ($access) {
1.811     albertel 2920:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2921:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2922:     }
                   2923: }
1.567     raeburn  2924: 
                   2925: sub standard_roleprivs {
                   2926:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2927:     if (defined($pr{$trole.':s'})) {
                   2928:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2929:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2930:     }
                   2931:     if ($tdomain ne '') {
                   2932:         if (defined($pr{$trole.':d'})) {
                   2933:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2934:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2935:         }
                   2936:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2937:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2938:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2939:         }
                   2940:     }
                   2941: }
                   2942: 
                   2943: sub set_userprivs {
1.678     raeburn  2944:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2945:     my $author=0;
                   2946:     my $adv=0;
1.678     raeburn  2947:     my %grouproles = ();
                   2948:     if (keys(%{$allgroups}) > 0) {
                   2949:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2950:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2951:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2952:                 $trole = $1;
                   2953:                 $area = $2;
1.681     raeburn  2954:                 $sec = $3;
                   2955:                 $extendedarea = $area.$sec;
                   2956:                 if (exists($$allgroups{$area})) {
                   2957:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2958:                         my $spec = $trole.'.'.$extendedarea;
                   2959:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2960:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2961:                     }
                   2962:                 }
                   2963:             }
                   2964:         }
                   2965:     }
1.800     albertel 2966:     foreach my $group (keys(%grouproles)) {
                   2967:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2968:     }
1.800     albertel 2969:     foreach my $role (keys(%{$allroles})) {
                   2970:         my %thesepriv;
                   2971:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   2972:         foreach my $item (split(/:/,$$allroles{$role})) {
                   2973:             if ($item ne '') {
                   2974:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  2975:                 if ($restrictions eq '') {
                   2976:                     $thesepriv{$privilege}='F';
                   2977:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2978:                     $thesepriv{$privilege}.=$restrictions;
                   2979:                 }
                   2980:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2981:             }
                   2982:         }
                   2983:         my $thesestr='';
1.800     albertel 2984:         foreach my $priv (keys(%thesepriv)) {
                   2985: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   2986: 	}
                   2987:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  2988:     }
                   2989:     return ($author,$adv);
                   2990: }
                   2991: 
1.12      www      2992: # --------------------------------------------------------------- get interface
                   2993: 
                   2994: sub get {
1.131     albertel 2995:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2996:    my $items='';
1.800     albertel 2997:    foreach my $item (@$storearr) {
                   2998:        $items.=&escape($item).'&';
1.191     harris41 2999:    }
1.12      www      3000:    $items=~s/\&$//;
1.620     albertel 3001:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3002:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3003:    my $uhome=&homeserver($uname,$udomain);
                   3004: 
1.133     albertel 3005:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3006:    my @pairs=split(/\&/,$rep);
1.273     albertel 3007:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3008:      return @pairs;
                   3009:    }
1.15      www      3010:    my %returnhash=();
1.42      www      3011:    my $i=0;
1.800     albertel 3012:    foreach my $item (@$storearr) {
                   3013:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3014:       $i++;
1.191     harris41 3015:    }
1.15      www      3016:    return %returnhash;
1.27      www      3017: }
                   3018: 
                   3019: # --------------------------------------------------------------- del interface
                   3020: 
                   3021: sub del {
1.133     albertel 3022:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3023:    my $items='';
1.800     albertel 3024:    foreach my $item (@$storearr) {
                   3025:        $items.=&escape($item).'&';
1.191     harris41 3026:    }
1.27      www      3027:    $items=~s/\&$//;
1.620     albertel 3028:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3029:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3030:    my $uhome=&homeserver($uname,$udomain);
                   3031: 
                   3032:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3033: }
                   3034: 
                   3035: # -------------------------------------------------------------- dump interface
                   3036: 
                   3037: sub dump {
1.755     albertel 3038:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3039:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3040:     if (!$uname) { $uname=$env{'user.name'}; }
                   3041:     my $uhome=&homeserver($uname,$udomain);
                   3042:     if ($regexp) {
                   3043: 	$regexp=&escape($regexp);
                   3044:     } else {
                   3045: 	$regexp='.';
                   3046:     }
                   3047:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3048:     my @pairs=split(/\&/,$rep);
                   3049:     my %returnhash=();
                   3050:     foreach my $item (@pairs) {
                   3051: 	my ($key,$value)=split(/=/,$item,2);
                   3052: 	$key = &unescape($key);
                   3053: 	next if ($key =~ /^error: 2 /);
                   3054: 	$returnhash{$key}=&thaw_unescape($value);
                   3055:     }
                   3056:     return %returnhash;
1.407     www      3057: }
                   3058: 
1.717     albertel 3059: # --------------------------------------------------------- dumpstore interface
                   3060: 
                   3061: sub dumpstore {
                   3062:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3063:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3064:    if (!$uname) { $uname=$env{'user.name'}; }
                   3065:    my $uhome=&homeserver($uname,$udomain);
                   3066:    if ($regexp) {
                   3067:        $regexp=&escape($regexp);
                   3068:    } else {
                   3069:        $regexp='.';
                   3070:    }
                   3071:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3072:    my @pairs=split(/\&/,$rep);
                   3073:    my %returnhash=();
                   3074:    foreach my $item (@pairs) {
                   3075:        my ($key,$value)=split(/=/,$item,2);
                   3076:        next if ($key =~ /^error: 2 /);
                   3077:        $returnhash{$key}=&thaw_unescape($value);
                   3078:    }
                   3079:    return %returnhash;
1.717     albertel 3080: }
                   3081: 
1.407     www      3082: # -------------------------------------------------------------- keys interface
                   3083: 
                   3084: sub getkeys {
                   3085:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3086:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3087:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3088:    my $uhome=&homeserver($uname,$udomain);
                   3089:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3090:    my @keyarray=();
1.800     albertel 3091:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3092:       next if ($key =~ /^error: 2 /);
1.800     albertel 3093:       push(@keyarray,&unescape($key));
1.407     www      3094:    }
                   3095:    return @keyarray;
1.318     matthew  3096: }
                   3097: 
1.319     matthew  3098: # --------------------------------------------------------------- currentdump
                   3099: sub currentdump {
1.328     matthew  3100:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3101:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3102:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3103:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3104:    my $uhome = &homeserver($sname,$sdom);
                   3105:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3106:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3107:    #
1.318     matthew  3108:    my %returnhash=();
1.319     matthew  3109:    #
                   3110:    if ($rep eq "unknown_cmd") { 
                   3111:        # an old lond will not know currentdump
                   3112:        # Do a dump and make it look like a currentdump
1.822     albertel 3113:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3114:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3115:        my %hash = @tmp;
                   3116:        @tmp=();
1.424     matthew  3117:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3118:    } else {
                   3119:        my @pairs=split(/\&/,$rep);
1.800     albertel 3120:        foreach my $pair (@pairs) {
                   3121:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3122:            my ($symb,$param) = split(/:/,$key);
                   3123:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3124:                                                         &thaw_unescape($value);
1.319     matthew  3125:        }
1.191     harris41 3126:    }
1.12      www      3127:    return %returnhash;
1.424     matthew  3128: }
                   3129: 
                   3130: sub convert_dump_to_currentdump{
                   3131:     my %hash = %{shift()};
                   3132:     my %returnhash;
                   3133:     # Code ripped from lond, essentially.  The only difference
                   3134:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3135:     # we might run in to problems with parameter names =~ /^v\./
                   3136:     while (my ($key,$value) = each(%hash)) {
                   3137:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3138: 	$symb  = &unescape($symb);
                   3139: 	$param = &unescape($param);
1.424     matthew  3140:         next if ($v eq 'version' || $symb eq 'keys');
                   3141:         next if (exists($returnhash{$symb}) &&
                   3142:                  exists($returnhash{$symb}->{$param}) &&
                   3143:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3144:         $returnhash{$symb}->{$param}=$value;
                   3145:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3146:     }
                   3147:     #
                   3148:     # Remove all of the keys in the hashes which keep track of
                   3149:     # the version of the parameter.
                   3150:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3151:         # use a foreach because we are going to delete from the hash.
                   3152:         foreach my $key (keys(%$param_hash)) {
                   3153:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3154:         }
                   3155:     }
                   3156:     return \%returnhash;
1.12      www      3157: }
                   3158: 
1.627     albertel 3159: # ------------------------------------------------------ critical inc interface
                   3160: 
                   3161: sub cinc {
                   3162:     return &inc(@_,'critical');
                   3163: }
                   3164: 
1.449     matthew  3165: # --------------------------------------------------------------- inc interface
                   3166: 
                   3167: sub inc {
1.627     albertel 3168:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3169:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3170:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3171:     my $uhome=&homeserver($uname,$udomain);
                   3172:     my $items='';
                   3173:     if (! ref($store)) {
                   3174:         # got a single value, so use that instead
                   3175:         $items = &escape($store).'=&';
                   3176:     } elsif (ref($store) eq 'SCALAR') {
                   3177:         $items = &escape($$store).'=&';        
                   3178:     } elsif (ref($store) eq 'ARRAY') {
                   3179:         $items = join('=&',map {&escape($_);} @{$store});
                   3180:     } elsif (ref($store) eq 'HASH') {
                   3181:         while (my($key,$value) = each(%{$store})) {
                   3182:             $items.= &escape($key).'='.&escape($value).'&';
                   3183:         }
                   3184:     }
                   3185:     $items=~s/\&$//;
1.627     albertel 3186:     if ($critical) {
                   3187: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3188:     } else {
                   3189: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3190:     }
1.449     matthew  3191: }
                   3192: 
1.12      www      3193: # --------------------------------------------------------------- put interface
                   3194: 
                   3195: sub put {
1.134     albertel 3196:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3197:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3198:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3199:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3200:    my $items='';
1.800     albertel 3201:    foreach my $item (keys(%$storehash)) {
                   3202:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3203:    }
1.12      www      3204:    $items=~s/\&$//;
1.134     albertel 3205:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3206: }
                   3207: 
1.631     albertel 3208: # ------------------------------------------------------------ newput interface
                   3209: 
                   3210: sub newput {
                   3211:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3212:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3213:    if (!$uname) { $uname=$env{'user.name'}; }
                   3214:    my $uhome=&homeserver($uname,$udomain);
                   3215:    my $items='';
                   3216:    foreach my $key (keys(%$storehash)) {
                   3217:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3218:    }
                   3219:    $items=~s/\&$//;
                   3220:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3221: }
                   3222: 
                   3223: # ---------------------------------------------------------  putstore interface
                   3224: 
1.524     raeburn  3225: sub putstore {
1.715     albertel 3226:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3227:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3228:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3229:    my $uhome=&homeserver($uname,$udomain);
                   3230:    my $items='';
1.715     albertel 3231:    foreach my $key (keys(%$storehash)) {
                   3232:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3233:    }
1.715     albertel 3234:    $items=~s/\&$//;
1.716     albertel 3235:    my $esc_symb=&escape($symb);
                   3236:    my $esc_v=&escape($version);
1.715     albertel 3237:    my $reply =
1.716     albertel 3238:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3239: 	      $uhome);
                   3240:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3241:        # gfall back to way things use to be done
1.715     albertel 3242:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3243: 			    $uname);
1.524     raeburn  3244:    }
1.715     albertel 3245:    return $reply;
                   3246: }
                   3247: 
                   3248: sub old_putstore {
1.716     albertel 3249:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3250:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3251:     if (!$uname) { $uname=$env{'user.name'}; }
                   3252:     my $uhome=&homeserver($uname,$udomain);
                   3253:     my %newstorehash;
1.800     albertel 3254:     foreach my $item (keys(%$storehash)) {
                   3255: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3256: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3257:     }
                   3258:     my $items='';
                   3259:     my %allitems = ();
1.800     albertel 3260:     foreach my $item (keys(%newstorehash)) {
                   3261: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3262: 	    my $key = $1.':keys:'.$2;
                   3263: 	    $allitems{$key} .= $3.':';
                   3264: 	}
1.800     albertel 3265: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3266:     }
1.800     albertel 3267:     foreach my $item (keys(%allitems)) {
                   3268: 	$allitems{$item} =~ s/\:$//;
                   3269: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3270:     }
                   3271:     $items=~s/\&$//;
                   3272:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3273: }
                   3274: 
1.47      www      3275: # ------------------------------------------------------ critical put interface
                   3276: 
                   3277: sub cput {
1.134     albertel 3278:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3279:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3280:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3281:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3282:    my $items='';
1.800     albertel 3283:    foreach my $item (keys(%$storehash)) {
                   3284:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3285:    }
1.47      www      3286:    $items=~s/\&$//;
1.134     albertel 3287:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3288: }
                   3289: 
                   3290: # -------------------------------------------------------------- eget interface
                   3291: 
                   3292: sub eget {
1.133     albertel 3293:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3294:    my $items='';
1.800     albertel 3295:    foreach my $item (@$storearr) {
                   3296:        $items.=&escape($item).'&';
1.191     harris41 3297:    }
1.12      www      3298:    $items=~s/\&$//;
1.620     albertel 3299:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3300:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3301:    my $uhome=&homeserver($uname,$udomain);
                   3302:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3303:    my @pairs=split(/\&/,$rep);
                   3304:    my %returnhash=();
1.42      www      3305:    my $i=0;
1.800     albertel 3306:    foreach my $item (@$storearr) {
                   3307:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3308:       $i++;
1.191     harris41 3309:    }
1.12      www      3310:    return %returnhash;
                   3311: }
                   3312: 
1.667     albertel 3313: # ------------------------------------------------------------ tmpput interface
                   3314: sub tmpput {
1.802     raeburn  3315:     my ($storehash,$server,$context)=@_;
1.667     albertel 3316:     my $items='';
1.800     albertel 3317:     foreach my $item (keys(%$storehash)) {
                   3318: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3319:     }
                   3320:     $items=~s/\&$//;
1.802     raeburn  3321:     if (defined($context)) {
                   3322:         $items .= ':'.&escape($context);
                   3323:     }
1.667     albertel 3324:     return &reply("tmpput:$items",$server);
                   3325: }
                   3326: 
                   3327: # ------------------------------------------------------------ tmpget interface
                   3328: sub tmpget {
1.688     albertel 3329:     my ($token,$server)=@_;
                   3330:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3331:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3332:     my %returnhash;
                   3333:     foreach my $item (split(/\&/,$rep)) {
                   3334: 	my ($key,$value)=split(/=/,$item);
                   3335: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3336:     }
                   3337:     return %returnhash;
                   3338: }
                   3339: 
1.688     albertel 3340: # ------------------------------------------------------------ tmpget interface
                   3341: sub tmpdel {
                   3342:     my ($token,$server)=@_;
                   3343:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3344:     return &reply("tmpdel:$token",$server);
                   3345: }
                   3346: 
1.765     albertel 3347: # -------------------------------------------------- portfolio access checking
                   3348: 
                   3349: sub portfolio_access {
1.766     albertel 3350:     my ($requrl) = @_;
1.765     albertel 3351:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3352:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3353:     if ($result) {
                   3354:         my %setters;
                   3355:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3356:             my ($startblock,$endblock) =
                   3357:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3358:             if ($startblock && $endblock) {
                   3359:                 return 'B';
                   3360:             }
                   3361:         } else {
                   3362:             my ($startblock,$endblock) =
                   3363:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3364:             if ($startblock && $endblock) {
                   3365:                 return 'B';
                   3366:             }
                   3367:         }
                   3368:     }
1.765     albertel 3369:     if ($result eq 'ok') {
1.766     albertel 3370:        return 'F';
1.765     albertel 3371:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3372:        return 'A';
1.765     albertel 3373:     }
1.766     albertel 3374:     return '';
1.765     albertel 3375: }
                   3376: 
                   3377: sub get_portfolio_access {
1.767     albertel 3378:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3379: 
                   3380:     if (!ref($access_hash)) {
                   3381: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3382: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3383: 						   $file_name);
                   3384: 	$access_hash = $access_controls{$file_name};
                   3385:     }
                   3386: 
1.765     albertel 3387:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3388:     my $now = time;
                   3389:     if (ref($access_hash) eq 'HASH') {
                   3390:         foreach my $key (keys(%{$access_hash})) {
                   3391:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3392:             if ($start > $now) {
                   3393:                 next;
                   3394:             }
                   3395:             if ($end && $end<$now) {
                   3396:                 next;
                   3397:             }
                   3398:             if ($scope eq 'public') {
                   3399:                 $public = $key;
                   3400:                 last;
                   3401:             } elsif ($scope eq 'guest') {
                   3402:                 $guest = $key;
                   3403:             } elsif ($scope eq 'domains') {
                   3404:                 push(@domains,$key);
                   3405:             } elsif ($scope eq 'users') {
                   3406:                 push(@users,$key);
                   3407:             } elsif ($scope eq 'course') {
                   3408:                 push(@courses,$key);
                   3409:             } elsif ($scope eq 'group') {
                   3410:                 push(@groups,$key);
                   3411:             }
                   3412:         }
                   3413:         if ($public) {
                   3414:             return 'ok';
                   3415:         }
                   3416:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3417:             if ($guest) {
                   3418:                 return $guest;
                   3419:             }
                   3420:         } else {
                   3421:             if (@domains > 0) {
                   3422:                 foreach my $domkey (@domains) {
                   3423:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3424:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3425:                             return 'ok';
                   3426:                         }
                   3427:                     }
                   3428:                 }
                   3429:             }
                   3430:             if (@users > 0) {
                   3431:                 foreach my $userkey (@users) {
                   3432:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3433:                         return 'ok';
                   3434:                     }
                   3435:                 }
                   3436:             }
                   3437:             my %roleshash;
                   3438:             my @courses_and_groups = @courses;
                   3439:             push(@courses_and_groups,@groups); 
                   3440:             if (@courses_and_groups > 0) {
                   3441:                 my (%allgroups,%allroles); 
                   3442:                 my ($start,$end,$role,$sec,$group);
                   3443:                 foreach my $envkey (%env) {
1.811     albertel 3444:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3445:                         my $cid = $2.'_'.$3; 
                   3446:                         if ($1 eq 'gr') {
                   3447:                             $group = $4;
                   3448:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3449:                         } else {
                   3450:                             if ($4 eq '') {
                   3451:                                 $sec = 'none';
                   3452:                             } else {
                   3453:                                 $sec = $4;
                   3454:                             }
                   3455:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3456:                         }
1.811     albertel 3457:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3458:                         my $cid = $2.'_'.$3;
                   3459:                         if ($4 eq '') {
                   3460:                             $sec = 'none';
                   3461:                         } else {
                   3462:                             $sec = $4;
                   3463:                         }
                   3464:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3465:                     }
                   3466:                 }
                   3467:                 if (keys(%allroles) == 0) {
                   3468:                     return;
                   3469:                 }
                   3470:                 foreach my $key (@courses_and_groups) {
                   3471:                     my %content = %{$$access_hash{$key}};
                   3472:                     my $cnum = $content{'number'};
                   3473:                     my $cdom = $content{'domain'};
                   3474:                     my $cid = $cdom.'_'.$cnum;
                   3475:                     if (!exists($allroles{$cid})) {
                   3476:                         next;
                   3477:                     }    
                   3478:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3479:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3480:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3481:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3482:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3483:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3484:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3485:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3486:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3487:                                         if (grep/^all$/,@sections) {
                   3488:                                             return 'ok';
                   3489:                                         } else {
                   3490:                                             if (grep/^$sec$/,@sections) {
                   3491:                                                 return 'ok';
                   3492:                                             }
                   3493:                                         }
                   3494:                                     }
                   3495:                                 }
                   3496:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3497:                                     if (grep/^none$/,@groups) {
                   3498:                                         return 'ok';
                   3499:                                     }
                   3500:                                 } else {
                   3501:                                     if (grep/^all$/,@groups) {
                   3502:                                         return 'ok';
                   3503:                                     } 
                   3504:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3505:                                         if (grep/^$group$/,@groups) {
                   3506:                                             return 'ok';
                   3507:                                         }
                   3508:                                     }
                   3509:                                 } 
                   3510:                             }
                   3511:                         }
                   3512:                     }
                   3513:                 }
                   3514:             }
                   3515:             if ($guest) {
                   3516:                 return $guest;
                   3517:             }
                   3518:         }
                   3519:     }
                   3520:     return;
                   3521: }
                   3522: 
                   3523: sub course_group_datechecker {
                   3524:     my ($dates,$now,$status) = @_;
                   3525:     my ($start,$end) = split(/\./,$dates);
                   3526:     if (!$start && !$end) {
                   3527:         return 'ok';
                   3528:     }
                   3529:     if (grep/^active$/,@{$status}) {
                   3530:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3531:             return 'ok';
                   3532:         }
                   3533:     }
                   3534:     if (grep/^previous$/,@{$status}) {
                   3535:         if ($end > $now ) {
                   3536:             return 'ok';
                   3537:         }
                   3538:     }
                   3539:     if (grep/^future$/,@{$status}) {
                   3540:         if ($start > $now) {
                   3541:             return 'ok';
                   3542:         }
                   3543:     }
                   3544:     return; 
                   3545: }
                   3546: 
                   3547: sub parse_portfolio_url {
                   3548:     my ($url) = @_;
                   3549: 
                   3550:     my ($type,$udom,$unum,$group,$file_name);
                   3551:     
1.823   ! albertel 3552:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3553: 	$type = 1;
                   3554:         $udom = $1;
                   3555:         $unum = $2;
                   3556:         $file_name = $3;
1.823   ! albertel 3557:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3558: 	$type = 2;
                   3559:         $udom = $1;
                   3560:         $unum = $2;
                   3561:         $group = $3;
                   3562:         $file_name = $3.'/'.$4;
                   3563:     }
                   3564:     if (wantarray) {
                   3565: 	return ($type,$udom,$unum,$file_name,$group);
                   3566:     }
                   3567:     return $type;
                   3568: }
                   3569: 
                   3570: sub is_portfolio_url {
                   3571:     my ($url) = @_;
                   3572:     return scalar(&parse_portfolio_url($url));
                   3573: }
                   3574: 
1.798     raeburn  3575: sub is_portfolio_file {
                   3576:     my ($file) = @_;
1.820     raeburn  3577:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3578:         return 1;
                   3579:     }
                   3580:     return;
                   3581: }
                   3582: 
                   3583: 
1.341     www      3584: # ---------------------------------------------- Custom access rule evaluation
                   3585: 
                   3586: sub customaccess {
                   3587:     my ($priv,$uri)=@_;
1.807     albertel 3588:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3589:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3590:     $udom = &LONCAPA::clean_domain($udom);
                   3591:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3592:     my $access=0;
1.800     albertel 3593:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3594: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3595:         if ($role) {
                   3596: 	   if ($role ne $urole) { next; }
                   3597:         }
1.800     albertel 3598:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3599:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3600:             if ($tdom) {
                   3601: 		if ($tdom ne $udom) { next; }
                   3602:             }
                   3603:             if ($tcrs) {
                   3604: 		if ($tcrs ne $ucrs) { next; }
                   3605:             }
                   3606:             if ($tsec) {
                   3607: 		if ($tsec ne $usec) { next; }
                   3608:             }
                   3609:             $access=($effect eq 'allow');
                   3610:             last;
1.342     www      3611:         }
1.402     bowersj2 3612: 	if ($realm eq '' && $role eq '') {
                   3613:             $access=($effect eq 'allow');
                   3614: 	}
1.341     www      3615:     }
                   3616:     return $access;
                   3617: }
                   3618: 
1.103     harris41 3619: # ------------------------------------------------- Check for a user privilege
1.12      www      3620: 
                   3621: sub allowed {
1.810     raeburn  3622:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3623:     my $ver_orguri=$uri;
1.439     www      3624:     $uri=&deversion($uri);
1.152     www      3625:     my $orguri=$uri;
1.52      www      3626:     $uri=&declutter($uri);
1.809     raeburn  3627: 
1.810     raeburn  3628:     if ($priv eq 'evb') {
                   3629: # Evade communication block restrictions for specified role in a course
                   3630:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3631:             return $1;
                   3632:         } else {
                   3633:             return;
                   3634:         }
                   3635:     }
                   3636: 
1.620     albertel 3637:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3638: # Free bre access to adm and meta resources
1.775     albertel 3639:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3640: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3641: 	&& ($priv eq 'bre')) {
1.14      www      3642: 	return 'F';
1.159     www      3643:     }
                   3644: 
1.545     banghart 3645: # Free bre access to user's own portfolio contents
1.714     raeburn  3646:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3647:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3648: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3649:         my %setters;
                   3650:         my ($startblock,$endblock) = 
                   3651:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3652:         if ($startblock && $endblock) {
                   3653:             return 'B';
                   3654:         } else {
                   3655:             return 'F';
                   3656:         }
1.545     banghart 3657:     }
                   3658: 
1.762     raeburn  3659: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3660:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3661:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3662:         if (exists($env{'request.course.id'})) {
                   3663:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3664:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3665:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3666:                 my $courseprivid=$env{'request.course.id'};
                   3667:                 $courseprivid=~s/\_/\//;
                   3668:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3669:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3670:                     return $1; 
1.762     raeburn  3671:                 } else {
                   3672:                     if ($env{'request.course.sec'}) {
                   3673:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3674:                     }
                   3675:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3676:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3677:                         return $2;
                   3678:                     }
1.714     raeburn  3679:                 }
                   3680:             }
                   3681:         }
                   3682:     }
                   3683: 
1.159     www      3684: # Free bre to public access
                   3685: 
                   3686:     if ($priv eq 'bre') {
1.238     www      3687:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3688: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3689:            return 'F'; 
                   3690:         }
1.238     www      3691:         if ($copyright eq 'priv') {
                   3692:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3693: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3694: 		return '';
                   3695:             }
                   3696:         }
                   3697:         if ($copyright eq 'domain') {
                   3698:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3699: 	    unless (($env{'user.domain'} eq $1) ||
                   3700:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3701: 		return '';
                   3702:             }
1.262     matthew  3703:         }
1.620     albertel 3704:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3705:             # Library role, so allow browsing of resources in this domain.
                   3706:             return 'F';
1.238     www      3707:         }
1.341     www      3708:         if ($copyright eq 'custom') {
                   3709: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3710:         }
1.14      www      3711:     }
1.264     matthew  3712:     # Domain coordinator is trying to create a course
1.620     albertel 3713:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3714:         # uri is the requested domain in this case.
                   3715:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3716:         # a role of dc for the domain in question.
1.620     albertel 3717:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3718:     }
1.29      www      3719: 
1.52      www      3720:     my $thisallowed='';
                   3721:     my $statecond=0;
                   3722:     my $courseprivid='';
                   3723: 
                   3724: # Course
                   3725: 
1.620     albertel 3726:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3727:        $thisallowed.=$1;
                   3728:     }
1.29      www      3729: 
1.52      www      3730: # Domain
                   3731: 
1.620     albertel 3732:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3733:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3734:        $thisallowed.=$1;
                   3735:     }
1.52      www      3736: 
                   3737: # Course: uri itself is a course
1.66      www      3738:     my $courseuri=$uri;
                   3739:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3740:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3741: 
1.620     albertel 3742:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3743:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3744:        $thisallowed.=$1;
                   3745:     }
1.29      www      3746: 
1.665     albertel 3747: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3748: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3749:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3750: 	$thisallowed='';
1.671     raeburn  3751:         my ($match)=&is_on_map($uri);
                   3752:         if ($match) {
                   3753:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3754:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3755:                 $thisallowed.=$1;
                   3756:             }
                   3757:         } else {
1.705     albertel 3758:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3759:             if ($refuri) {
                   3760:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3761:                     $thisallowed='F';
1.671     raeburn  3762:                 } else {
                   3763:                     $refuri=&declutter($refuri);
                   3764:                     my ($match) = &is_on_map($refuri);
                   3765:                     if ($match) {
                   3766:                         $thisallowed='F';
                   3767:                     }
1.669     raeburn  3768:                 }
1.671     raeburn  3769:             }
                   3770:         }
1.314     www      3771:     }
1.492     albertel 3772: 
1.766     albertel 3773:     if ($priv eq 'bre'
                   3774: 	&& $thisallowed ne 'F' 
                   3775: 	&& $thisallowed ne '2'
                   3776: 	&& &is_portfolio_url($uri)) {
                   3777: 	$thisallowed = &portfolio_access($uri);
                   3778:     }
                   3779:     
1.52      www      3780: # Full access at system, domain or course-wide level? Exit.
1.29      www      3781: 
                   3782:     if ($thisallowed=~/F/) {
                   3783: 	return 'F';
                   3784:     }
                   3785: 
1.52      www      3786: # If this is generating or modifying users, exit with special codes
1.29      www      3787: 
1.643     www      3788:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3789: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3790: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3791: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3792: 	    unless ($auname) { return $thisallowed; }
                   3793: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3794: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3795: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3796: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3797: 	}
1.52      www      3798: 	return $thisallowed;
                   3799:     }
                   3800: #
1.103     harris41 3801: # Gathered so far: system, domain and course wide privileges
1.52      www      3802: #
                   3803: # Course: See if uri or referer is an individual resource that is part of 
                   3804: # the course
                   3805: 
1.620     albertel 3806:     if ($env{'request.course.id'}) {
1.232     www      3807: 
1.620     albertel 3808:        $courseprivid=$env{'request.course.id'};
                   3809:        if ($env{'request.course.sec'}) {
                   3810:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3811:        }
                   3812:        $courseprivid=~s/\_/\//;
                   3813:        my $checkreferer=1;
1.232     www      3814:        my ($match,$cond)=&is_on_map($uri);
                   3815:        if ($match) {
                   3816:            $statecond=$cond;
1.620     albertel 3817:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3818:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3819:                $thisallowed.=$1;
                   3820:                $checkreferer=0;
                   3821:            }
1.29      www      3822:        }
1.83      www      3823:        
1.148     www      3824:        if ($checkreferer) {
1.620     albertel 3825: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3826:             unless ($refuri) {
1.800     albertel 3827:                 foreach my $key (keys(%env)) {
                   3828: 		    if ($key=~/^httpref\..*\*/) {
                   3829: 			my $pattern=$key;
1.156     www      3830:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3831:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3832:                         $pattern=~s/\//\\\//g;
1.152     www      3833:                         if ($orguri=~/$pattern/) {
1.800     albertel 3834: 			    $refuri=$env{$key};
1.148     www      3835:                         }
                   3836:                     }
1.191     harris41 3837:                 }
1.148     www      3838:             }
1.232     www      3839: 
1.148     www      3840:          if ($refuri) { 
1.152     www      3841: 	  $refuri=&declutter($refuri);
1.232     www      3842:           my ($match,$cond)=&is_on_map($refuri);
                   3843:             if ($match) {
                   3844:               my $refstatecond=$cond;
1.620     albertel 3845:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3846:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3847:                   $thisallowed.=$1;
1.53      www      3848:                   $uri=$refuri;
                   3849:                   $statecond=$refstatecond;
1.52      www      3850:               }
                   3851:           }
1.148     www      3852:         }
1.29      www      3853:        }
1.52      www      3854:    }
1.29      www      3855: 
1.52      www      3856: #
1.103     harris41 3857: # Gathered now: all privileges that could apply, and condition number
1.52      www      3858: # 
                   3859: #
                   3860: # Full or no access?
                   3861: #
1.29      www      3862: 
1.52      www      3863:     if ($thisallowed=~/F/) {
                   3864: 	return 'F';
                   3865:     }
1.29      www      3866: 
1.52      www      3867:     unless ($thisallowed) {
                   3868:         return '';
                   3869:     }
1.29      www      3870: 
1.52      www      3871: # Restrictions exist, deal with them
                   3872: #
                   3873: #   C:according to course preferences
                   3874: #   R:according to resource settings
                   3875: #   L:unless locked
                   3876: #   X:according to user session state
                   3877: #
                   3878: 
                   3879: # Possibly locked functionality, check all courses
1.54      www      3880: # Locks might take effect only after 10 minutes cache expiration for other
                   3881: # courses, and 2 minutes for current course
1.52      www      3882: 
                   3883:     my $envkey;
                   3884:     if ($thisallowed=~/L/) {
1.620     albertel 3885:         foreach $envkey (keys %env) {
1.54      www      3886:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3887:                my $courseid=$2;
                   3888:                my $roleid=$1.'.'.$2;
1.92      www      3889:                $courseid=~s/^\///;
1.54      www      3890:                my $expiretime=600;
1.620     albertel 3891:                if ($env{'request.role'} eq $roleid) {
1.54      www      3892: 		  $expiretime=120;
                   3893:                }
                   3894: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3895:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3896:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3897: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3898:                }
1.620     albertel 3899:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3900:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3901: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3902:                        &log($env{'user.domain'},$env{'user.name'},
                   3903:                             $env{'user.home'},
1.57      www      3904:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3905:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3906:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3907: 		       return '';
                   3908:                    }
                   3909:                }
1.620     albertel 3910:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3911:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3912: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3913:                        &log($env{'user.domain'},$env{'user.name'},
                   3914:                             $env{'user.home'},
1.57      www      3915:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3916:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3917:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3918: 		       return '';
                   3919:                    }
                   3920:                }
                   3921: 	   }
1.29      www      3922:        }
1.52      www      3923:     }
                   3924:    
                   3925: #
                   3926: # Rest of the restrictions depend on selected course
                   3927: #
                   3928: 
1.620     albertel 3929:     unless ($env{'request.course.id'}) {
1.766     albertel 3930: 	if ($thisallowed eq 'A') {
                   3931: 	    return 'A';
1.814     raeburn  3932:         } elsif ($thisallowed eq 'B') {
                   3933:             return 'B';
1.766     albertel 3934: 	} else {
                   3935: 	    return '1';
                   3936: 	}
1.52      www      3937:     }
1.29      www      3938: 
1.52      www      3939: #
                   3940: # Now user is definitely in a course
                   3941: #
1.53      www      3942: 
                   3943: 
                   3944: # Course preferences
                   3945: 
                   3946:    if ($thisallowed=~/C/) {
1.620     albertel 3947:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3948:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3949:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3950: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3951: 	   if ($priv ne 'pch') { 
                   3952: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3953: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3954: 			$env{'request.course.id'});
                   3955: 	   }
1.237     www      3956:            return '';
                   3957:        }
                   3958: 
1.620     albertel 3959:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3960: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3961: 	   if ($priv ne 'pch') { 
                   3962: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3963: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3964: 			$env{'request.course.id'});
                   3965: 	   }
1.54      www      3966:            return '';
                   3967:        }
1.53      www      3968:    }
                   3969: 
                   3970: # Resource preferences
                   3971: 
                   3972:    if ($thisallowed=~/R/) {
1.620     albertel 3973:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3974:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3975: 	   if ($priv ne 'pch') { 
                   3976: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3977: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3978: 	   }
                   3979: 	   return '';
1.54      www      3980:        }
1.53      www      3981:    }
1.30      www      3982: 
1.246     www      3983: # Restricted by state or randomout?
1.30      www      3984: 
1.52      www      3985:    if ($thisallowed=~/X/) {
1.620     albertel 3986:       if ($env{'acc.randomout'}) {
1.579     albertel 3987: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3988:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3989:             return ''; 
                   3990:          }
1.247     www      3991:       }
                   3992:       if (&condval($statecond)) {
1.52      www      3993: 	 return '2';
                   3994:       } else {
                   3995:          return '';
                   3996:       }
                   3997:    }
1.30      www      3998: 
1.766     albertel 3999:     if ($thisallowed eq 'A') {
                   4000: 	return 'A';
1.814     raeburn  4001:     } elsif ($thisallowed eq 'B') {
                   4002:         return 'B';
1.766     albertel 4003:     }
1.52      www      4004:    return 'F';
1.232     www      4005: }
                   4006: 
1.710     albertel 4007: sub split_uri_for_cond {
                   4008:     my $uri=&deversion(&declutter(shift));
                   4009:     my @uriparts=split(/\//,$uri);
                   4010:     my $filename=pop(@uriparts);
                   4011:     my $pathname=join('/',@uriparts);
                   4012:     return ($pathname,$filename);
                   4013: }
1.232     www      4014: # --------------------------------------------------- Is a resource on the map?
                   4015: 
                   4016: sub is_on_map {
1.710     albertel 4017:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4018:     #Trying to find the conditional for the file
1.620     albertel 4019:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4020: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4021:     if ($match) {
1.289     bowersj2 4022: 	return (1,$1);
                   4023:     } else {
1.434     www      4024: 	return (0,0);
1.289     bowersj2 4025:     }
1.12      www      4026: }
                   4027: 
1.427     www      4028: # --------------------------------------------------------- Get symb from alias
                   4029: 
                   4030: sub get_symb_from_alias {
                   4031:     my $symb=shift;
                   4032:     my ($map,$resid,$url)=&decode_symb($symb);
                   4033: # Already is a symb
                   4034:     if ($url) { return $symb; }
                   4035: # Must be an alias
                   4036:     my $aliassymb='';
                   4037:     my %bighash;
1.620     albertel 4038:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4039:                             &GDBM_READER(),0640)) {
                   4040:         my $rid=$bighash{'mapalias_'.$symb};
                   4041: 	if ($rid) {
                   4042: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4043: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4044: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4045: 	}
                   4046:         untie %bighash;
                   4047:     }
                   4048:     return $aliassymb;
                   4049: }
                   4050: 
1.12      www      4051: # ----------------------------------------------------------------- Define Role
                   4052: 
                   4053: sub definerole {
                   4054:   if (allowed('mcr','/')) {
                   4055:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4056:     foreach my $role (split(':',$sysrole)) {
                   4057: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4058:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4059:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4060: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4061:                return "refused:s:$crole&$cqual"; 
                   4062:             }
                   4063:         }
1.191     harris41 4064:     }
1.800     albertel 4065:     foreach my $role (split(':',$domrole)) {
                   4066: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4067:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4068:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4069: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4070:                return "refused:d:$crole&$cqual"; 
                   4071:             }
                   4072:         }
1.191     harris41 4073:     }
1.800     albertel 4074:     foreach my $role (split(':',$courole)) {
                   4075: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4076:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4077:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4078: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4079:                return "refused:c:$crole&$cqual"; 
                   4080:             }
                   4081:         }
1.191     harris41 4082:     }
1.620     albertel 4083:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4084:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4085: 	        "rolesdef_$rolename=".
                   4086:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4087:     return reply($command,$env{'user.home'});
1.12      www      4088:   } else {
                   4089:     return 'refused';
                   4090:   }
1.105     harris41 4091: }
                   4092: 
                   4093: # ---------------- Make a metadata query against the network of library servers
                   4094: 
                   4095: sub metadata_query {
1.244     matthew  4096:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4097:     my %rhash;
1.244     matthew  4098:     my @server_list = (defined($server_array) ? @$server_array
                   4099:                                               : keys(%libserv) );
                   4100:     for my $server (@server_list) {
1.118     harris41 4101: 	unless ($custom or $customshow) {
                   4102: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4103: 	    $rhash{$server}=$reply;
                   4104: 	}
                   4105: 	else {
                   4106: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4107: 			     &escape($custom).':'.&escape($customshow),
                   4108: 			     $server);
                   4109: 	    $rhash{$server}=$reply;
                   4110: 	}
1.112     harris41 4111:     }
1.118     harris41 4112:     return \%rhash;
1.240     www      4113: }
                   4114: 
                   4115: # ----------------------------------------- Send log queries and wait for reply
                   4116: 
                   4117: sub log_query {
                   4118:     my ($uname,$udom,$query,%filters)=@_;
                   4119:     my $uhome=&homeserver($uname,$udom);
                   4120:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4121:     my $uhost=$hostname{$uhome};
1.800     albertel 4122:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4123:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4124:                        $uhome);
1.479     albertel 4125:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4126:     return get_query_reply($queryid);
                   4127: }
                   4128: 
1.818     raeburn  4129: # -------------------------- Update MySQL table for portfolio file
                   4130: 
                   4131: sub update_portfolio_table {
1.821     raeburn  4132:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4133:     my $homeserver = &homeserver($uname,$udom);
                   4134:     my $queryid=
1.821     raeburn  4135:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4136:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4137:     my $reply = &get_query_reply($queryid);
                   4138:     return $reply;
                   4139: }
                   4140: 
1.508     raeburn  4141: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4142: 
                   4143: sub fetch_enrollment_query {
1.511     raeburn  4144:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4145:     my $homeserver;
1.547     raeburn  4146:     my $maxtries = 1;
1.508     raeburn  4147:     if ($context eq 'automated') {
                   4148:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4149:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4150:     } else {
                   4151:         $homeserver = &homeserver($cnum,$dom);
                   4152:     }
1.506     raeburn  4153:     my $host=$hostname{$homeserver};
                   4154:     my $cmd = '';
1.800     albertel 4155:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4156:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4157:     }
                   4158:     $cmd =~ s/%%$//;
                   4159:     $cmd = &escape($cmd);
                   4160:     my $query = 'fetchenrollment';
1.620     albertel 4161:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4162:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4163:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4164:         return 'error: '.$queryid;
                   4165:     }
1.506     raeburn  4166:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4167:     my $tries = 1;
                   4168:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4169:         $reply = &get_query_reply($queryid);
                   4170:         $tries ++;
                   4171:     }
1.526     raeburn  4172:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4173:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4174:     } else {
1.515     raeburn  4175:         my @responses = split/:/,$reply;
                   4176:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4177:             foreach my $line (@responses) {
                   4178:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4179:                 $$replyref{$key} = $value;
                   4180:             }
                   4181:         } else {
1.506     raeburn  4182:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4183:             foreach my $line (@responses) {
                   4184:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4185:                 $$replyref{$key} = $value;
                   4186:                 if ($value > 0) {
1.800     albertel 4187:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4188:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4189:                         my $destname = $pathname.'/'.$filename;
                   4190:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4191:                         if ($xml_classlist =~ /^error/) {
                   4192:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4193:                         } else {
1.506     raeburn  4194:                             if ( open(FILE,">$destname") ) {
                   4195:                                 print FILE &unescape($xml_classlist);
                   4196:                                 close(FILE);
1.526     raeburn  4197:                             } else {
                   4198:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4199:                             }
                   4200:                         }
                   4201:                     }
                   4202:                 }
                   4203:             }
                   4204:         }
                   4205:         return 'ok';
                   4206:     }
                   4207:     return 'error';
                   4208: }
                   4209: 
1.242     www      4210: sub get_query_reply {
                   4211:     my $queryid=shift;
1.240     www      4212:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4213:     my $reply='';
                   4214:     for (1..100) {
                   4215: 	sleep 2;
                   4216:         if (-e $replyfile.'.end') {
1.448     albertel 4217: 	    if (open(my $fh,$replyfile)) {
1.240     www      4218:                $reply.=<$fh>;
1.448     albertel 4219:                close($fh);
1.240     www      4220: 	   } else { return 'error: reply_file_error'; }
1.242     www      4221:            return &unescape($reply);
                   4222: 	}
1.240     www      4223:     }
1.242     www      4224:     return 'timeout:'.$queryid;
1.240     www      4225: }
                   4226: 
                   4227: sub courselog_query {
1.241     www      4228: #
                   4229: # possible filters:
                   4230: # url: url or symb
                   4231: # username
                   4232: # domain
                   4233: # action: view, submit, grade
                   4234: # start: timestamp
                   4235: # end: timestamp
                   4236: #
1.240     www      4237:     my (%filters)=@_;
1.620     albertel 4238:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4239:     if ($filters{'url'}) {
                   4240: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4241:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4242:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4243:     }
1.620     albertel 4244:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4245:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4246:     return &log_query($cname,$cdom,'courselog',%filters);
                   4247: }
                   4248: 
                   4249: sub userlog_query {
                   4250:     my ($uname,$udom,%filters)=@_;
                   4251:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4252: }
                   4253: 
1.506     raeburn  4254: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4255: 
                   4256: sub auto_run {
1.508     raeburn  4257:     my ($cnum,$cdom) = @_;
                   4258:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4259:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4260:     return $response;
                   4261: }
1.776     albertel 4262: 
1.506     raeburn  4263: sub auto_get_sections {
1.508     raeburn  4264:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4265:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4266:     my @secs = ();
1.511     raeburn  4267:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4268:     unless ($response eq 'refused') {
                   4269:         @secs = split/:/,$response;
                   4270:     }
                   4271:     return @secs;
                   4272: }
1.776     albertel 4273: 
1.506     raeburn  4274: sub auto_new_course {
1.508     raeburn  4275:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4276:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4277:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4278:     return $response;
                   4279: }
1.776     albertel 4280: 
1.506     raeburn  4281: sub auto_validate_courseID {
1.508     raeburn  4282:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4283:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4284:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4285:     return $response;
                   4286: }
1.776     albertel 4287: 
1.506     raeburn  4288: sub auto_create_password {
1.508     raeburn  4289:     my ($cnum,$cdom,$authparam) = @_;
                   4290:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4291:     my $create_passwd = 0;
                   4292:     my $authchk = '';
1.511     raeburn  4293:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4294:     if ($response eq 'refused') {
                   4295:         $authchk = 'refused';
                   4296:     } else {
                   4297:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4298:     }
                   4299:     return ($authparam,$create_passwd,$authchk);
                   4300: }
                   4301: 
1.706     raeburn  4302: sub auto_photo_permission {
                   4303:     my ($cnum,$cdom,$students) = @_;
                   4304:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4305:     my ($outcome,$perm_reqd,$conditions) = 
                   4306: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4307:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4308: 	return (undef,undef);
                   4309:     }
1.706     raeburn  4310:     return ($outcome,$perm_reqd,$conditions);
                   4311: }
                   4312: 
                   4313: sub auto_checkphotos {
                   4314:     my ($uname,$udom,$pid) = @_;
                   4315:     my $homeserver = &homeserver($uname,$udom);
                   4316:     my ($result,$resulttype);
                   4317:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4318: 				   &escape($uname).':'.&escape($pid),
                   4319: 				   $homeserver));
1.709     albertel 4320:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4321: 	return (undef,undef);
                   4322:     }
1.706     raeburn  4323:     if ($outcome) {
                   4324:         ($result,$resulttype) = split(/:/,$outcome);
                   4325:     } 
                   4326:     return ($result,$resulttype);
                   4327: }
                   4328: 
                   4329: sub auto_photochoice {
                   4330:     my ($cnum,$cdom) = @_;
                   4331:     my $homeserver = &homeserver($cnum,$cdom);
                   4332:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4333: 						       &escape($cdom),
                   4334: 						       $homeserver)));
1.709     albertel 4335:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4336: 	return (undef,undef);
                   4337:     }
1.706     raeburn  4338:     return ($update,$comment);
                   4339: }
                   4340: 
                   4341: sub auto_photoupdate {
                   4342:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4343:     my $homeserver = &homeserver($cnum,$dom);
                   4344:     my $host=$hostname{$homeserver};
                   4345:     my $cmd = '';
                   4346:     my $maxtries = 1;
1.800     albertel 4347:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4348:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4349:     }
                   4350:     $cmd =~ s/%%$//;
                   4351:     $cmd = &escape($cmd);
                   4352:     my $query = 'institutionalphotos';
                   4353:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4354:     unless ($queryid=~/^\Q$host\E\_/) {
                   4355:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4356:         return 'error: '.$queryid;
                   4357:     }
                   4358:     my $reply = &get_query_reply($queryid);
                   4359:     my $tries = 1;
                   4360:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4361:         $reply = &get_query_reply($queryid);
                   4362:         $tries ++;
                   4363:     }
                   4364:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4365:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4366:     } else {
                   4367:         my @responses = split(/:/,$reply);
                   4368:         my $outcome = shift(@responses); 
                   4369:         foreach my $item (@responses) {
                   4370:             my ($key,$value) = split(/=/,$item);
                   4371:             $$photo{$key} = $value;
                   4372:         }
                   4373:         return $outcome;
                   4374:     }
                   4375:     return 'error';
                   4376: }
                   4377: 
1.521     raeburn  4378: sub auto_instcode_format {
1.793     albertel 4379:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4380: 	$cat_order) = @_;
1.521     raeburn  4381:     my $courses = '';
1.772     raeburn  4382:     my @homeservers;
1.521     raeburn  4383:     if ($caller eq 'global') {
1.793     albertel 4384:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4385:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4386:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4387:                     push(@homeservers,$tryserver);
                   4388:                 }
1.584     raeburn  4389:             }
                   4390:         }
1.521     raeburn  4391:     } else {
1.772     raeburn  4392:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4393:     }
1.793     albertel 4394:     foreach my $code (keys(%{$instcodes})) {
                   4395:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4396:     }
                   4397:     chop($courses);
1.772     raeburn  4398:     my $ok_response = 0;
                   4399:     my $response;
                   4400:     while (@homeservers > 0 && $ok_response == 0) {
                   4401:         my $server = shift(@homeservers); 
                   4402:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4403:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4404:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4405: 		split/:/,$response;
1.772     raeburn  4406:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4407:             push(@{$codetitles},&str2array($codetitles_str));
                   4408:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4409:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4410:             $ok_response = 1;
                   4411:         }
                   4412:     }
                   4413:     if ($ok_response) {
1.521     raeburn  4414:         return 'ok';
1.772     raeburn  4415:     } else {
                   4416:         return $response;
1.521     raeburn  4417:     }
                   4418: }
                   4419: 
1.792     raeburn  4420: sub auto_instcode_defaults {
                   4421:     my ($domain,$returnhash,$code_order) = @_;
                   4422:     my @homeservers;
1.793     albertel 4423:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4424:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4425:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4426:                 push(@homeservers,$tryserver);
                   4427:             }
                   4428:         }
                   4429:     }
                   4430:     my $ok_response = 0;
                   4431:     my $response;
                   4432:     while (@homeservers > 0 && $ok_response == 0) {
                   4433:         my $server = shift(@homeservers);
                   4434:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4435:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4436:             foreach my $pair (split(/\&/,$response)) {
                   4437:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4438:                 if ($name eq 'code_order') {
1.796     raeburn  4439:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4440:                 } else {
1.796     raeburn  4441:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4442:                 }
                   4443:             }
1.804     raeburn  4444:             $ok_response = 1;
1.792     raeburn  4445:         }
                   4446:     }
                   4447:     if ($ok_response) {
                   4448:         return 'ok';
                   4449:     } else {
                   4450:         return $response;
                   4451:     }
                   4452: } 
                   4453: 
1.777     albertel 4454: sub auto_validate_class_sec {
1.773     raeburn  4455:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4456:     my $homeserver = &homeserver($cnum,$cdom);
                   4457:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4458:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4459:     return $response;
                   4460: }
                   4461: 
1.679     raeburn  4462: # ------------------------------------------------------- Course Group routines
                   4463: 
                   4464: sub get_coursegroups {
1.809     raeburn  4465:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4466:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4467: }
                   4468: 
1.679     raeburn  4469: sub modify_coursegroup {
                   4470:     my ($cdom,$cnum,$groupsettings) = @_;
                   4471:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4472: }
                   4473: 
1.809     raeburn  4474: sub toggle_coursegroup_status {
                   4475:     my ($cdom,$cnum,$group,$action) = @_;
                   4476:     my ($from_namespace,$to_namespace);
                   4477:     if ($action eq 'delete') {
                   4478:         $from_namespace = 'coursegroups';
                   4479:         $to_namespace = 'deleted_groups';
                   4480:     } else {
                   4481:         $from_namespace = 'deleted_groups';
                   4482:         $to_namespace = 'coursegroups';
                   4483:     }
                   4484:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4485:     if (my $tmp = &error(%curr_group)) {
                   4486:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4487:         return ('read error',$tmp);
                   4488:     } else {
                   4489:         my %savedsettings = %curr_group; 
1.809     raeburn  4490:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4491:         my $deloutcome;
                   4492:         if ($result eq 'ok') {
1.809     raeburn  4493:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4494:         } else {
                   4495:             return ('write error',$result);
                   4496:         }
                   4497:         if ($deloutcome eq 'ok') {
                   4498:             return 'ok';
                   4499:         } else {
                   4500:             return ('delete error',$deloutcome);
                   4501:         }
                   4502:     }
                   4503: }
                   4504: 
1.679     raeburn  4505: sub modify_group_roles {
                   4506:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4507:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4508:     my $role = 'gr/'.&escape($userprivs);
                   4509:     my ($uname,$udom) = split(/:/,$user);
                   4510:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4511:     if ($result eq 'ok') {
                   4512:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4513:     }
1.679     raeburn  4514:     return $result;
                   4515: }
                   4516: 
                   4517: sub modify_coursegroup_membership {
                   4518:     my ($cdom,$cnum,$membership) = @_;
                   4519:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4520:     return $result;
                   4521: }
                   4522: 
1.682     raeburn  4523: sub get_active_groups {
                   4524:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4525:     my $now = time;
                   4526:     my %groups = ();
                   4527:     foreach my $key (keys(%env)) {
1.811     albertel 4528:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4529:             my ($start,$end) = split(/\./,$env{$key});
                   4530:             if (($end!=0) && ($end<$now)) { next; }
                   4531:             if (($start!=0) && ($start>$now)) { next; }
                   4532:             if ($1 eq $cdom && $2 eq $cnum) {
                   4533:                 $groups{$3} = $env{$key} ;
                   4534:             }
                   4535:         }
                   4536:     }
                   4537:     return %groups;
                   4538: }
                   4539: 
1.683     raeburn  4540: sub get_group_membership {
                   4541:     my ($cdom,$cnum,$group) = @_;
                   4542:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4543: }
                   4544: 
                   4545: sub get_users_groups {
                   4546:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4547:     my @usersgroups;
1.683     raeburn  4548:     my $cachetime=1800;
                   4549: 
                   4550:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4551:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4552:     if (defined($cached)) {
1.734     albertel 4553:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4554:     } else {  
                   4555:         $grouplist = '';
1.816     raeburn  4556:         my $courseurl = &courseid_to_courseurl($courseid);
                   4557:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4558:         my $access_end = $env{'course.'.$courseid.
                   4559:                               '.default_enrollment_end_date'};
                   4560:         my $now = time;
                   4561:         foreach my $key (keys(%roleshash)) {
                   4562:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4563:                 my $group = $1;
                   4564:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4565:                     my $start = $2;
                   4566:                     my $end = $1;
                   4567:                     if ($start == -1) { next; } # deleted from group
                   4568:                     if (($start!=0) && ($start>$now)) { next; }
                   4569:                     if (($end!=0) && ($end<$now)) {
                   4570:                         if ($access_end && $access_end < $now) {
                   4571:                             if ($access_end - $end < 86400) {
                   4572:                                 push(@usersgroups,$group);
1.733     raeburn  4573:                             }
                   4574:                         }
1.817     raeburn  4575:                         next;
1.733     raeburn  4576:                     }
1.817     raeburn  4577:                     push(@usersgroups,$group);
1.683     raeburn  4578:                 }
                   4579:             }
                   4580:         }
1.817     raeburn  4581:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4582:         $grouplist = join(':',@usersgroups);
                   4583:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4584:     }
1.733     raeburn  4585:     return @usersgroups;
1.683     raeburn  4586: }
                   4587: 
                   4588: sub devalidate_getgroups_cache {
                   4589:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4590:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4591: 
1.683     raeburn  4592:     my $hashid="$udom:$uname:$courseid";
                   4593:     &devalidate_cache_new('getgroups',$hashid);
                   4594: }
                   4595: 
1.12      www      4596: # ------------------------------------------------------------------ Plain Text
                   4597: 
                   4598: sub plaintext {
1.742     raeburn  4599:     my ($short,$type,$cid) = @_;
1.758     albertel 4600:     if ($short =~ /^cr/) {
                   4601: 	return (split('/',$short))[-1];
                   4602:     }
1.742     raeburn  4603:     if (!defined($cid)) {
                   4604:         $cid = $env{'request.course.id'};
                   4605:     }
                   4606:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4607:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4608:                                           '.plaintext'});
                   4609:     }
                   4610:     my %rolenames = (
                   4611:                       Course => 'std',
                   4612:                       Group => 'alt1',
                   4613:                     );
                   4614:     if (defined($type) && 
                   4615:          defined($rolenames{$type}) && 
                   4616:          defined($prp{$short}{$rolenames{$type}})) {
                   4617:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4618:     } else {
                   4619:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4620:     }
1.12      www      4621: }
                   4622: 
                   4623: # ----------------------------------------------------------------- Assign Role
                   4624: 
                   4625: sub assignrole {
1.357     www      4626:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4627:     my $mrole;
                   4628:     if ($role =~ /^cr\//) {
1.393     www      4629:         my $cwosec=$url;
1.811     albertel 4630:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4631: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4632:            &logthis('Refused custom assignrole: '.
                   4633:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4634: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4635:            return 'refused'; 
                   4636:         }
1.21      www      4637:         $mrole='cr';
1.678     raeburn  4638:     } elsif ($role =~ /^gr\//) {
                   4639:         my $cwogrp=$url;
1.811     albertel 4640:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4641:         unless (&allowed('mdg',$cwogrp)) {
                   4642:             &logthis('Refused group assignrole: '.
                   4643:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4644:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4645:             return 'refused';
                   4646:         }
                   4647:         $mrole='gr';
1.21      www      4648:     } else {
1.82      www      4649:         my $cwosec=$url;
1.811     albertel 4650:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4651:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4652:            &logthis('Refused assignrole: '.
                   4653:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4654: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4655:            return 'refused'; 
                   4656:         }
1.21      www      4657:         $mrole=$role;
                   4658:     }
1.620     albertel 4659:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4660:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4661:     if ($end) { $command.='_'.$end; }
1.21      www      4662:     if ($start) {
                   4663: 	if ($end) { 
1.81      www      4664:            $command.='_'.$start; 
1.21      www      4665:         } else {
1.81      www      4666:            $command.='_0_'.$start;
1.21      www      4667:         }
                   4668:     }
1.739     raeburn  4669:     my $origstart = $start;
                   4670:     my $origend = $end;
1.357     www      4671: # actually delete
                   4672:     if ($deleteflag) {
1.373     www      4673: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4674: # modify command to delete the role
1.620     albertel 4675:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4676:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4677: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4678: # set start and finish to negative values for userrolelog
                   4679:            $start=-1;
                   4680:            $end=-1;
                   4681:         }
                   4682:     }
                   4683: # send command
1.349     www      4684:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4685: # log new user role if status is ok
1.349     www      4686:     if ($answer eq 'ok') {
1.663     raeburn  4687: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4688: # for course roles, perform group memberships changes triggered by role change.
                   4689:         unless ($role =~ /^gr/) {
                   4690:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4691:                                              $origstart);
                   4692:         }
1.349     www      4693:     }
                   4694:     return $answer;
1.169     harris41 4695: }
                   4696: 
                   4697: # -------------------------------------------------- Modify user authentication
1.197     www      4698: # Overrides without validation
                   4699: 
1.169     harris41 4700: sub modifyuserauth {
                   4701:     my ($udom,$uname,$umode,$upass)=@_;
                   4702:     my $uhome=&homeserver($uname,$udom);
1.197     www      4703:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4704:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4705:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4706:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4707:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4708: 		     &escape($upass),$uhome);
1.620     albertel 4709:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4710:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4711:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4712:     &log($udom,,$uname,$uhome,
1.620     albertel 4713:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4714:                                      $env{'user.name'}.', '.$umode.
1.197     www      4715:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4716:     unless ($reply eq 'ok') {
1.197     www      4717:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4718: 	return 'error: '.$reply;
                   4719:     }   
1.170     harris41 4720:     return 'ok';
1.80      www      4721: }
                   4722: 
1.81      www      4723: # --------------------------------------------------------------- Modify a user
1.80      www      4724: 
1.81      www      4725: sub modifyuser {
1.206     matthew  4726:     my ($udom,    $uname, $uid,
                   4727:         $umode,   $upass, $first,
                   4728:         $middle,  $last,  $gene,
1.387     www      4729:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4730:     $udom= &LONCAPA::clean_domain($udom);
                   4731:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4732:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4733:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4734: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4735:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4736:                                      ' desiredhome not specified'). 
1.620     albertel 4737:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4738:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4739:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4740: # ----------------------------------------------------------------- Create User
1.406     albertel 4741:     if (($uhome eq 'no_host') && 
                   4742: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4743:         my $unhome='';
1.209     matthew  4744:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4745:             $unhome = $desiredhome;
1.620     albertel 4746: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4747: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4748:         } else { # load balancing routine for determining $unhome
1.80      www      4749:             my $tryserver;
1.81      www      4750:             my $loadm=10000000;
1.80      www      4751:             foreach $tryserver (keys %libserv) {
                   4752: 	       if ($hostdom{$tryserver} eq $udom) {
                   4753:                   my $answer=reply('load',$tryserver);
                   4754:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4755: 		      $loadm=$answer;
                   4756:                       $unhome=$tryserver;
                   4757:                   }
                   4758: 	       }
                   4759: 	    }
                   4760:         }
                   4761:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4762: 	    return 'error: unable to find a home server for '.$uname.
                   4763:                    ' in domain '.$udom;
1.80      www      4764:         }
                   4765:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4766:                          &escape($upass),$unhome);
                   4767: 	unless ($reply eq 'ok') {
                   4768:             return 'error: '.$reply;
                   4769:         }   
1.230     stredwic 4770:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4771:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4772: 	    return 'error: unable verify users home machine.';
1.80      www      4773:         }
1.209     matthew  4774:     }   # End of creation of new user
1.80      www      4775: # ---------------------------------------------------------------------- Add ID
                   4776:     if ($uid) {
                   4777:        $uid=~tr/A-Z/a-z/;
                   4778:        my %uidhash=&idrget($udom,$uname);
1.196     www      4779:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4780:          && (!$forceid)) {
1.80      www      4781: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4782: 	      return 'error: user id "'.$uid.'" does not match '.
                   4783:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4784:           }
                   4785:        } else {
                   4786: 	  &idput($udom,($uname => $uid));
                   4787:        }
                   4788:     }
                   4789: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4790:     my @tmp=&get('environment',
1.134     albertel 4791: 		   ['firstname','middlename','lastname','generation'],
                   4792: 		   $udom,$uname);
1.313     matthew  4793:     my %names;
                   4794:     if ($tmp[0] =~ m/^error:.*/) { 
                   4795:         %names=(); 
                   4796:     } else {
                   4797:         %names = @tmp;
                   4798:     }
1.388     www      4799: #
                   4800: # Make sure to not trash student environment if instructor does not bother
                   4801: # to supply name and email information
                   4802: #
                   4803:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4804:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4805:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4806:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4807:     if ($email) {
                   4808:        $email=~s/[^\w\@\.\-\,]//gs;
                   4809:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4810: 			   $names{'critnotification'} = $email;
                   4811: 			   $names{'permanentemail'} = $email; }
                   4812:     }
1.134     albertel 4813:     my $reply = &put('environment', \%names, $udom,$uname);
                   4814:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4815:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4816:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4817:              $umode.', '.$first.', '.$middle.', '.
                   4818: 	     $last.', '.$gene.' by '.
1.620     albertel 4819:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4820:     return 'ok';
1.80      www      4821: }
                   4822: 
1.81      www      4823: # -------------------------------------------------------------- Modify student
1.80      www      4824: 
1.81      www      4825: sub modifystudent {
                   4826:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4827:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4828:     if (!$cid) {
1.620     albertel 4829: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4830: 	    return 'not_in_class';
                   4831: 	}
1.80      www      4832:     }
                   4833: # --------------------------------------------------------------- Make the user
1.81      www      4834:     my $reply=&modifyuser
1.209     matthew  4835: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4836:          $desiredhome,$email);
1.80      www      4837:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4838:     # This will cause &modify_student_enrollment to get the uid from the
                   4839:     # students environment
                   4840:     $uid = undef if (!$forceid);
1.455     albertel 4841:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4842: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4843:     return $reply;
                   4844: }
                   4845: 
                   4846: sub modify_student_enrollment {
1.515     raeburn  4847:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4848:     my ($cdom,$cnum,$chome);
                   4849:     if (!$cid) {
1.620     albertel 4850: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4851: 	    return 'not_in_class';
                   4852: 	}
1.620     albertel 4853: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4854: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4855:     } else {
                   4856: 	($cdom,$cnum)=split(/_/,$cid);
                   4857:     }
1.620     albertel 4858:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4859:     if (!$chome) {
1.457     raeburn  4860: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4861:     }
1.455     albertel 4862:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4863:     # Make sure the user exists
1.81      www      4864:     my $uhome=&homeserver($uname,$udom);
                   4865:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4866: 	return 'error: no such user';
                   4867:     }
1.297     matthew  4868:     # Get student data if we were not given enough information
                   4869:     if (!defined($first)  || $first  eq '' || 
                   4870:         !defined($last)   || $last   eq '' || 
                   4871:         !defined($uid)    || $uid    eq '' || 
                   4872:         !defined($middle) || $middle eq '' || 
                   4873:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4874:         # They did not supply us with enough data to enroll the student, so
                   4875:         # we need to pick up more information.
1.297     matthew  4876:         my %tmp = &get('environment',
1.294     matthew  4877:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4878:                        ,$udom,$uname);
                   4879: 
1.800     albertel 4880:         #foreach my $key (keys(%tmp)) {
                   4881:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4882:         #}
1.294     matthew  4883:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4884:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4885:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4886:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4887:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4888:     }
1.556     albertel 4889:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4890:     my $reply=cput('classlist',
                   4891: 		   {"$uname:$udom" => 
1.515     raeburn  4892: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4893: 		   $cdom,$cnum);
1.81      www      4894:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4895: 	return 'error: '.$reply;
1.652     albertel 4896:     } else {
                   4897: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4898:     }
1.297     matthew  4899:     # Add student role to user
1.83      www      4900:     my $uurl='/'.$cid;
1.81      www      4901:     $uurl=~s/\_/\//g;
                   4902:     if ($usec) {
                   4903: 	$uurl.='/'.$usec;
                   4904:     }
                   4905:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4906: }
                   4907: 
1.556     albertel 4908: sub format_name {
                   4909:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4910:     my $name;
                   4911:     if ($first ne 'lastname') {
                   4912: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4913:     } else {
                   4914: 	if ($lastname=~/\S/) {
                   4915: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4916: 	    $name=~s/\s+,/,/;
                   4917: 	} else {
                   4918: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4919: 	}
                   4920:     }
                   4921:     $name=~s/^\s+//;
                   4922:     $name=~s/\s+$//;
                   4923:     $name=~s/\s+/ /g;
                   4924:     return $name;
                   4925: }
                   4926: 
1.84      www      4927: # ------------------------------------------------- Write to course preferences
                   4928: 
                   4929: sub writecoursepref {
                   4930:     my ($courseid,%prefs)=@_;
                   4931:     $courseid=~s/^\///;
                   4932:     $courseid=~s/\_/\//g;
                   4933:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4934:     my $chome=homeserver($cnum,$cdomain);
                   4935:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4936: 	return 'error: no such course';
                   4937:     }
                   4938:     my $cstring='';
1.800     albertel 4939:     foreach my $pref (keys(%prefs)) {
                   4940: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4941:     }
1.84      www      4942:     $cstring=~s/\&$//;
                   4943:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4944: }
                   4945: 
                   4946: # ---------------------------------------------------------- Make/modify course
                   4947: 
                   4948: sub createcourse {
1.741     raeburn  4949:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4950:         $course_owner,$crstype)=@_;
1.84      www      4951:     $url=&declutter($url);
                   4952:     my $cid='';
1.264     matthew  4953:     unless (&allowed('ccc',$udom)) {
1.84      www      4954:         return 'refused';
                   4955:     }
                   4956: # ------------------------------------------------------------------- Create ID
1.674     www      4957:    my $uname=int(1+rand(9)).
                   4958:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4959:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4960:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4961: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4962:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4963:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4964:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4965:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4966:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4967:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4968:            return 'error: unable to generate unique course-ID';
                   4969:        } 
                   4970:    }
1.264     matthew  4971: # ------------------------------------------------ Check supplied server name
1.620     albertel 4972:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4973:     if (! exists($libserv{$course_server})) {
                   4974:         return 'error:bad server name '.$course_server;
                   4975:     }
1.84      www      4976: # ------------------------------------------------------------- Make the course
                   4977:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4978:                       $course_server);
1.84      www      4979:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4980:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4981:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4982: 	return 'error: no such course';
                   4983:     }
1.271     www      4984: # ----------------------------------------------------------------- Course made
1.516     raeburn  4985: # log existence
                   4986:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4987:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4988:                   &escape($crstype),$uhome);
1.358     www      4989:     &flushcourselogs();
                   4990: # set toplevel url
1.271     www      4991:     my $topurl=$url;
                   4992:     unless ($nonstandard) {
                   4993: # ------------------------------------------ For standard courses, make top url
                   4994:         my $mapurl=&clutter($url);
1.278     www      4995:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4996:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4997: <map>
                   4998: <resource id="1" type="start"></resource>
                   4999: <resource id="2" src="$mapurl"></resource>
                   5000: <resource id="3" type="finish"></resource>
                   5001: <link index="1" from="1" to="2"></link>
                   5002: <link index="2" from="2" to="3"></link>
                   5003: </map>
                   5004: ENDINITMAP
                   5005:         $topurl=&declutter(
1.638     albertel 5006:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5007:                           );
                   5008:     }
                   5009: # ----------------------------------------------------------- Write preferences
1.84      www      5010:     &writecoursepref($udom.'_'.$uname,
                   5011:                      ('description' => $description,
1.271     www      5012:                       'url'         => $topurl));
1.84      www      5013:     return '/'.$udom.'/'.$uname;
                   5014: }
                   5015: 
1.813     albertel 5016: sub is_course {
                   5017:     my ($cdom,$cnum) = @_;
                   5018:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5019: 				undef,'.');
                   5020:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5021:         return 1;
                   5022:     }
                   5023:     return 0;
                   5024: }
                   5025: 
1.21      www      5026: # ---------------------------------------------------------- Assign Custom Role
                   5027: 
                   5028: sub assigncustomrole {
1.357     www      5029:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5030:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5031:                        $end,$start,$deleteflag);
1.21      www      5032: }
                   5033: 
                   5034: # ----------------------------------------------------------------- Revoke Role
                   5035: 
                   5036: sub revokerole {
1.357     www      5037:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5038:     my $now=time;
1.357     www      5039:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5040: }
                   5041: 
                   5042: # ---------------------------------------------------------- Revoke Custom Role
                   5043: 
                   5044: sub revokecustomrole {
1.357     www      5045:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5046:     my $now=time;
1.357     www      5047:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5048:            $deleteflag);
1.17      www      5049: }
                   5050: 
1.533     banghart 5051: # ------------------------------------------------------------ Disk usage
1.535     albertel 5052: sub diskusage {
1.533     banghart 5053:     my ($udom,$uname,$directoryRoot)=@_;
                   5054:     $directoryRoot =~ s/\/$//;
1.535     albertel 5055:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5056:     return $listing;
1.512     banghart 5057: }
                   5058: 
1.566     banghart 5059: sub is_locked {
                   5060:     my ($file_name, $domain, $user) = @_;
                   5061:     my @check;
                   5062:     my $is_locked;
                   5063:     push @check, $file_name;
1.613     albertel 5064:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5065: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5066:     my ($tmp)=keys(%locked);
                   5067:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5068:     
1.566     banghart 5069:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5070:         $is_locked = 'false';
                   5071:         foreach my $entry (@{$locked{$file_name}}) {
                   5072:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5073:                $is_locked = 'true';
                   5074:                last;
1.745     raeburn  5075:            }
                   5076:        }
1.566     banghart 5077:     } else {
                   5078:         $is_locked = 'false';
                   5079:     }
                   5080: }
                   5081: 
1.759     albertel 5082: sub declutter_portfile {
                   5083:     my ($file) = @_;
                   5084:     &logthis("got $file");
                   5085:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5086:     &logthis("ret $file");
                   5087:     return $file;
                   5088: }
                   5089: 
1.559     banghart 5090: # ------------------------------------------------------------- Mark as Read Only
                   5091: 
                   5092: sub mark_as_readonly {
                   5093:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5094:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5095:     my ($tmp)=keys(%current_permissions);
                   5096:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5097:     foreach my $file (@{$files}) {
1.759     albertel 5098: 	$file = &declutter_portfile($file);
1.561     banghart 5099:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5100:     }
1.613     albertel 5101:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5102:     return;
                   5103: }
                   5104: 
1.572     banghart 5105: # ------------------------------------------------------------Save Selected Files
                   5106: 
                   5107: sub save_selected_files {
                   5108:     my ($user, $path, @files) = @_;
                   5109:     my $filename = $user."savedfiles";
1.573     banghart 5110:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5111:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5112:     foreach my $file (@files) {
1.620     albertel 5113:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5114:     }
                   5115:     foreach my $file (@other_files) {
1.574     banghart 5116:         print (OUT $file."\n");
1.572     banghart 5117:     }
1.574     banghart 5118:     close (OUT);
1.572     banghart 5119:     return 'ok';
                   5120: }
                   5121: 
1.574     banghart 5122: sub clear_selected_files {
                   5123:     my ($user) = @_;
                   5124:     my $filename = $user."savedfiles";
                   5125:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5126:     print (OUT undef);
                   5127:     close (OUT);
                   5128:     return ("ok");    
                   5129: }
                   5130: 
1.572     banghart 5131: sub files_in_path {
                   5132:     my ($user, $path) = @_;
                   5133:     my $filename = $user."savedfiles";
                   5134:     my %return_files;
1.574     banghart 5135:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5136:     while (my $line_in = <IN>) {
1.574     banghart 5137:         chomp ($line_in);
                   5138:         my @paths_and_file = split (m!/!, $line_in);
                   5139:         my $file_part = pop (@paths_and_file);
                   5140:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5141:         $path_part.='/';
                   5142:         my $path_and_file = $path_part.$file_part;
                   5143:         if ($path_part eq $path) {
                   5144:             $return_files{$file_part}= 'selected';
                   5145:         }
                   5146:     }
1.574     banghart 5147:     close (IN);
                   5148:     return (\%return_files);
1.572     banghart 5149: }
                   5150: 
                   5151: # called in portfolio select mode, to show files selected NOT in current directory
                   5152: sub files_not_in_path {
                   5153:     my ($user, $path) = @_;
                   5154:     my $filename = $user."savedfiles";
                   5155:     my @return_files;
                   5156:     my $path_part;
1.800     albertel 5157:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5158:     while (my $line = <IN>) {
1.572     banghart 5159:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5160:         my @paths_and_file = split(m|/|, $line);
                   5161:         my $file_part = pop(@paths_and_file);
                   5162:         chomp($file_part);
                   5163:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5164:         $path_part .= '/';
                   5165:         my $path_and_file = $path_part.$file_part;
                   5166:         if ($path_part ne $path) {
1.800     albertel 5167:             push(@return_files, ($path_and_file));
1.572     banghart 5168:         }
                   5169:     }
1.800     albertel 5170:     close(OUT);
1.574     banghart 5171:     return (@return_files);
1.572     banghart 5172: }
                   5173: 
1.745     raeburn  5174: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5175: 
1.745     raeburn  5176: sub get_portfile_permissions {
                   5177:     my ($domain,$user) = @_;
1.613     albertel 5178:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5179:     my ($tmp)=keys(%current_permissions);
                   5180:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5181:     return \%current_permissions;
                   5182: }
                   5183: 
                   5184: #---------------------------------------------Get portfolio file access controls
                   5185: 
1.749     raeburn  5186: sub get_access_controls {
1.745     raeburn  5187:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5188:     my %access;
                   5189:     my $real_file = $file;
                   5190:     $file =~ s/\.meta$//;
1.745     raeburn  5191:     if (defined($file)) {
1.749     raeburn  5192:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5193:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5194:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5195:             }
                   5196:         }
1.745     raeburn  5197:     } else {
1.749     raeburn  5198:         foreach my $key (keys(%{$current_permissions})) {
                   5199:             if ($key =~ /\0accesscontrol$/) {
                   5200:                 if (defined($group)) {
                   5201:                     if ($key !~ m-^\Q$group\E/-) {
                   5202:                         next;
                   5203:                     }
                   5204:                 }
                   5205:                 my ($fullpath) = split(/\0/,$key);
                   5206:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5207:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5208:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5209:                     }
                   5210:                 }
                   5211:             }
                   5212:         }
                   5213:     }
                   5214:     return %access;
                   5215: }
                   5216: 
                   5217: sub modify_access_controls {
                   5218:     my ($file_name,$changes,$domain,$user)=@_;
                   5219:     my ($outcome,$deloutcome);
                   5220:     my %store_permissions;
                   5221:     my %new_values;
                   5222:     my %new_control;
                   5223:     my %translation;
                   5224:     my @deletions = ();
                   5225:     my $now = time;
                   5226:     if (exists($$changes{'activate'})) {
                   5227:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5228:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5229:             my $numnew = scalar(@newitems);
                   5230:             for (my $i=0; $i<$numnew; $i++) {
                   5231:                 my $newkey = $newitems[$i];
                   5232:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5233:                 if ($newkey =~ /^\d+:/) { 
                   5234:                     $newkey =~ s/^(\d+)/$newid/;
                   5235:                     $translation{$1} = $newid;
                   5236:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5237:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5238:                     $translation{$1} = $newid;
                   5239:                 }
1.749     raeburn  5240:                 $new_values{$file_name."\0".$newkey} = 
                   5241:                                           $$changes{'activate'}{$newitems[$i]};
                   5242:                 $new_control{$newkey} = $now;
                   5243:             }
                   5244:         }
                   5245:     }
                   5246:     my %todelete;
                   5247:     my %changed_items;
                   5248:     foreach my $action ('delete','update') {
                   5249:         if (exists($$changes{$action})) {
                   5250:             if (ref($$changes{$action}) eq 'HASH') {
                   5251:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5252:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5253:                     if ($action eq 'delete') { 
                   5254:                         $todelete{$itemnum} = 1;
                   5255:                     } else {
                   5256:                         $changed_items{$itemnum} = $key;
                   5257:                     }
                   5258:                 }
1.745     raeburn  5259:             }
                   5260:         }
1.749     raeburn  5261:     }
                   5262:     # get lock on access controls for file.
                   5263:     my $lockhash = {
                   5264:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5265:                                                        ':'.$env{'user.domain'},
                   5266:                    }; 
                   5267:     my $tries = 0;
                   5268:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5269:    
                   5270:     while (($gotlock ne 'ok') && $tries <3) {
                   5271:         $tries ++;
                   5272:         sleep 1;
                   5273:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5274:     }
                   5275:     if ($gotlock eq 'ok') {
                   5276:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5277:         my ($tmp)=keys(%curr_permissions);
                   5278:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5279:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5280:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5281:             if (ref($curr_controls) eq 'HASH') {
                   5282:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5283:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5284:                     if (defined($todelete{$itemnum})) {
                   5285:                         push(@deletions,$file_name."\0".$control_item);
                   5286:                     } else {
                   5287:                         if (defined($changed_items{$itemnum})) {
                   5288:                             $new_control{$changed_items{$itemnum}} = $now;
                   5289:                             push(@deletions,$file_name."\0".$control_item);
                   5290:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5291:                         } else {
                   5292:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5293:                         }
                   5294:                     }
1.745     raeburn  5295:                 }
                   5296:             }
                   5297:         }
1.749     raeburn  5298:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5299:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5300:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5301:         #  remove lock
                   5302:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5303:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5304:         my ($file,$group);
                   5305:         if (&is_course($domain,$user)) {
                   5306:             ($group,$file) = split(/\//,$file_name,2);
                   5307:         } else {
                   5308:             $file = $file_name;
                   5309:         }
                   5310:         my $sqlresult =
                   5311:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5312:                                     $group);
1.749     raeburn  5313:     } else {
                   5314:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5315:     }
1.749     raeburn  5316:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5317: }
                   5318: 
                   5319: #------------------------------------------------------Get Marked as Read Only
                   5320: 
                   5321: sub get_marked_as_readonly {
                   5322:     my ($domain,$user,$what,$group) = @_;
                   5323:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5324:     my @readonly_files;
1.629     banghart 5325:     my $cmp1=$what;
                   5326:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5327:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5328:         if (defined($group)) {
                   5329:             if ($file_name !~ m-^\Q$group\E/-) {
                   5330:                 next;
                   5331:             }
                   5332:         }
1.561     banghart 5333:         if (ref($value) eq "ARRAY"){
                   5334:             foreach my $stored_what (@{$value}) {
1.629     banghart 5335:                 my $cmp2=$stored_what;
1.759     albertel 5336:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5337:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5338:                 }
1.629     banghart 5339:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5340:                     push(@readonly_files, $file_name);
1.745     raeburn  5341:                     last;
1.563     banghart 5342:                 } elsif (!defined($what)) {
                   5343:                     push(@readonly_files, $file_name);
1.745     raeburn  5344:                     last;
1.561     banghart 5345:                 }
                   5346:             }
1.745     raeburn  5347:         }
1.561     banghart 5348:     }
                   5349:     return @readonly_files;
                   5350: }
1.577     banghart 5351: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5352: 
1.577     banghart 5353: sub get_marked_as_readonly_hash {
1.745     raeburn  5354:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5355:     my %readonly_files;
1.745     raeburn  5356:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5357:         if (defined($group)) {
                   5358:             if ($file_name !~ m-^\Q$group\E/-) {
                   5359:                 next;
                   5360:             }
                   5361:         }
1.577     banghart 5362:         if (ref($value) eq "ARRAY"){
                   5363:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5364:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5365:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5366:                         if ($lock_descriptor eq 'graded') {
                   5367:                             $readonly_files{$file_name} = 'graded';
                   5368:                         } elsif ($lock_descriptor eq 'handback') {
                   5369:                             $readonly_files{$file_name} = 'handback';
                   5370:                         } else {
                   5371:                             if (!exists($readonly_files{$file_name})) {
                   5372:                                 $readonly_files{$file_name} = 'locked';
                   5373:                             }
                   5374:                         }
1.745     raeburn  5375:                     }
1.750     banghart 5376:                 } 
1.577     banghart 5377:             }
                   5378:         } 
                   5379:     }
                   5380:     return %readonly_files;
                   5381: }
1.559     banghart 5382: # ------------------------------------------------------------ Unmark as Read Only
                   5383: 
                   5384: sub unmark_as_readonly {
1.629     banghart 5385:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5386:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5387:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5388:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5389:     my $symb_crs = $what;
                   5390:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5391:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5392:     my ($tmp)=keys(%current_permissions);
                   5393:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5394:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5395:     foreach my $file (@readonly_files) {
1.759     albertel 5396: 	my $clean_file = &declutter_portfile($file);
                   5397: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5398: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5399:         my @new_locks;
                   5400:         my @del_keys;
                   5401:         if (ref($current_locks) eq "ARRAY"){
                   5402:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5403:                 my $compare=$locker;
1.749     raeburn  5404:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5405:                     $compare=join('',@{$locker});
1.746     raeburn  5406:                     if ($compare ne $symb_crs) {
                   5407:                         push(@new_locks, $locker);
                   5408:                     }
1.563     banghart 5409:                 }
                   5410:             }
1.650     albertel 5411:             if (scalar(@new_locks) > 0) {
1.563     banghart 5412:                 $current_permissions{$file} = \@new_locks;
                   5413:             } else {
                   5414:                 push(@del_keys, $file);
1.613     albertel 5415:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5416:                 delete($current_permissions{$file});
1.563     banghart 5417:             }
                   5418:         }
1.561     banghart 5419:     }
1.613     albertel 5420:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5421:     return;
                   5422: }
1.512     banghart 5423: 
1.17      www      5424: # ------------------------------------------------------------ Directory lister
                   5425: 
                   5426: sub dirlist {
1.253     stredwic 5427:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5428: 
1.18      www      5429:     $uri=~s/^\///;
                   5430:     $uri=~s/\/$//;
1.253     stredwic 5431:     my ($udom, $uname);
                   5432:     (undef,$udom,$uname)=split(/\//,$uri);
                   5433:     if(defined($userdomain)) {
                   5434:         $udom = $userdomain;
                   5435:     }
                   5436:     if(defined($username)) {
                   5437:         $uname = $username;
                   5438:     }
                   5439: 
                   5440:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5441:     if(defined($alternateDirectoryRoot)) {
                   5442:         $dirRoot = $alternateDirectoryRoot;
                   5443:         $dirRoot =~ s/\/$//;
1.751     banghart 5444:     }
1.253     stredwic 5445: 
                   5446:     if($udom) {
                   5447:         if($uname) {
1.800     albertel 5448:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5449: 				 &homeserver($uname,$udom));
1.605     matthew  5450:             my @listing_results;
                   5451:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5452:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5453: 				  &homeserver($uname,$udom));
1.605     matthew  5454:                 @listing_results = split(/:/,$listing);
                   5455:             } else {
                   5456:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5457:             }
                   5458:             return @listing_results;
1.253     stredwic 5459:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5460:             my %allusers;
                   5461:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5462:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5463:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5464: 					 $udom, $tryserver);
1.605     matthew  5465:                     my @listing_results;
                   5466:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5467:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5468: 					  $udom, $tryserver);
1.605     matthew  5469:                         @listing_results = split(/:/,$listing);
                   5470:                     } else {
                   5471:                         @listing_results =
                   5472:                             map { &unescape($_); } split(/:/,$listing);
                   5473:                     }
                   5474:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5475:                         $listing_results[0] ne 'empty'       &&
                   5476:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5477:                         foreach my $line (@listing_results) {
                   5478:                             my ($entry) = split(/&/,$line,2);
                   5479:                             $allusers{$entry} = 1;
1.253     stredwic 5480:                         }
                   5481:                     }
1.191     harris41 5482:                 }
1.253     stredwic 5483:             }
                   5484:             my $alluserstr='';
1.800     albertel 5485:             foreach my $user (sort(keys(%allusers))) {
                   5486:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5487:             }
                   5488:             $alluserstr=~s/:$//;
                   5489:             return split(/:/,$alluserstr);
                   5490:         } else {
1.800     albertel 5491:             return ('missing user name');
1.253     stredwic 5492:         }
                   5493:     } elsif(!defined($alternateDirectoryRoot)) {
                   5494:         my $tryserver;
                   5495:         my %alldom=();
1.800     albertel 5496:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5497:             $alldom{$hostdom{$tryserver}}=1;
                   5498:         }
                   5499:         my $alldomstr='';
1.800     albertel 5500:         foreach my $domain (sort(keys(%alldom))) {
                   5501:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5502:         }
                   5503:         $alldomstr=~s/:$//;
                   5504:         return split(/:/,$alldomstr);       
                   5505:     } else {
1.800     albertel 5506:         return ('missing domain');
1.275     stredwic 5507:     }
                   5508: }
                   5509: 
                   5510: # --------------------------------------------- GetFileTimestamp
                   5511: # This function utilizes dirlist and returns the date stamp for
                   5512: # when it was last modified.  It will also return an error of -1
                   5513: # if an error occurs
                   5514: 
1.410     matthew  5515: ##
                   5516: ## FIXME: This subroutine assumes its caller knows something about the
                   5517: ## directory structure of the home server for the student ($root).
                   5518: ## Not a good assumption to make.  Since this is for looking up files
                   5519: ## in user directories, the full path should be constructed by lond, not
                   5520: ## whatever machine we request data from.
                   5521: ##
1.275     stredwic 5522: sub GetFileTimestamp {
                   5523:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5524:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5525:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5526:     my $subdir=$studentName.'__';
                   5527:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5528:     my $proname="$studentDomain/$subdir/$studentName";
                   5529:     $proname .= '/'.$filename;
1.375     matthew  5530:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5531:                                               $studentName, $root);
1.275     stredwic 5532:     my @stats = split('&', $fileStat);
                   5533:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5534:         # @stats contains first the filename, then the stat output
                   5535:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5536:     } else {
                   5537:         return -1;
1.253     stredwic 5538:     }
1.26      www      5539: }
                   5540: 
1.712     albertel 5541: sub stat_file {
                   5542:     my ($uri) = @_;
1.787     albertel 5543:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5544: 
1.712     albertel 5545:     my ($udom,$uname,$file,$dir);
                   5546:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5547: 	($udom,$uname,$file) =
1.811     albertel 5548: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5549: 	$file = 'userfiles/'.$file;
1.740     www      5550: 	$dir = &propath($udom,$uname);
1.712     albertel 5551:     }
                   5552:     if ($uri =~ m-^/res/-) {
                   5553: 	($udom,$uname) = 
1.807     albertel 5554: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5555: 	$file = $uri;
                   5556:     }
                   5557: 
                   5558:     if (!$udom || !$uname || !$file) {
                   5559: 	# unable to handle the uri
                   5560: 	return ();
                   5561:     }
                   5562: 
                   5563:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5564:     my @stats = split('&', $result);
1.721     banghart 5565:     
1.712     albertel 5566:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5567: 	shift(@stats); #filename is first
                   5568: 	return @stats;
                   5569:     }
                   5570:     return ();
                   5571: }
                   5572: 
1.26      www      5573: # -------------------------------------------------------- Value of a Condition
                   5574: 
1.713     albertel 5575: # gets the value of a specific preevaluated condition
                   5576: #    stored in the string  $env{user.state.<cid>}
                   5577: # or looks up a condition reference in the bighash and if if hasn't
                   5578: # already been evaluated recurses into docondval to get the value of
                   5579: # the condition, then memoizing it to 
                   5580: #   $env{user.state.<cid>.<condition>}
1.40      www      5581: sub directcondval {
                   5582:     my $number=shift;
1.620     albertel 5583:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5584: 	&Apache::lonuserstate::evalstate();
                   5585:     }
1.713     albertel 5586:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5587: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5588:     } elsif ($number =~ /^_/) {
                   5589: 	my $sub_condition;
                   5590: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5591: 		&GDBM_READER(),0640)) {
                   5592: 	    $sub_condition=$bighash{'conditions'.$number};
                   5593: 	    untie(%bighash);
                   5594: 	}
                   5595: 	my $value = &docondval($sub_condition);
                   5596: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5597: 	return $value;
                   5598:     }
1.620     albertel 5599:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5600:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5601:     } else {
                   5602:        return 2;
                   5603:     }
                   5604: }
                   5605: 
1.713     albertel 5606: # get the collection of conditions for this resource
1.26      www      5607: sub condval {
                   5608:     my $condidx=shift;
1.54      www      5609:     my $allpathcond='';
1.713     albertel 5610:     foreach my $cond (split(/\|/,$condidx)) {
                   5611: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5612: 	    $allpathcond.=
                   5613: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5614: 	}
1.191     harris41 5615:     }
1.54      www      5616:     $allpathcond=~s/\|$//;
1.713     albertel 5617:     return &docondval($allpathcond);
                   5618: }
                   5619: 
                   5620: #evaluates an expression of conditions
                   5621: sub docondval {
                   5622:     my ($allpathcond) = @_;
                   5623:     my $result=0;
                   5624:     if ($env{'request.course.id'}
                   5625: 	&& defined($allpathcond)) {
                   5626: 	my $operand='|';
                   5627: 	my @stack;
                   5628: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5629: 	    if ($chunk eq '(') {
                   5630: 		push @stack,($operand,$result);
                   5631: 	    } elsif ($chunk eq ')') {
                   5632: 		my $before=pop @stack;
                   5633: 		if (pop @stack eq '&') {
                   5634: 		    $result=$result>$before?$before:$result;
                   5635: 		} else {
                   5636: 		    $result=$result>$before?$result:$before;
                   5637: 		}
                   5638: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5639: 		$operand=$chunk;
                   5640: 	    } else {
                   5641: 		my $new=directcondval($chunk);
                   5642: 		if ($operand eq '&') {
                   5643: 		    $result=$result>$new?$new:$result;
                   5644: 		} else {
                   5645: 		    $result=$result>$new?$result:$new;
                   5646: 		}
                   5647: 	    }
                   5648: 	}
1.26      www      5649:     }
                   5650:     return $result;
1.421     albertel 5651: }
                   5652: 
                   5653: # ---------------------------------------------------- Devalidate courseresdata
                   5654: 
                   5655: sub devalidatecourseresdata {
                   5656:     my ($coursenum,$coursedomain)=@_;
                   5657:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5658:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5659: }
                   5660: 
1.763     www      5661: 
1.200     www      5662: # --------------------------------------------------- Course Resourcedata Query
                   5663: 
1.624     albertel 5664: sub get_courseresdata {
                   5665:     my ($coursenum,$coursedomain)=@_;
1.200     www      5666:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5667:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5668:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5669:     my %dumpreply;
1.417     albertel 5670:     unless (defined($cached)) {
1.624     albertel 5671: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5672: 	$result=\%dumpreply;
1.251     albertel 5673: 	my ($tmp) = keys(%dumpreply);
                   5674: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5675: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5676: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5677: 	    return $tmp;
1.416     albertel 5678: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5679: 	    $result=undef;
1.599     albertel 5680: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5681: 	}
                   5682:     }
1.624     albertel 5683:     return $result;
                   5684: }
                   5685: 
1.633     albertel 5686: sub devalidateuserresdata {
                   5687:     my ($uname,$udom)=@_;
                   5688:     my $hashid="$udom:$uname";
                   5689:     &devalidate_cache_new('userres',$hashid);
                   5690: }
                   5691: 
1.624     albertel 5692: sub get_userresdata {
                   5693:     my ($uname,$udom)=@_;
                   5694:     #most student don\'t have any data set, check if there is some data
                   5695:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5696: 
                   5697:     my $hashid="$udom:$uname";
                   5698:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5699:     if (!defined($cached)) {
                   5700: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5701: 	$result=\%resourcedata;
                   5702: 	&do_cache_new('userres',$hashid,$result,600);
                   5703:     }
                   5704:     my ($tmp)=keys(%$result);
                   5705:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5706: 	return $result;
                   5707:     }
                   5708:     #error 2 occurs when the .db doesn't exist
                   5709:     if ($tmp!~/error: 2 /) {
1.672     albertel 5710: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5711: 		 " Trying to get resource data for ".
                   5712: 		 $uname." at ".$udom.": ".
                   5713: 		 $tmp."</font>");
                   5714:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5715: 	#&EXT_cache_set($udom,$uname);
                   5716: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5717: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5718:     }
                   5719:     return $tmp;
                   5720: }
                   5721: 
                   5722: sub resdata {
                   5723:     my ($name,$domain,$type,@which)=@_;
                   5724:     my $result;
                   5725:     if ($type eq 'course') {
                   5726: 	$result=&get_courseresdata($name,$domain);
                   5727:     } elsif ($type eq 'user') {
                   5728: 	$result=&get_userresdata($name,$domain);
                   5729:     }
                   5730:     if (!ref($result)) { return $result; }    
1.251     albertel 5731:     foreach my $item (@which) {
1.417     albertel 5732: 	if (defined($result->{$item})) {
                   5733: 	    return $result->{$item};
1.251     albertel 5734: 	}
1.250     albertel 5735:     }
1.291     albertel 5736:     return undef;
1.200     www      5737: }
                   5738: 
1.379     matthew  5739: #
                   5740: # EXT resource caching routines
                   5741: #
                   5742: 
                   5743: sub clear_EXT_cache_status {
1.383     albertel 5744:     &delenv('cache.EXT.');
1.379     matthew  5745: }
                   5746: 
                   5747: sub EXT_cache_status {
                   5748:     my ($target_domain,$target_user) = @_;
1.383     albertel 5749:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5750:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5751:         # We know already the user has no data
                   5752:         return 1;
                   5753:     } else {
                   5754:         return 0;
                   5755:     }
                   5756: }
                   5757: 
                   5758: sub EXT_cache_set {
                   5759:     my ($target_domain,$target_user) = @_;
1.383     albertel 5760:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5761:     #&appenv($cachename => time);
1.379     matthew  5762: }
                   5763: 
1.28      www      5764: # --------------------------------------------------------- Value of a Variable
1.58      www      5765: sub EXT {
1.715     albertel 5766: 
1.395     albertel 5767:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5768:     unless ($varname) { return ''; }
1.218     albertel 5769:     #get real user name/domain, courseid and symb
                   5770:     my $courseid;
1.359     albertel 5771:     my $publicuser;
1.427     www      5772:     if ($symbparm) {
                   5773: 	$symbparm=&get_symb_from_alias($symbparm);
                   5774:     }
1.218     albertel 5775:     if (!($uname && $udom)) {
1.790     albertel 5776:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5777:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5778:     } else {
1.620     albertel 5779: 	$courseid=$env{'request.course.id'};
1.218     albertel 5780:     }
1.48      www      5781:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5782:     my $rest;
1.320     albertel 5783:     if (defined($therest[0])) {
1.48      www      5784:        $rest=join('.',@therest);
                   5785:     } else {
                   5786:        $rest='';
                   5787:     }
1.320     albertel 5788: 
1.57      www      5789:     my $qualifierrest=$qualifier;
                   5790:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5791:     my $spacequalifierrest=$space;
                   5792:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5793:     if ($realm eq 'user') {
1.48      www      5794: # --------------------------------------------------------------- user.resource
                   5795: 	if ($space eq 'resource') {
1.651     albertel 5796: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5797: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5798: 		 &&
1.744     albertel 5799: 		 ($symbparm eq &symbread()) ) {	
                   5800: 		# if we are in the middle of processing the resource the
                   5801: 		# get the value we are planning on committing
                   5802:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5803:                     return $Apache::lonhomework::results{$qualifierrest};
                   5804:                 } else {
                   5805:                     return $Apache::lonhomework::history{$qualifierrest};
                   5806:                 }
1.335     albertel 5807: 	    } else {
1.359     albertel 5808: 		my %restored;
1.620     albertel 5809: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5810: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5811: 		} else {
                   5812: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5813: 		}
1.335     albertel 5814: 		return $restored{$qualifierrest};
                   5815: 	    }
1.48      www      5816: # ----------------------------------------------------------------- user.access
                   5817:         } elsif ($space eq 'access') {
1.218     albertel 5818: 	    # FIXME - not supporting calls for a specific user
1.48      www      5819:             return &allowed($qualifier,$rest);
                   5820: # ------------------------------------------ user.preferences, user.environment
                   5821:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5822: 	    if (($uname eq $env{'user.name'}) &&
                   5823: 		($udom eq $env{'user.domain'})) {
                   5824: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5825: 	    } else {
1.359     albertel 5826: 		my %returnhash;
                   5827: 		if (!$publicuser) {
                   5828: 		    %returnhash=&userenvironment($udom,$uname,
                   5829: 						 $qualifierrest);
                   5830: 		}
1.218     albertel 5831: 		return $returnhash{$qualifierrest};
                   5832: 	    }
1.48      www      5833: # ----------------------------------------------------------------- user.course
                   5834:         } elsif ($space eq 'course') {
1.218     albertel 5835: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5836:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5837: # ------------------------------------------------------------------- user.role
                   5838:         } elsif ($space eq 'role') {
1.218     albertel 5839: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5840:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5841:             if ($qualifier eq 'value') {
                   5842: 		return $role;
                   5843:             } elsif ($qualifier eq 'extent') {
                   5844:                 return $where;
                   5845:             }
                   5846: # ----------------------------------------------------------------- user.domain
                   5847:         } elsif ($space eq 'domain') {
1.218     albertel 5848:             return $udom;
1.48      www      5849: # ------------------------------------------------------------------- user.name
                   5850:         } elsif ($space eq 'name') {
1.218     albertel 5851:             return $uname;
1.48      www      5852: # ---------------------------------------------------- Any other user namespace
1.29      www      5853:         } else {
1.359     albertel 5854: 	    my %reply;
                   5855: 	    if (!$publicuser) {
                   5856: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5857: 	    }
                   5858: 	    return $reply{$qualifierrest};
1.48      www      5859:         }
1.236     www      5860:     } elsif ($realm eq 'query') {
                   5861: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5862:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5863: 						[$spacequalifierrest]);
1.620     albertel 5864: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5865:    } elsif ($realm eq 'request') {
1.48      www      5866: # ------------------------------------------------------------- request.browser
                   5867:         if ($space eq 'browser') {
1.430     www      5868: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5869: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5870: 		    return 1;
                   5871: 		} else {
                   5872: 		    return 0;
                   5873: 		}
                   5874: 	    } else {
1.620     albertel 5875: 		return $env{'browser.'.$qualifier};
1.430     www      5876: 	    }
1.57      www      5877: # ------------------------------------------------------------ request.filename
                   5878:         } else {
1.620     albertel 5879:             return $env{'request.'.$spacequalifierrest};
1.29      www      5880:         }
1.28      www      5881:     } elsif ($realm eq 'course') {
1.48      www      5882: # ---------------------------------------------------------- course.description
1.620     albertel 5883:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5884:     } elsif ($realm eq 'resource') {
1.165     www      5885: 
1.620     albertel 5886: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5887: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5888: 	}
1.693     albertel 5889: 
                   5890: 	if ($space eq 'title') {
                   5891: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5892: 	    return &gettitle($symbparm);
                   5893: 	}
                   5894: 	
                   5895: 	if ($space eq 'map') {
                   5896: 	    my ($map) = &decode_symb($symbparm);
                   5897: 	    return &symbread($map);
                   5898: 	}
                   5899: 
                   5900: 	my ($section, $group, @groups);
1.593     albertel 5901: 	my ($courselevelm,$courselevel);
1.539     albertel 5902: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5903: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5904: 
1.218     albertel 5905: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5906: 
1.60      www      5907: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5908: 	    my $symbp=$symbparm;
1.735     albertel 5909: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5910: 
                   5911: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5912: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5913: 
1.620     albertel 5914: 	    if (($env{'user.name'} eq $uname) &&
                   5915: 		($env{'user.domain'} eq $udom)) {
                   5916: 		$section=$env{'request.course.sec'};
1.733     raeburn  5917:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5918:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5919: 	    } else {
1.539     albertel 5920: 		if (! defined($usection)) {
1.551     albertel 5921: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5922: 		} else {
                   5923: 		    $section = $usection;
                   5924: 		}
1.733     raeburn  5925:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5926: 	    }
                   5927: 
                   5928: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5929: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5930: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5931: 
1.593     albertel 5932: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5933: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5934: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5935: 
1.60      www      5936: # ----------------------------------------------------------- first, check user
1.624     albertel 5937: 
                   5938: 	    my $userreply=&resdata($uname,$udom,'user',
                   5939: 				       ($courselevelr,$courselevelm,
                   5940: 					$courselevel));
                   5941: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5942: 
1.594     albertel 5943: # ------------------------------------------------ second, check some of course
1.684     raeburn  5944:             my $coursereply;
1.691     raeburn  5945:             if (@groups > 0) {
                   5946:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5947:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5948:                 if (defined($coursereply)) { return $coursereply; }
                   5949:             }
1.96      www      5950: 
1.684     raeburn  5951: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5952: 				     $env{'course.'.$courseid.'.domain'},
                   5953: 				     'course',
                   5954: 				     ($seclevelr,$seclevelm,$seclevel,
                   5955: 				      $courselevelr));
1.287     albertel 5956: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5957: 
1.60      www      5958: # ------------------------------------------------------ third, check map parms
1.218     albertel 5959: 	    my %parmhash=();
                   5960: 	    my $thisparm='';
                   5961: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5962: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5963: 		    &GDBM_READER(),0640)) {
1.218     albertel 5964: 		$thisparm=$parmhash{$symbparm};
                   5965: 		untie(%parmhash);
                   5966: 	    }
                   5967: 	    if ($thisparm) { return $thisparm; }
                   5968: 	}
1.594     albertel 5969: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5970: 
1.218     albertel 5971: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5972: 	my $filename;
                   5973: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5974: 	if ($symbparm) {
1.409     www      5975: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5976: 	} else {
1.620     albertel 5977: 	    $filename=$env{'request.filename'};
1.282     albertel 5978: 	}
                   5979: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5980: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5981: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5982: 	if (defined($metadata)) { return $metadata; }
1.142     www      5983: 
1.594     albertel 5984: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5985: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5986: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5987: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5988: 				     $env{'course.'.$courseid.'.domain'},
                   5989: 				     'course',
                   5990: 				     ($courselevelm,$courselevel));
1.593     albertel 5991: 	    if (defined($coursereply)) { return $coursereply; }
                   5992: 	}
1.145     www      5993: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5994: 	unless ($space eq '0') {
1.336     albertel 5995: 	    my @parts=split(/_/,$space);
                   5996: 	    my $id=pop(@parts);
                   5997: 	    my $part=join('_',@parts);
                   5998: 	    if ($part eq '') { $part='0'; }
                   5999: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6000: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6001: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6002: 	}
1.395     albertel 6003: 	if ($recurse) { return undef; }
                   6004: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6005: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6006: 
1.48      www      6007: # ---------------------------------------------------- Any other user namespace
                   6008:     } elsif ($realm eq 'environment') {
                   6009: # ----------------------------------------------------------------- environment
1.620     albertel 6010: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6011: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6012: 	} else {
1.770     albertel 6013: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6014: 		return '';
                   6015: 	    }
1.219     albertel 6016: 	    my %returnhash=&userenvironment($udom,$uname,
                   6017: 					    $spacequalifierrest);
                   6018: 	    return $returnhash{$spacequalifierrest};
                   6019: 	}
1.28      www      6020:     } elsif ($realm eq 'system') {
1.48      www      6021: # ----------------------------------------------------------------- system.time
                   6022: 	if ($space eq 'time') {
                   6023: 	    return time;
                   6024:         }
1.696     albertel 6025:     } elsif ($realm eq 'server') {
                   6026: # ----------------------------------------------------------------- system.time
                   6027: 	if ($space eq 'name') {
                   6028: 	    return $ENV{'SERVER_NAME'};
                   6029:         }
1.28      www      6030:     }
1.48      www      6031:     return '';
1.61      www      6032: }
                   6033: 
1.691     raeburn  6034: sub check_group_parms {
                   6035:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6036:     my @groupitems = ();
                   6037:     my $resultitem;
                   6038:     my @levels = ($symbparm,$mapparm,$what);
                   6039:     foreach my $group (@{$groups}) {
                   6040:         foreach my $level (@levels) {
                   6041:              my $item = $courseid.'.['.$group.'].'.$level;
                   6042:              push(@groupitems,$item);
                   6043:         }
                   6044:     }
                   6045:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6046:                             $env{'course.'.$courseid.'.domain'},
                   6047:                                      'course',@groupitems);
                   6048:     return $coursereply;
                   6049: }
                   6050: 
                   6051: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6052:     my ($courseid,@groups) = @_;
                   6053:     @groups = sort(@groups);
1.691     raeburn  6054:     return @groups;
                   6055: }
                   6056: 
1.395     albertel 6057: sub packages_tab_default {
                   6058:     my ($uri,$varname)=@_;
                   6059:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6060: 
                   6061:     my (@extension,@specifics,$do_default);
                   6062:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6063: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6064: 	if ($pack_type eq 'default') {
                   6065: 	    $do_default=1;
                   6066: 	} elsif ($pack_type eq 'extension') {
                   6067: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6068: 	} else {
                   6069: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6070: 	}
                   6071:     }
                   6072:     # first look for a package that matches the requested part id
                   6073:     foreach my $package (@specifics) {
                   6074: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6075: 	next if ($pack_part ne $part);
                   6076: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6077: 	    return $packagetab{"$pack_type&$name&default"};
                   6078: 	}
                   6079:     }
                   6080:     # look for any possible matching non extension_ package
                   6081:     foreach my $package (@specifics) {
                   6082: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6083: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6084: 	    return $packagetab{"$pack_type&$name&default"};
                   6085: 	}
1.585     albertel 6086: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6087: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6088: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6089: 	}
                   6090:     }
1.738     albertel 6091:     # look for any posible extension_ match
                   6092:     foreach my $package (@extension) {
                   6093: 	my ($package,$pack_type)=@{$package};
                   6094: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6095: 	    return $packagetab{"$pack_type&$name&default"};
                   6096: 	}
                   6097: 	if (defined($packagetab{$package."&$name&default"})) {
                   6098: 	    return $packagetab{$package."&$name&default"};
                   6099: 	}
                   6100:     }
                   6101:     # look for a global default setting
                   6102:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6103: 	return $packagetab{"default&$name&default"};
                   6104:     }
1.395     albertel 6105:     return undef;
                   6106: }
                   6107: 
1.334     albertel 6108: sub add_prefix_and_part {
                   6109:     my ($prefix,$part)=@_;
                   6110:     my $keyroot;
                   6111:     if (defined($prefix) && $prefix !~ /^__/) {
                   6112: 	# prefix that has a part already
                   6113: 	$keyroot=$prefix;
                   6114:     } elsif (defined($prefix)) {
                   6115: 	# prefix that is missing a part
                   6116: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6117:     } else {
                   6118: 	# no prefix at all
                   6119: 	if (defined($part)) { $keyroot='_'.$part; }
                   6120:     }
                   6121:     return $keyroot;
                   6122: }
                   6123: 
1.71      www      6124: # ---------------------------------------------------------------- Get metadata
                   6125: 
1.599     albertel 6126: my %metaentry;
1.71      www      6127: sub metadata {
1.176     www      6128:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6129:     $uri=&declutter($uri);
1.288     albertel 6130:     # if it is a non metadata possible uri return quickly
1.529     albertel 6131:     if (($uri eq '') || 
                   6132: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6133: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6134:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6135: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6136: 	return undef;
1.288     albertel 6137:     }
1.73      www      6138:     my $filename=$uri;
                   6139:     $uri=~s/\.meta$//;
1.172     www      6140: #
                   6141: # Is the metadata already cached?
1.177     www      6142: # Look at timestamp of caching
1.172     www      6143: # Everything is cached by the main uri, libraries are never directly cached
                   6144: #
1.428     albertel 6145:     if (!defined($liburi)) {
1.599     albertel 6146: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6147: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6148:     }
                   6149:     {
1.172     www      6150: #
                   6151: # Is this a recursive call for a library?
                   6152: #
1.599     albertel 6153: #	if (! exists($metacache{$uri})) {
                   6154: #	    $metacache{$uri}={};
                   6155: #	}
1.171     www      6156:         if ($liburi) {
                   6157: 	    $liburi=&declutter($liburi);
                   6158:             $filename=$liburi;
1.401     bowersj2 6159:         } else {
1.599     albertel 6160: 	    &devalidate_cache_new('meta',$uri);
                   6161: 	    undef(%metaentry);
1.401     bowersj2 6162: 	}
1.140     www      6163:         my %metathesekeys=();
1.73      www      6164:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6165: 	my $metastring;
1.768     albertel 6166: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6167: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6168: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6169: 	    $metastring=&getfile($file);
1.489     albertel 6170: 	}
1.208     albertel 6171:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6172:         my $token;
1.140     www      6173:         undef %metathesekeys;
1.71      www      6174:         while ($token=$parser->get_token) {
1.339     albertel 6175: 	    if ($token->[0] eq 'S') {
                   6176: 		if (defined($token->[2]->{'package'})) {
1.172     www      6177: #
                   6178: # This is a package - get package info
                   6179: #
1.339     albertel 6180: 		    my $package=$token->[2]->{'package'};
                   6181: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6182: 		    if (defined($token->[2]->{'id'})) { 
                   6183: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6184: 		    }
1.599     albertel 6185: 		    if ($metaentry{':packages'}) {
                   6186: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6187: 		    } else {
1.599     albertel 6188: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6189: 		    }
1.736     albertel 6190: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6191: 			my $part=$keyroot;
                   6192: 			$part=~s/^\_//;
1.736     albertel 6193: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6194: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6195: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6196: 			    # ignore package.tab specified default values
                   6197:                             # here &package_tab_default() will fetch those
                   6198: 			    if ($subp eq 'default') { next; }
1.736     albertel 6199: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6200: 			    my $unikey;
                   6201: 			    if ($pack =~ /_0$/) {
                   6202: 				$unikey='parameter_0_'.$name;
                   6203: 				$part=0;
                   6204: 			    } else {
                   6205: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6206: 			    }
1.339     albertel 6207: 			    if ($subp eq 'display') {
                   6208: 				$value.=' [Part: '.$part.']';
                   6209: 			    }
1.599     albertel 6210: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6211: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6212: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6213: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6214: 			    }
1.599     albertel 6215: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6216: 				$metaentry{':'.$unikey}=
                   6217: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6218: 			    }
1.339     albertel 6219: 			}
                   6220: 		    }
                   6221: 		} else {
1.172     www      6222: #
                   6223: # This is not a package - some other kind of start tag
1.339     albertel 6224: #
                   6225: 		    my $entry=$token->[1];
                   6226: 		    my $unikey;
                   6227: 		    if ($entry eq 'import') {
                   6228: 			$unikey='';
                   6229: 		    } else {
                   6230: 			$unikey=$entry;
                   6231: 		    }
                   6232: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6233: 
                   6234: 		    if (defined($token->[2]->{'id'})) { 
                   6235: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6236: 		    }
1.175     www      6237: 
1.339     albertel 6238: 		    if ($entry eq 'import') {
1.175     www      6239: #
                   6240: # Importing a library here
1.339     albertel 6241: #
                   6242: 			if ($depthcount<20) {
                   6243: 			    my $location=$parser->get_text('/import');
                   6244: 			    my $dir=$filename;
                   6245: 			    $dir=~s|[^/]*$||;
                   6246: 			    $location=&filelocation($dir,$location);
1.736     albertel 6247: 			    my $metadata = 
                   6248: 				&metadata($uri,'keys', $location,$unikey,
                   6249: 					  $depthcount+1);
                   6250: 			    foreach my $meta (split(',',$metadata)) {
                   6251: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6252: 				$metathesekeys{$meta}=1;
1.339     albertel 6253: 			    }
                   6254: 			}
                   6255: 		    } else { 
                   6256: 			
                   6257: 			if (defined($token->[2]->{'name'})) { 
                   6258: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6259: 			}
                   6260: 			$metathesekeys{$unikey}=1;
1.736     albertel 6261: 			foreach my $param (@{$token->[3]}) {
                   6262: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6263: 				$token->[2]->{$param};
1.339     albertel 6264: 			}
                   6265: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6266: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6267: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6268: 		 # only ws inside the tag, and not in default, so use default
                   6269: 		 # as value
1.599     albertel 6270: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6271: 			} else {
1.321     albertel 6272: 		  # either something interesting inside the tag or default
                   6273:                   # uninteresting
1.599     albertel 6274: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6275: 			}
1.172     www      6276: # end of not-a-package not-a-library import
1.339     albertel 6277: 		    }
1.172     www      6278: # end of not-a-package start tag
1.339     albertel 6279: 		}
1.172     www      6280: # the next is the end of "start tag"
1.339     albertel 6281: 	    }
                   6282: 	}
1.483     albertel 6283: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6284: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6285: 	    #no specific packages #how's our extension
                   6286: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6287: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6288: 					 \%metathesekeys);
                   6289: 	}
1.599     albertel 6290: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6291: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6292: 		#no specific packages well let's get default then
                   6293: 		if ($key!~/^default&/) { next; }
1.488     albertel 6294: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6295: 					     \%metathesekeys);
                   6296: 	    }
                   6297: 	}
1.338     www      6298: # are there custom rights to evaluate
1.599     albertel 6299: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6300: 
1.338     www      6301:     #
                   6302:     # Importing a rights file here
1.339     albertel 6303:     #
                   6304: 	    unless ($depthcount) {
1.599     albertel 6305: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6306: 		my $dir=$filename;
                   6307: 		$dir=~s|[^/]*$||;
                   6308: 		$location=&filelocation($dir,$location);
1.736     albertel 6309: 		my $rights_metadata =
                   6310: 		    &metadata($uri,'keys',$location,'_rights',
                   6311: 			      $depthcount+1);
                   6312: 		foreach my $rights (split(',',$rights_metadata)) {
                   6313: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6314: 		    $metathesekeys{$rights}=1;
1.339     albertel 6315: 		}
                   6316: 	    }
                   6317: 	}
1.737     albertel 6318: 	# uniqifiy package listing
                   6319: 	my %seen;
                   6320: 	my @uniq_packages =
                   6321: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6322: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6323: 
                   6324: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6325: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6326: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6327: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6328: # this is the end of "was not already recently cached
1.71      www      6329:     }
1.599     albertel 6330:     return $metaentry{':'.$what};
1.261     albertel 6331: }
                   6332: 
1.488     albertel 6333: sub metadata_create_package_def {
1.483     albertel 6334:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6335:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6336:     if ($subp eq 'default') { next; }
                   6337:     
1.599     albertel 6338:     if (defined($metaentry{':packages'})) {
                   6339: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6340:     } else {
1.599     albertel 6341: 	$metaentry{':packages'}=$package;
1.483     albertel 6342:     }
                   6343:     my $value=$packagetab{$key};
                   6344:     my $unikey;
                   6345:     $unikey='parameter_0_'.$name;
1.599     albertel 6346:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6347:     $$metathesekeys{$unikey}=1;
1.599     albertel 6348:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6349: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6350:     }
1.599     albertel 6351:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6352: 	$metaentry{':'.$unikey}=
                   6353: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6354:     }
                   6355: }
                   6356: 
1.261     albertel 6357: sub metadata_generate_part0 {
                   6358:     my ($metadata,$metacache,$uri) = @_;
                   6359:     my %allnames;
1.737     albertel 6360:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6361: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6362: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6363: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6364: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6365: 	    $allnames{$name}=$part;
                   6366: 	  }
                   6367: 	}
                   6368:     }
                   6369:     foreach my $name (keys(%allnames)) {
                   6370:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6371:       my $key=":parameter_0_$name";
1.261     albertel 6372:       $$metacache{"$key.part"}='0';
                   6373:       $$metacache{"$key.name"}=$name;
1.428     albertel 6374:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6375: 					   $allnames{$name}.'_'.$name.
                   6376: 					   '.type'};
1.428     albertel 6377:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6378: 			     '.display'};
1.644     www      6379:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6380:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6381:       $$metacache{"$key.display"}=$olddis;
                   6382:     }
1.71      www      6383: }
                   6384: 
1.764     albertel 6385: # ------------------------------------------------------ Devalidate title cache
                   6386: 
                   6387: sub devalidate_title_cache {
                   6388:     my ($url)=@_;
                   6389:     if (!$env{'request.course.id'}) { return; }
                   6390:     my $symb=&symbread($url);
                   6391:     if (!$symb) { return; }
                   6392:     my $key=$env{'request.course.id'}."\0".$symb;
                   6393:     &devalidate_cache_new('title',$key);
                   6394: }
                   6395: 
1.301     www      6396: # ------------------------------------------------- Get the title of a resource
                   6397: 
                   6398: sub gettitle {
                   6399:     my $urlsymb=shift;
                   6400:     my $symb=&symbread($urlsymb);
1.534     albertel 6401:     if ($symb) {
1.620     albertel 6402: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6403: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6404: 	if (defined($cached)) { 
                   6405: 	    return $result;
                   6406: 	}
1.534     albertel 6407: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6408: 	my $title='';
                   6409: 	my %bighash;
1.620     albertel 6410: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6411: 		&GDBM_READER(),0640)) {
                   6412: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6413: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6414: 	    untie %bighash;
                   6415: 	}
                   6416: 	$title=~s/\&colon\;/\:/gs;
                   6417: 	if ($title) {
1.599     albertel 6418: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6419: 	}
                   6420: 	$urlsymb=$url;
                   6421:     }
                   6422:     my $title=&metadata($urlsymb,'title');
                   6423:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6424:     return $title;
1.301     www      6425: }
1.613     albertel 6426: 
1.614     albertel 6427: sub get_slot {
                   6428:     my ($which,$cnum,$cdom)=@_;
                   6429:     if (!$cnum || !$cdom) {
1.790     albertel 6430: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6431: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6432: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6433:     }
1.703     albertel 6434:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6435:     my %slotinfo;
                   6436:     if (exists($remembered{$key})) {
                   6437: 	$slotinfo{$which} = $remembered{$key};
                   6438:     } else {
                   6439: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6440: 	&Apache::lonhomework::showhash(%slotinfo);
                   6441: 	my ($tmp)=keys(%slotinfo);
                   6442: 	if ($tmp=~/^error:/) { return (); }
                   6443: 	$remembered{$key} = $slotinfo{$which};
                   6444:     }
1.616     albertel 6445:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6446: 	return %{$slotinfo{$which}};
                   6447:     }
                   6448:     return $slotinfo{$which};
1.614     albertel 6449: }
1.31      www      6450: # ------------------------------------------------- Update symbolic store links
                   6451: 
                   6452: sub symblist {
                   6453:     my ($mapname,%newhash)=@_;
1.438     www      6454:     $mapname=&deversion(&declutter($mapname));
1.31      www      6455:     my %hash;
1.620     albertel 6456:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6457:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6458:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6459: 	    foreach my $url (keys %newhash) {
                   6460: 		next if ($url eq 'last_known'
                   6461: 			 && $env{'form.no_update_last_known'});
                   6462: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6463: 						    $newhash{$url}->[1],
                   6464: 						    $newhash{$url}->[0]);
1.191     harris41 6465:             }
1.31      www      6466:             if (untie(%hash)) {
                   6467: 		return 'ok';
                   6468:             }
                   6469:         }
                   6470:     }
                   6471:     return 'error';
1.212     www      6472: }
                   6473: 
                   6474: # --------------------------------------------------------------- Verify a symb
                   6475: 
                   6476: sub symbverify {
1.510     www      6477:     my ($symb,$thisurl)=@_;
                   6478:     my $thisfn=$thisurl;
1.439     www      6479:     $thisfn=&declutter($thisfn);
1.215     www      6480: # direct jump to resource in page or to a sequence - will construct own symbs
                   6481:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6482: # check URL part
1.409     www      6483:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6484: 
1.431     www      6485:     unless ($url eq $thisfn) { return 0; }
1.213     www      6486: 
1.216     www      6487:     $symb=&symbclean($symb);
1.510     www      6488:     $thisurl=&deversion($thisurl);
1.439     www      6489:     $thisfn=&deversion($thisfn);
1.213     www      6490: 
                   6491:     my %bighash;
                   6492:     my $okay=0;
1.431     www      6493: 
1.620     albertel 6494:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6495:                             &GDBM_READER(),0640)) {
1.510     www      6496:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6497:         unless ($ids) { 
1.510     www      6498:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6499:         }
                   6500:         if ($ids) {
                   6501: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6502: 	    foreach my $id (split(/\,/,$ids)) {
                   6503: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6504:                if (
                   6505:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6506:    eq $symb) { 
1.620     albertel 6507: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6508: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6509: 		       $okay=1; 
                   6510: 		   }
                   6511: 	       }
1.216     www      6512: 	   }
                   6513:         }
1.213     www      6514: 	untie(%bighash);
                   6515:     }
                   6516:     return $okay;
1.31      www      6517: }
                   6518: 
1.210     www      6519: # --------------------------------------------------------------- Clean-up symb
                   6520: 
                   6521: sub symbclean {
                   6522:     my $symb=shift;
1.568     albertel 6523:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6524: # remove version from map
                   6525:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6526: 
1.210     www      6527: # remove version from URL
                   6528:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6529: 
1.507     www      6530: # remove wrapper
                   6531: 
1.510     www      6532:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6533:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6534:     return $symb;
1.409     www      6535: }
                   6536: 
                   6537: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6538: 
                   6539: sub encode_symb {
                   6540:     my ($map,$resid,$url)=@_;
                   6541:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6542: }
1.409     www      6543: 
                   6544: sub decode_symb {
1.568     albertel 6545:     my $symb=shift;
                   6546:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6547:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6548:     return (&fixversion($map),$resid,&fixversion($url));
                   6549: }
                   6550: 
                   6551: sub fixversion {
                   6552:     my $fn=shift;
1.609     banghart 6553:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6554:     my %bighash;
                   6555:     my $uri=&clutter($fn);
1.620     albertel 6556:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6557: # is this cached?
1.599     albertel 6558:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6559:     if (defined($cached)) { return $result; }
                   6560: # unfortunately not cached, or expired
1.620     albertel 6561:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6562: 	    &GDBM_READER(),0640)) {
                   6563:  	if ($bighash{'version_'.$uri}) {
                   6564:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6565:  	    unless (($version eq 'mostrecent') || 
                   6566: 		    ($version==&getversion($uri))) {
1.440     www      6567:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6568:  	    }
                   6569:  	}
                   6570:  	untie %bighash;
1.413     www      6571:     }
1.599     albertel 6572:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6573: }
                   6574: 
                   6575: sub deversion {
                   6576:     my $url=shift;
                   6577:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6578:     return $url;
1.210     www      6579: }
                   6580: 
1.31      www      6581: # ------------------------------------------------------ Return symb list entry
                   6582: 
                   6583: sub symbread {
1.249     www      6584:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6585:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6586:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6587: # no filename provided? try from environment
1.44      www      6588:     unless ($thisfn) {
1.620     albertel 6589:         if ($env{'request.symb'}) {
                   6590: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6591: 	}
1.620     albertel 6592: 	$thisfn=$env{'request.filename'};
1.44      www      6593:     }
1.569     albertel 6594:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6595: # is that filename actually a symb? Verify, clean, and return
                   6596:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6597: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6598: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6599: 	}
1.242     www      6600:     }
1.44      www      6601:     $thisfn=declutter($thisfn);
1.31      www      6602:     my %hash;
1.37      www      6603:     my %bighash;
                   6604:     my $syval='';
1.620     albertel 6605:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6606:         my $targetfn = $thisfn;
1.609     banghart 6607:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6608:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6609:         }
1.687     albertel 6610: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6611: 	    $targetfn=$1;
                   6612: 	}
1.620     albertel 6613:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6614:                       &GDBM_READER(),0640)) {
1.481     raeburn  6615: 	    $syval=$hash{$targetfn};
1.37      www      6616:             untie(%hash);
                   6617:         }
                   6618: # ---------------------------------------------------------- There was an entry
                   6619:         if ($syval) {
1.601     albertel 6620: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6621: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6622: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6623: 		    #return $env{$cache_str}='';
1.601     albertel 6624: 		#}    
                   6625: 		#$syval.=$1;
                   6626: 	    #}
1.37      www      6627:         } else {
                   6628: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6629:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6630:                             &GDBM_READER(),0640)) {
1.37      www      6631: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6632:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6633:               unless ($ids) { 
                   6634:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6635:               }
                   6636:               unless ($ids) {
                   6637: # alias?
                   6638: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6639:               }
1.37      www      6640:               if ($ids) {
                   6641: # ------------------------------------------------------------------- Has ID(s)
                   6642:                  my @possibilities=split(/\,/,$ids);
1.39      www      6643:                  if ($#possibilities==0) {
                   6644: # ----------------------------------------------- There is only one possibility
1.37      www      6645: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6646: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6647: 						    $resid,$thisfn);
1.249     www      6648:                  } elsif (!$donotrecurse) {
1.39      www      6649: # ------------------------------------------ There is more than one possibility
                   6650:                      my $realpossible=0;
1.800     albertel 6651:                      foreach my $id (@possibilities) {
                   6652: 			 my $file=$bighash{'src_'.$id};
1.39      www      6653:                          if (&allowed('bre',$file)) {
1.800     albertel 6654:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6655:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6656: 				$realpossible++;
1.626     albertel 6657:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6658: 						    $resid,$thisfn);
1.39      www      6659:                             }
                   6660: 			 }
1.191     harris41 6661:                      }
1.39      www      6662: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6663:                  } else {
                   6664:                      $syval='';
1.37      www      6665:                  }
                   6666: 	      }
                   6667:               untie(%bighash)
1.481     raeburn  6668:            }
1.31      www      6669:         }
1.62      www      6670:         if ($syval) {
1.620     albertel 6671: 	    return $env{$cache_str}=$syval;
1.62      www      6672:         }
1.31      www      6673:     }
1.44      www      6674:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6675:     return $env{$cache_str}='';
1.31      www      6676: }
                   6677: 
                   6678: # ---------------------------------------------------------- Return random seed
                   6679: 
1.32      www      6680: sub numval {
                   6681:     my $txt=shift;
                   6682:     $txt=~tr/A-J/0-9/;
                   6683:     $txt=~tr/a-j/0-9/;
                   6684:     $txt=~tr/K-T/0-9/;
                   6685:     $txt=~tr/k-t/0-9/;
                   6686:     $txt=~tr/U-Z/0-5/;
                   6687:     $txt=~tr/u-z/0-5/;
                   6688:     $txt=~s/\D//g;
1.564     albertel 6689:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6690:     return int($txt);
1.368     albertel 6691: }
                   6692: 
1.484     albertel 6693: sub numval2 {
                   6694:     my $txt=shift;
                   6695:     $txt=~tr/A-J/0-9/;
                   6696:     $txt=~tr/a-j/0-9/;
                   6697:     $txt=~tr/K-T/0-9/;
                   6698:     $txt=~tr/k-t/0-9/;
                   6699:     $txt=~tr/U-Z/0-5/;
                   6700:     $txt=~tr/u-z/0-5/;
                   6701:     $txt=~s/\D//g;
                   6702:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6703:     my $total;
                   6704:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6705:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6706:     return int($total);
                   6707: }
                   6708: 
1.575     albertel 6709: sub numval3 {
                   6710:     use integer;
                   6711:     my $txt=shift;
                   6712:     $txt=~tr/A-J/0-9/;
                   6713:     $txt=~tr/a-j/0-9/;
                   6714:     $txt=~tr/K-T/0-9/;
                   6715:     $txt=~tr/k-t/0-9/;
                   6716:     $txt=~tr/U-Z/0-5/;
                   6717:     $txt=~tr/u-z/0-5/;
                   6718:     $txt=~s/\D//g;
                   6719:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6720:     my $total;
                   6721:     foreach my $val (@txts) { $total+=$val; }
                   6722:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6723:     return $total;
                   6724: }
                   6725: 
1.675     albertel 6726: sub digest {
                   6727:     my ($data)=@_;
                   6728:     my $digest=&Digest::MD5::md5($data);
                   6729:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6730:     my ($e,$f);
                   6731:     {
                   6732:         use integer;
                   6733:         $e=($a+$b);
                   6734:         $f=($c+$d);
                   6735:         if ($_64bit) {
                   6736:             $e=(($e<<32)>>32);
                   6737:             $f=(($f<<32)>>32);
                   6738:         }
                   6739:     }
                   6740:     if (wantarray) {
                   6741: 	return ($e,$f);
                   6742:     } else {
                   6743: 	my $g;
                   6744: 	{
                   6745: 	    use integer;
                   6746: 	    $g=($e+$f);
                   6747: 	    if ($_64bit) {
                   6748: 		$g=(($g<<32)>>32);
                   6749: 	    }
                   6750: 	}
                   6751: 	return $g;
                   6752:     }
                   6753: }
                   6754: 
1.368     albertel 6755: sub latest_rnd_algorithm_id {
1.675     albertel 6756:     return '64bit5';
1.366     albertel 6757: }
1.32      www      6758: 
1.503     albertel 6759: sub get_rand_alg {
                   6760:     my ($courseid)=@_;
1.790     albertel 6761:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6762:     if ($courseid) {
1.620     albertel 6763: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6764:     }
                   6765:     return &latest_rnd_algorithm_id();
                   6766: }
                   6767: 
1.562     albertel 6768: sub validCODE {
                   6769:     my ($CODE)=@_;
                   6770:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6771:     return 0;
                   6772: }
                   6773: 
1.491     albertel 6774: sub getCODE {
1.620     albertel 6775:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6776:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6777: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6778: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6779: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6780:     }
                   6781:     return undef;
                   6782: }
                   6783: 
1.31      www      6784: sub rndseed {
1.155     albertel 6785:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6786: 
1.790     albertel 6787:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6788:     if (!$symb) {
1.366     albertel 6789: 	unless ($symb=$wsymb) { return time; }
                   6790:     }
                   6791:     if (!$courseid) { $courseid=$wcourseid; }
                   6792:     if (!$domain) { $domain=$wdomain; }
                   6793:     if (!$username) { $username=$wusername }
1.503     albertel 6794:     my $which=&get_rand_alg();
1.803     albertel 6795: 
1.491     albertel 6796:     if (defined(&getCODE())) {
1.675     albertel 6797: 	if ($which eq '64bit5') {
                   6798: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6799: 	} elsif ($which eq '64bit4') {
1.575     albertel 6800: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6801: 	} else {
                   6802: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6803: 	}
1.675     albertel 6804:     } elsif ($which eq '64bit5') {
                   6805: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6806:     } elsif ($which eq '64bit4') {
                   6807: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6808:     } elsif ($which eq '64bit3') {
                   6809: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6810:     } elsif ($which eq '64bit2') {
                   6811: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6812:     } elsif ($which eq '64bit') {
                   6813: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6814:     }
                   6815:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6816: }
                   6817: 
                   6818: sub rndseed_32bit {
                   6819:     my ($symb,$courseid,$domain,$username)=@_;
                   6820:     {
                   6821: 	use integer;
                   6822: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6823: 	my $symbseed=numval($symb) << 22;
                   6824: 	my $namechck=unpack("%32C*",$username) << 17;
                   6825: 	my $nameseed=numval($username) << 12;
                   6826: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6827: 	my $courseseed=unpack("%32C*",$courseid);
                   6828: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6829: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6830: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6831: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6832: 	return $num;
                   6833:     }
                   6834: }
                   6835: 
                   6836: sub rndseed_64bit {
                   6837:     my ($symb,$courseid,$domain,$username)=@_;
                   6838:     {
                   6839: 	use integer;
                   6840: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6841: 	my $symbseed=numval($symb) << 10;
                   6842: 	my $namechck=unpack("%32S*",$username);
                   6843: 	
                   6844: 	my $nameseed=numval($username) << 21;
                   6845: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6846: 	my $courseseed=unpack("%32S*",$courseid);
                   6847: 	
                   6848: 	my $num1=$symbchck+$symbseed+$namechck;
                   6849: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6850: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6851: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6852: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6853: 	return "$num1,$num2";
1.155     albertel 6854:     }
1.366     albertel 6855: }
                   6856: 
1.443     albertel 6857: sub rndseed_64bit2 {
                   6858:     my ($symb,$courseid,$domain,$username)=@_;
                   6859:     {
                   6860: 	use integer;
                   6861: 	# strings need to be an even # of cahracters long, it it is odd the
                   6862:         # last characters gets thrown away
                   6863: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6864: 	my $symbseed=numval($symb) << 10;
                   6865: 	my $namechck=unpack("%32S*",$username.' ');
                   6866: 	
                   6867: 	my $nameseed=numval($username) << 21;
1.501     albertel 6868: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6869: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6870: 	
                   6871: 	my $num1=$symbchck+$symbseed+$namechck;
                   6872: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6873: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6874: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6875: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6876: 	return "$num1,$num2";
                   6877:     }
                   6878: }
                   6879: 
                   6880: sub rndseed_64bit3 {
                   6881:     my ($symb,$courseid,$domain,$username)=@_;
                   6882:     {
                   6883: 	use integer;
                   6884: 	# strings need to be an even # of cahracters long, it it is odd the
                   6885:         # last characters gets thrown away
                   6886: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6887: 	my $symbseed=numval2($symb) << 10;
                   6888: 	my $namechck=unpack("%32S*",$username.' ');
                   6889: 	
                   6890: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6891: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6892: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6893: 	
                   6894: 	my $num1=$symbchck+$symbseed+$namechck;
                   6895: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6896: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6897: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6898: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6899: 	
1.503     albertel 6900: 	return "$num1:$num2";
1.443     albertel 6901:     }
                   6902: }
                   6903: 
1.575     albertel 6904: sub rndseed_64bit4 {
                   6905:     my ($symb,$courseid,$domain,$username)=@_;
                   6906:     {
                   6907: 	use integer;
                   6908: 	# strings need to be an even # of cahracters long, it it is odd the
                   6909:         # last characters gets thrown away
                   6910: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6911: 	my $symbseed=numval3($symb) << 10;
                   6912: 	my $namechck=unpack("%32S*",$username.' ');
                   6913: 	
                   6914: 	my $nameseed=numval3($username) << 21;
                   6915: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6916: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6917: 	
                   6918: 	my $num1=$symbchck+$symbseed+$namechck;
                   6919: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6920: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6921: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6922: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6923: 	
                   6924: 	return "$num1:$num2";
                   6925:     }
                   6926: }
                   6927: 
1.675     albertel 6928: sub rndseed_64bit5 {
                   6929:     my ($symb,$courseid,$domain,$username)=@_;
                   6930:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6931:     return "$num1:$num2";
                   6932: }
                   6933: 
1.366     albertel 6934: sub rndseed_CODE_64bit {
                   6935:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6936:     {
1.366     albertel 6937: 	use integer;
1.443     albertel 6938: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6939: 	my $symbseed=numval2($symb);
1.491     albertel 6940: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6941: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6942: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6943: 	my $num1=$symbseed+$CODEchck;
                   6944: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6945: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6946: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6947: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6948: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6949: 	return "$num1:$num2";
1.366     albertel 6950:     }
                   6951: }
                   6952: 
1.575     albertel 6953: sub rndseed_CODE_64bit4 {
                   6954:     my ($symb,$courseid,$domain,$username)=@_;
                   6955:     {
                   6956: 	use integer;
                   6957: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6958: 	my $symbseed=numval3($symb);
                   6959: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6960: 	my $CODEseed=numval3(&getCODE());
                   6961: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6962: 	my $num1=$symbseed+$CODEchck;
                   6963: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6964: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6965: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6966: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6967: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6968: 	return "$num1:$num2";
                   6969:     }
                   6970: }
                   6971: 
1.675     albertel 6972: sub rndseed_CODE_64bit5 {
                   6973:     my ($symb,$courseid,$domain,$username)=@_;
                   6974:     my $code = &getCODE();
                   6975:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6976:     return "$num1:$num2";
                   6977: }
                   6978: 
1.366     albertel 6979: sub setup_random_from_rndseed {
                   6980:     my ($rndseed)=@_;
1.503     albertel 6981:     if ($rndseed =~/([,:])/) {
                   6982: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6983: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6984:     } else {
                   6985: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6986:     }
1.36      albertel 6987: }
                   6988: 
1.474     albertel 6989: sub latest_receipt_algorithm_id {
                   6990:     return 'receipt2';
                   6991: }
                   6992: 
1.480     www      6993: sub recunique {
                   6994:     my $fucourseid=shift;
                   6995:     my $unique;
1.620     albertel 6996:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6997: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6998:     } else {
                   6999: 	$unique=$perlvar{'lonReceipt'};
                   7000:     }
                   7001:     return unpack("%32C*",$unique);
                   7002: }
                   7003: 
                   7004: sub recprefix {
                   7005:     my $fucourseid=shift;
                   7006:     my $prefix;
1.620     albertel 7007:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7008: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7009:     } else {
                   7010: 	$prefix=$perlvar{'lonHostID'};
                   7011:     }
                   7012:     return unpack("%32C*",$prefix);
                   7013: }
                   7014: 
1.76      www      7015: sub ireceipt {
1.474     albertel 7016:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      7017:     my $cuname=unpack("%32C*",$funame);
                   7018:     my $cudom=unpack("%32C*",$fudom);
                   7019:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7020:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7021:     my $cunique=&recunique($fucourseid);
1.474     albertel 7022:     my $cpart=unpack("%32S*",$part);
1.480     www      7023:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 7024:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7025: 	$env{'request.state'} eq 'construct') {
1.790     albertel 7026: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7027: 			       
                   7028: 	$return.= ($cunique%$cuname+
                   7029: 		   $cunique%$cudom+
                   7030: 		   $cusymb%$cuname+
                   7031: 		   $cusymb%$cudom+
                   7032: 		   $cucourseid%$cuname+
                   7033: 		   $cucourseid%$cudom+
                   7034: 		   $cpart%$cuname+
                   7035: 		   $cpart%$cudom);
                   7036:     } else {
                   7037: 	$return.= ($cunique%$cuname+
                   7038: 		   $cunique%$cudom+
                   7039: 		   $cusymb%$cuname+
                   7040: 		   $cusymb%$cudom+
                   7041: 		   $cucourseid%$cuname+
                   7042: 		   $cucourseid%$cudom);
                   7043:     }
                   7044:     return $return;
1.76      www      7045: }
                   7046: 
                   7047: sub receipt {
1.474     albertel 7048:     my ($part)=@_;
1.790     albertel 7049:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7050:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7051: }
1.260     ng       7052: 
1.790     albertel 7053: sub whichuser {
                   7054:     my ($passedsymb)=@_;
                   7055:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7056:     if (defined($env{'form.grade_symb'})) {
                   7057: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7058: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7059: 	if (!$allowed &&
                   7060: 	    exists($env{'request.course.sec'}) &&
                   7061: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7062: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7063: 			      '/'.$env{'request.course.sec'});
                   7064: 	}
                   7065: 	if ($allowed) {
                   7066: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7067: 	    $courseid=$tmp_courseid;
                   7068: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7069: 	    ($name)=&get_env_multiple('form.grade_username');
                   7070: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7071: 	}
                   7072:     }
                   7073:     if (!$passedsymb) {
                   7074: 	$symb=&symbread();
                   7075:     } else {
                   7076: 	$symb=$passedsymb;
                   7077:     }
                   7078:     $courseid=$env{'request.course.id'};
                   7079:     $domain=$env{'user.domain'};
                   7080:     $name=$env{'user.name'};
                   7081:     if ($name eq 'public' && $domain eq 'public') {
                   7082: 	if (!defined($env{'form.username'})) {
                   7083: 	    $env{'form.username'}.=time.rand(10000000);
                   7084: 	}
                   7085: 	$name.=$env{'form.username'};
                   7086:     }
                   7087:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7088: 
                   7089: }
                   7090: 
1.36      albertel 7091: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7092: # returns either the contents of the file or 
                   7093: # -1 if the file doesn't exist
1.481     raeburn  7094: #
                   7095: # if the target is a file that was uploaded via DOCS, 
                   7096: # a check will be made to see if a current copy exists on the local server,
                   7097: # if it does this will be served, otherwise a copy will be retrieved from
                   7098: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7099: # the local server.   
1.472     albertel 7100: 
1.36      albertel 7101: sub getfile {
1.538     albertel 7102:     my ($file) = @_;
1.609     banghart 7103:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7104:     &repcopy($file);
                   7105:     return &readfile($file);
                   7106: }
                   7107: 
                   7108: sub repcopy_userfile {
                   7109:     my ($file)=@_;
1.609     banghart 7110:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7111:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7112:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7113: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7114:     my ($info,$rtncode);
                   7115:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7116:     if (-e "$file") {
                   7117: 	my @fileinfo = stat($file);
                   7118: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7119: 	if ($lwpresp ne 'ok') {
                   7120: 	    if ($rtncode eq '404') {
1.538     albertel 7121: 		unlink($file);
1.482     albertel 7122: 	    }
1.517     albertel 7123: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7124: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7125: 	    #my $response=$ua->request($request);
                   7126: 	    #if ($response->is_success()) {
                   7127: 	#	return $response->content;
                   7128: 	#    } else {
                   7129: 	#	return -1;
                   7130: 	#    }
1.482     albertel 7131: 	    return -1;
                   7132: 	}
                   7133: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7134: 	    return 'ok';
1.482     albertel 7135: 	}
                   7136: 	$info = '';
1.538     albertel 7137: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7138: 	if ($lwpresp ne 'ok') {
                   7139: 	    return -1;
                   7140: 	}
                   7141:     } else {
1.538     albertel 7142: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7143: 	if ($lwpresp ne 'ok') {
1.517     albertel 7144: 	    my $ua=new LWP::UserAgent;
1.538     albertel 7145: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7146: 	    my $response=$ua->request($request);
                   7147: 	    if ($response->is_success()) {
1.538     albertel 7148: 		$info=$response->content;
1.517     albertel 7149: 	    } else {
                   7150: 		return -1;
                   7151: 	    }
1.482     albertel 7152: 	}
                   7153: 	my @parts = ($cdom,$cnum); 
                   7154: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7155: 	    push @parts, split(/\//,$1);
1.518     albertel 7156: 	}
1.538     albertel 7157: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7158: 	foreach my $part (@parts) {
                   7159: 	    $path .= '/'.$part;
                   7160: 	    if (!-e $path) {
                   7161: 		mkdir($path,0770);
                   7162: 	    }
                   7163: 	}
                   7164:     }
1.538     albertel 7165:     open(FILE,">$file");
1.482     albertel 7166:     print FILE $info;
                   7167:     close(FILE);
1.607     raeburn  7168:     return 'ok';
1.481     raeburn  7169: }
                   7170: 
1.517     albertel 7171: sub tokenwrapper {
                   7172:     my $uri=shift;
1.552     albertel 7173:     $uri=~s|^http\://([^/]+)||;
                   7174:     $uri=~s|^/||;
1.620     albertel 7175:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7176:     my $token=$1;
1.552     albertel 7177:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7178:     if ($udom && $uname && $file) {
                   7179: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7180:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7181:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7182:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7183:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7184:     } else {
                   7185:         return '/adm/notfound.html';
                   7186:     }
                   7187: }
                   7188: 
1.481     raeburn  7189: sub getuploaded {
                   7190:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7191:     $uri=~s/^\///;
                   7192:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7193:     my $ua=new LWP::UserAgent;
                   7194:     my $request=new HTTP::Request($reqtype,$uri);
                   7195:     my $response=$ua->request($request);
                   7196:     $$rtncode = $response->code;
1.482     albertel 7197:     if (! $response->is_success()) {
                   7198: 	return 'failed';
                   7199:     }      
                   7200:     if ($reqtype eq 'HEAD') {
1.486     www      7201: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7202:     } elsif ($reqtype eq 'GET') {
                   7203: 	$$info = $response->content;
1.472     albertel 7204:     }
1.482     albertel 7205:     return 'ok';
1.36      albertel 7206: }
                   7207: 
1.481     raeburn  7208: sub readfile {
                   7209:     my $file = shift;
                   7210:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7211:     my $fh;
                   7212:     open($fh,"<$file");
                   7213:     my $a='';
1.800     albertel 7214:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7215:     return $a;
                   7216: }
                   7217: 
1.36      albertel 7218: sub filelocation {
1.590     banghart 7219:     my ($dir,$file) = @_;
                   7220:     my $location;
                   7221:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7222: 
                   7223:     if ($file =~ m-^/adm/-) {
                   7224: 	$file=~s-^/adm/wrapper/-/-;
                   7225: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7226:     }
1.590     banghart 7227:     if ($file=~m:^/~:) { # is a contruction space reference
                   7228:         $location = $file;
                   7229:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7230:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7231: 	# is a correct contruction space reference
                   7232:         $location = $file;
1.609     banghart 7233:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7234:         my ($udom,$uname,$filename)=
1.811     albertel 7235:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7236:         my $home=&homeserver($uname,$udom);
                   7237:         my $is_me=0;
                   7238:         my @ids=&current_machine_ids();
                   7239:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7240:         if ($is_me) {
1.740     www      7241:   	    $location=&propath($udom,$uname).
1.590     banghart 7242:   	      '/userfiles/'.$filename;
                   7243:         } else {
                   7244:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7245:   	      $udom.'/'.$uname.'/'.$filename;
                   7246:         }
                   7247:     } else {
                   7248:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7249:         $file=~s:^/res/:/:;
                   7250:         if ( !( $file =~ m:^/:) ) {
                   7251:             $location = $dir. '/'.$file;
                   7252:         } else {
                   7253:             $location = '/home/httpd/html/res'.$file;
                   7254:         }
1.59      albertel 7255:     }
1.590     banghart 7256:     $location=~s://+:/:g; # remove duplicate /
                   7257:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7258:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7259:     return $location;
1.46      www      7260: }
1.36      albertel 7261: 
1.46      www      7262: sub hreflocation {
                   7263:     my ($dir,$file)=@_;
1.460     albertel 7264:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7265: 	$file=filelocation($dir,$file);
1.700     albertel 7266:     } elsif ($file=~m-^/adm/-) {
                   7267: 	$file=~s-^/adm/wrapper/-/-;
                   7268: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7269:     }
                   7270:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7271: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7272:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7273: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7274:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7275: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7276: 	    -/uploaded/$1/$2/-x;
1.46      www      7277:     }
1.462     albertel 7278:     return $file;
1.465     albertel 7279: }
                   7280: 
                   7281: sub current_machine_domains {
                   7282:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7283:     my @domains;
                   7284:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7285: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7286: 	if ($hostname eq $name) {
                   7287: 	    push(@domains,$hostdom{$id});
                   7288: 	}
                   7289:     }
                   7290:     return @domains;
                   7291: }
                   7292: 
                   7293: sub current_machine_ids {
                   7294:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7295:     my @ids;
                   7296:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7297: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7298: 	if ($hostname eq $name) {
                   7299: 	    push(@ids,$id);
                   7300: 	}
                   7301:     }
                   7302:     return @ids;
1.31      www      7303: }
                   7304: 
                   7305: # ------------------------------------------------------------- Declutters URLs
                   7306: 
                   7307: sub declutter {
                   7308:     my $thisfn=shift;
1.569     albertel 7309:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7310:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7311:     $thisfn=~s/^\///;
1.697     albertel 7312:     $thisfn=~s|^adm/wrapper/||;
                   7313:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7314:     $thisfn=~s/^res\///;
1.235     www      7315:     $thisfn=~s/\?.+$//;
1.268     www      7316:     return $thisfn;
                   7317: }
                   7318: 
                   7319: # ------------------------------------------------------------- Clutter up URLs
                   7320: 
                   7321: sub clutter {
                   7322:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7323:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7324:        $thisfn='/res'.$thisfn; 
                   7325:     }
1.694     albertel 7326:     if ($thisfn !~m|/adm|) {
1.695     albertel 7327: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7328: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7329: 	} else {
                   7330: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7331: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7332: 	    if ($embstyle eq 'ssi'
                   7333: 		|| ($embstyle eq 'hdn')
                   7334: 		|| ($embstyle eq 'rat')
                   7335: 		|| ($embstyle eq 'prv')
                   7336: 		|| ($embstyle eq 'ign')) {
                   7337: 		#do nothing with these
                   7338: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7339: 		|| ($embstyle eq 'emb')
                   7340: 		|| ($embstyle eq 'wrp')) {
                   7341: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7342: 	    } elsif ($embstyle eq 'unk'
                   7343: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7344: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7345: 	    } else {
1.718     www      7346: #		&logthis("Got a blank emb style");
1.695     albertel 7347: 	    }
1.694     albertel 7348: 	}
                   7349:     }
1.31      www      7350:     return $thisfn;
1.12      www      7351: }
                   7352: 
1.787     albertel 7353: sub clutter_with_no_wrapper {
                   7354:     my $uri = &clutter(shift);
                   7355:     if ($uri =~ m-^/adm/-) {
                   7356: 	$uri =~ s-^/adm/wrapper/-/-;
                   7357: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7358:     }
                   7359:     return $uri;
                   7360: }
                   7361: 
1.557     albertel 7362: sub freeze_escape {
                   7363:     my ($value)=@_;
                   7364:     if (ref($value)) {
                   7365: 	$value=&nfreeze($value);
                   7366: 	return '__FROZEN__'.&escape($value);
                   7367:     }
                   7368:     return &escape($value);
                   7369: }
                   7370: 
1.11      www      7371: 
1.557     albertel 7372: sub thaw_unescape {
                   7373:     my ($value)=@_;
                   7374:     if ($value =~ /^__FROZEN__/) {
                   7375: 	substr($value,0,10,undef);
                   7376: 	$value=&unescape($value);
                   7377: 	return &thaw($value);
                   7378:     }
                   7379:     return &unescape($value);
                   7380: }
                   7381: 
1.436     albertel 7382: sub correct_line_ends {
                   7383:     my ($result)=@_;
                   7384:     $$result =~s/\r\n/\n/mg;
                   7385:     $$result =~s/\r/\n/mg;
1.415     albertel 7386: }
1.1       albertel 7387: # ================================================================ Main Program
                   7388: 
1.184     www      7389: sub goodbye {
1.204     albertel 7390:    &logthis("Starting Shut down");
1.443     albertel 7391: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7392:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7393: #converted
1.599     albertel 7394: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7395:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7396: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7397: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7398: #1.1 only
1.599     albertel 7399: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7400: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7401: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7402: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7403:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7404:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7405:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7406:    &flushcourselogs();
                   7407:    &logthis("Shutting down");
                   7408: }
                   7409: 
1.179     www      7410: BEGIN {
1.228     harris41 7411: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7412:     unless ($readit) {
1.217     harris41 7413: {
1.781     raeburn  7414:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7415:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7416: }
1.1       albertel 7417: 
1.327     albertel 7418: # ------------------------------------------------------------ Read domain file
                   7419: {
                   7420:     %domaindescription = ();
                   7421:     %domain_auth_def = ();
                   7422:     %domain_auth_arg_def = ();
1.448     albertel 7423:     my $fh;
                   7424:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7425: 	while (my $line = <$fh>) {
                   7426:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7427: #           next if /^\#/;
1.801     foxr     7428:            chomp $line;
1.403     www      7429:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7430: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7431: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7432:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7433: 	   $domaindescription{$domain}=$domain_description;
                   7434: 	   $domain_lang_def{$domain}=$def_lang;
                   7435: 	   $domain_city{$domain}=$city;
                   7436: 	   $domain_longi{$domain}=$longi;
                   7437: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7438:            $domain_primary{$domain}=$primary;
1.403     www      7439: 
1.448     albertel 7440:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7441: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7442: 	}
1.327     albertel 7443:     }
1.448     albertel 7444:     close ($fh);
1.327     albertel 7445: }
                   7446: 
                   7447: 
1.1       albertel 7448: # ------------------------------------------------------------- Read hosts file
                   7449: {
1.448     albertel 7450:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7451: 
                   7452:     while (my $configline=<$config>) {
1.303     matthew  7453:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7454:        chomp($configline);
1.595     albertel 7455:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7456:        $name=~s/\s//g;
1.595     albertel 7457:        if ($id && $domain && $role && $name) {
1.252     albertel 7458: 	 $hostname{$id}=$name;
                   7459: 	 $hostdom{$id}=$domain;
                   7460: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7461:        }
1.1       albertel 7462:     }
1.448     albertel 7463:     close($config);
1.619     albertel 7464:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7465:     #&get_iphost();
1.1       albertel 7466: }
                   7467: 
1.598     albertel 7468: sub get_iphost {
                   7469:     if (%iphost) { return %iphost; }
1.653     albertel 7470:     my %name_to_ip;
1.598     albertel 7471:     foreach my $id (keys(%hostname)) {
                   7472: 	my $name=$hostname{$id};
1.653     albertel 7473: 	my $ip;
                   7474: 	if (!exists($name_to_ip{$name})) {
                   7475: 	    $ip = gethostbyname($name);
                   7476: 	    if (!$ip || length($ip) ne 4) {
                   7477: 		&logthis("Skipping host $id name $name no IP found\n");
                   7478: 		next;
                   7479: 	    }
                   7480: 	    $ip=inet_ntoa($ip);
                   7481: 	    $name_to_ip{$name} = $ip;
                   7482: 	} else {
                   7483: 	    $ip = $name_to_ip{$name};
1.598     albertel 7484: 	}
                   7485: 	push(@{$iphost{$ip}},$id);
                   7486:     }
                   7487:     return %iphost;
                   7488: }
                   7489: 
1.1       albertel 7490: # ------------------------------------------------------ Read spare server file
                   7491: {
1.448     albertel 7492:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7493: 
                   7494:     while (my $configline=<$config>) {
                   7495:        chomp($configline);
1.284     matthew  7496:        if ($configline) {
1.784     albertel 7497: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7498: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7499: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7500:        }
                   7501:     }
1.448     albertel 7502:     close($config);
1.1       albertel 7503: }
1.11      www      7504: # ------------------------------------------------------------ Read permissions
                   7505: {
1.448     albertel 7506:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7507: 
                   7508:     while (my $configline=<$config>) {
1.448     albertel 7509: 	chomp($configline);
                   7510: 	if ($configline) {
                   7511: 	    my ($role,$perm)=split(/ /,$configline);
                   7512: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7513: 	}
1.11      www      7514:     }
1.448     albertel 7515:     close($config);
1.11      www      7516: }
                   7517: 
                   7518: # -------------------------------------------- Read plain texts for permissions
                   7519: {
1.448     albertel 7520:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7521: 
                   7522:     while (my $configline=<$config>) {
1.448     albertel 7523: 	chomp($configline);
                   7524: 	if ($configline) {
1.742     raeburn  7525: 	    my ($short,@plain)=split(/:/,$configline);
                   7526:             %{$prp{$short}} = ();
                   7527: 	    if (@plain > 0) {
                   7528:                 $prp{$short}{'std'} = $plain[0];
                   7529:                 for (my $i=1; $i<@plain; $i++) {
                   7530:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7531:                 }
                   7532:             }
1.448     albertel 7533: 	}
1.135     www      7534:     }
1.448     albertel 7535:     close($config);
1.135     www      7536: }
                   7537: 
                   7538: # ---------------------------------------------------------- Read package table
                   7539: {
1.448     albertel 7540:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7541: 
                   7542:     while (my $configline=<$config>) {
1.483     albertel 7543: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7544: 	chomp($configline);
                   7545: 	my ($short,$plain)=split(/:/,$configline);
                   7546: 	my ($pack,$name)=split(/\&/,$short);
                   7547: 	if ($plain ne '') {
                   7548: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7549: 	    $packagetab{$short}=$plain; 
                   7550: 	}
1.11      www      7551:     }
1.448     albertel 7552:     close($config);
1.329     matthew  7553: }
                   7554: 
                   7555: # ------------- set up temporary directory
                   7556: {
                   7557:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7558: 
1.11      www      7559: }
                   7560: 
1.794     albertel 7561: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7562: 				'compress_threshold'=> 20_000,
                   7563:  			        });
1.185     www      7564: 
1.281     www      7565: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7566: $dumpcount=0;
1.22      www      7567: 
1.163     harris41 7568: &logtouch();
1.672     albertel 7569: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7570: $readit=1;
1.564     albertel 7571:     {
                   7572: 	use integer;
                   7573: 	my $test=(2**32)+1;
1.568     albertel 7574: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7575: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7576:     }
1.195     www      7577: }
1.1       albertel 7578: }
1.179     www      7579: 
1.1       albertel 7580: 1;
1.191     harris41 7581: __END__
                   7582: 
1.243     albertel 7583: =pod
                   7584: 
1.191     harris41 7585: =head1 NAME
                   7586: 
1.243     albertel 7587: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7588: 
                   7589: =head1 SYNOPSIS
                   7590: 
1.243     albertel 7591: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7592: 
                   7593:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7594: 
1.243     albertel 7595: Common parameters:
                   7596: 
                   7597: =over 4
                   7598: 
                   7599: =item *
                   7600: 
                   7601: $uname : an internal username (if $cname expecting a course Id specifically)
                   7602: 
                   7603: =item *
                   7604: 
                   7605: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7606: 
                   7607: =item *
                   7608: 
                   7609: $symb : a resource instance identifier
                   7610: 
                   7611: =item *
                   7612: 
                   7613: $namespace : the name of a .db file that contains the data needed or
                   7614: being set.
                   7615: 
                   7616: =back
                   7617: 
1.394     bowersj2 7618: =head1 OVERVIEW
1.191     harris41 7619: 
1.394     bowersj2 7620: lonnet provides subroutines which interact with the
                   7621: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7622: about classes, users, and resources.
1.243     albertel 7623: 
                   7624: For many of these objects you can also use this to store data about
                   7625: them or modify them in various ways.
1.191     harris41 7626: 
1.394     bowersj2 7627: =head2 Symbs
1.191     harris41 7628: 
1.394     bowersj2 7629: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7630: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7631: map, the resource number of the resource in the map, and the URL of
                   7632: the resource itself. The latter is somewhat redundant, but might help
                   7633: if maps change.
                   7634: 
                   7635: An example is
                   7636: 
                   7637:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7638: 
                   7639: The respective map entry is
                   7640: 
                   7641:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7642:   title="Problem 2">
                   7643:  </resource>
                   7644: 
                   7645: Symbs are used by the random number generator, as well as to store and
                   7646: restore data specific to a certain instance of for example a problem.
                   7647: 
                   7648: =head2 Storing And Retrieving Data
                   7649: 
                   7650: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7651: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7652: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7653: is is the non-critical message twin of cstore. These functions are for
                   7654: handlers to store a perl hash to a user's permanent data space in an
                   7655: easy manner, and to retrieve it again on another call. It is expected
                   7656: that a handler would use this once at the beginning to retrieve data,
                   7657: and then again once at the end to send only the new data back.
                   7658: 
                   7659: The data is stored in the user's data directory on the user's
                   7660: homeserver under the ID of the course.
                   7661: 
                   7662: The hash that is returned by restore will have all of the previous
                   7663: value for all of the elements of the hash.
                   7664: 
                   7665: Example:
                   7666: 
                   7667:  #creating a hash
                   7668:  my %hash;
                   7669:  $hash{'foo'}='bar';
                   7670: 
                   7671:  #storing it
                   7672:  &Apache::lonnet::cstore(\%hash);
                   7673: 
                   7674:  #changing a value
                   7675:  $hash{'foo'}='notbar';
                   7676: 
                   7677:  #adding a new value
                   7678:  $hash{'bar'}='foo';
                   7679:  &Apache::lonnet::cstore(\%hash);
                   7680: 
                   7681:  #retrieving the hash
                   7682:  my %history=&Apache::lonnet::restore();
                   7683: 
                   7684:  #print the hash
                   7685:  foreach my $key (sort(keys(%history))) {
                   7686:    print("\%history{$key} = $history{$key}");
                   7687:  }
                   7688: 
                   7689: Will print out:
1.191     harris41 7690: 
1.394     bowersj2 7691:  %history{1:foo} = bar
                   7692:  %history{1:keys} = foo:timestamp
                   7693:  %history{1:timestamp} = 990455579
                   7694:  %history{2:bar} = foo
                   7695:  %history{2:foo} = notbar
                   7696:  %history{2:keys} = foo:bar:timestamp
                   7697:  %history{2:timestamp} = 990455580
                   7698:  %history{bar} = foo
                   7699:  %history{foo} = notbar
                   7700:  %history{timestamp} = 990455580
                   7701:  %history{version} = 2
                   7702: 
                   7703: Note that the special hash entries C<keys>, C<version> and
                   7704: C<timestamp> were added to the hash. C<version> will be equal to the
                   7705: total number of versions of the data that have been stored. The
                   7706: C<timestamp> attribute will be the UNIX time the hash was
                   7707: stored. C<keys> is available in every historical section to list which
                   7708: keys were added or changed at a specific historical revision of a
                   7709: hash.
                   7710: 
                   7711: B<Warning>: do not store the hash that restore returns directly. This
                   7712: will cause a mess since it will restore the historical keys as if the
                   7713: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7714: 
1.394     bowersj2 7715: Calling convention:
1.191     harris41 7716: 
1.394     bowersj2 7717:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7718:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7719: 
1.394     bowersj2 7720: For more detailed information, see lonnet specific documentation.
1.191     harris41 7721: 
1.394     bowersj2 7722: =head1 RETURN MESSAGES
1.191     harris41 7723: 
1.394     bowersj2 7724: =over 4
1.191     harris41 7725: 
1.394     bowersj2 7726: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7727: 
1.394     bowersj2 7728: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7729: when the connection is brought back up
1.191     harris41 7730: 
1.394     bowersj2 7731: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7732: for later delivery
1.191     harris41 7733: 
1.394     bowersj2 7734: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7735: 
1.394     bowersj2 7736: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7737: that was requested
1.191     harris41 7738: 
1.243     albertel 7739: =back
1.191     harris41 7740: 
1.243     albertel 7741: =head1 PUBLIC SUBROUTINES
1.191     harris41 7742: 
1.243     albertel 7743: =head2 Session Environment Functions
1.191     harris41 7744: 
1.243     albertel 7745: =over 4
1.191     harris41 7746: 
1.394     bowersj2 7747: =item * 
                   7748: X<appenv()>
                   7749: B<appenv(%hash)>: the value of %hash is written to
                   7750: the user envirnoment file, and will be restored for each access this
1.620     albertel 7751: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7752: process
1.191     harris41 7753: 
                   7754: =item *
1.394     bowersj2 7755: X<delenv()>
                   7756: B<delenv($regexp)>: removes all items from the session
                   7757: environment file that matches the regular expression in $regexp. The
1.620     albertel 7758: values are also delted from the current processes %env.
1.191     harris41 7759: 
1.795     albertel 7760: =item * get_env_multiple($name) 
                   7761: 
                   7762: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7763: values may be defined and end up as an array ref.
                   7764: 
                   7765: returns an array of values
                   7766: 
1.243     albertel 7767: =back
                   7768: 
                   7769: =head2 User Information
1.191     harris41 7770: 
1.243     albertel 7771: =over 4
1.191     harris41 7772: 
                   7773: =item *
1.394     bowersj2 7774: X<queryauthenticate()>
                   7775: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7776: authentication scheme
                   7777: 
                   7778: =item *
1.394     bowersj2 7779: X<authenticate()>
                   7780: B<authenticate($uname,$upass,$udom)>: try to
                   7781: authenticate user from domain's lib servers (first use the current
                   7782: one). C<$upass> should be the users password.
1.191     harris41 7783: 
                   7784: =item *
1.394     bowersj2 7785: X<homeserver()>
                   7786: B<homeserver($uname,$udom)>: find the server which has
                   7787: the user's directory and files (there must be only one), this caches
                   7788: the answer, and also caches if there is a borken connection.
1.191     harris41 7789: 
                   7790: =item *
1.394     bowersj2 7791: X<idget()>
                   7792: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7793: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7794: username, and only 1 username per ID in a specific domain) (returns
                   7795: hash: id=>name,id=>name)
1.191     harris41 7796: 
                   7797: =item *
1.394     bowersj2 7798: X<idrget()>
                   7799: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7800: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7801: 
                   7802: =item *
1.394     bowersj2 7803: X<idput()>
                   7804: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7805: 
                   7806: =item *
1.394     bowersj2 7807: X<rolesinit()>
                   7808: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7809: 
                   7810: =item *
1.551     albertel 7811: X<getsection()>
                   7812: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7813: course $cname, return section name/number or '' for "not in course"
                   7814: and '-1' for "no section"
                   7815: 
                   7816: =item *
1.394     bowersj2 7817: X<userenvironment()>
                   7818: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7819: passed in @what from the requested user's environment, returns a hash
                   7820: 
                   7821: =back
                   7822: 
                   7823: =head2 User Roles
                   7824: 
                   7825: =over 4
                   7826: 
                   7827: =item *
                   7828: 
1.810     raeburn  7829: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7830:  F: full access
                   7831:  U,I,K: authentication modes (cxx only)
                   7832:  '': forbidden
                   7833:  1: user needs to choose course
                   7834:  2: browse allowed
1.766     albertel 7835:  A: passphrase authentication needed
1.243     albertel 7836: 
                   7837: =item *
                   7838: 
                   7839: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7840: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7841: and course level
                   7842: 
                   7843: =item *
                   7844: 
                   7845: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7846: explanation of a user role term
                   7847: 
                   7848: =back
                   7849: 
                   7850: =head2 User Modification
                   7851: 
                   7852: =over 4
                   7853: 
                   7854: =item *
                   7855: 
                   7856: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7857: user for the level given by URL.  Optional start and end dates (leave empty
                   7858: string or zero for "no date")
1.191     harris41 7859: 
                   7860: =item *
                   7861: 
1.243     albertel 7862: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7863: change a users, password, possible return values are: ok,
                   7864: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7865: refused
1.191     harris41 7866: 
                   7867: =item *
                   7868: 
1.243     albertel 7869: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7870: 
                   7871: =item *
                   7872: 
1.243     albertel 7873: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7874: modify user
1.191     harris41 7875: 
                   7876: =item *
                   7877: 
1.286     matthew  7878: modifystudent
                   7879: 
                   7880: modify a students enrollment and identification information.
                   7881: The course id is resolved based on the current users environment.  
                   7882: This means the envoking user must be a course coordinator or otherwise
                   7883: associated with a course.
                   7884: 
1.297     matthew  7885: This call is essentially a wrapper for lonnet::modifyuser and
                   7886: lonnet::modify_student_enrollment
1.286     matthew  7887: 
                   7888: Inputs: 
                   7889: 
                   7890: =over 4
                   7891: 
                   7892: =item B<$udom> Students loncapa domain
                   7893: 
                   7894: =item B<$uname> Students loncapa login name
                   7895: 
                   7896: =item B<$uid> Students id/student number
                   7897: 
                   7898: =item B<$umode> Students authentication mode
                   7899: 
                   7900: =item B<$upass> Students password
                   7901: 
                   7902: =item B<$first> Students first name
                   7903: 
                   7904: =item B<$middle> Students middle name
                   7905: 
                   7906: =item B<$last> Students last name
                   7907: 
                   7908: =item B<$gene> Students generation
                   7909: 
                   7910: =item B<$usec> Students section in course
                   7911: 
                   7912: =item B<$end> Unix time of the roles expiration
                   7913: 
                   7914: =item B<$start> Unix time of the roles start date
                   7915: 
                   7916: =item B<$forceid> If defined, allow $uid to be changed
                   7917: 
                   7918: =item B<$desiredhome> server to use as home server for student
                   7919: 
                   7920: =back
1.297     matthew  7921: 
                   7922: =item *
                   7923: 
                   7924: modify_student_enrollment
                   7925: 
                   7926: Change a students enrollment status in a class.  The environment variable
                   7927: 'role.request.course' must be defined for this function to proceed.
                   7928: 
                   7929: Inputs:
                   7930: 
                   7931: =over 4
                   7932: 
                   7933: =item $udom, students domain
                   7934: 
                   7935: =item $uname, students name
                   7936: 
                   7937: =item $uid, students user id
                   7938: 
                   7939: =item $first, students first name
                   7940: 
                   7941: =item $middle
                   7942: 
                   7943: =item $last
                   7944: 
                   7945: =item $gene
                   7946: 
                   7947: =item $usec
                   7948: 
                   7949: =item $end
                   7950: 
                   7951: =item $start
                   7952: 
                   7953: =back
                   7954: 
1.191     harris41 7955: 
                   7956: =item *
                   7957: 
1.243     albertel 7958: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7959: custom role; give a custom role to a user for the level given by URL.  Specify
                   7960: name and domain of role author, and role name
1.191     harris41 7961: 
                   7962: =item *
                   7963: 
1.243     albertel 7964: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7965: 
                   7966: =item *
                   7967: 
1.243     albertel 7968: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7969: 
                   7970: =back
                   7971: 
                   7972: =head2 Course Infomation
                   7973: 
                   7974: =over 4
1.191     harris41 7975: 
                   7976: =item *
                   7977: 
1.631     albertel 7978: coursedescription($courseid) : returns a hash of information about the
                   7979: specified course id, including all environment settings for the
                   7980: course, the description of the course will be in the hash under the
                   7981: key 'description'
1.191     harris41 7982: 
                   7983: =item *
                   7984: 
1.624     albertel 7985: resdata($name,$domain,$type,@which) : request for current parameter
                   7986: setting for a specific $type, where $type is either 'course' or 'user',
                   7987: @what should be a list of parameters to ask about. This routine caches
                   7988: answers for 5 minutes.
1.243     albertel 7989: 
                   7990: =back
                   7991: 
                   7992: =head2 Course Modification
                   7993: 
                   7994: =over 4
1.191     harris41 7995: 
                   7996: =item *
                   7997: 
1.243     albertel 7998: writecoursepref($courseid,%prefs) : write preferences (environment
                   7999: database) for a course
1.191     harris41 8000: 
                   8001: =item *
                   8002: 
1.243     albertel 8003: createcourse($udom,$description,$url) : make/modify course
                   8004: 
                   8005: =back
                   8006: 
                   8007: =head2 Resource Subroutines
                   8008: 
                   8009: =over 4
1.191     harris41 8010: 
                   8011: =item *
                   8012: 
1.243     albertel 8013: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8014: 
                   8015: =item *
                   8016: 
1.243     albertel 8017: repcopy($filename) : subscribes to the requested file, and attempts to
                   8018: replicate from the owning library server, Might return
1.607     raeburn  8019: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8020: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8021: resource. Expects the local filesystem pathname
                   8022: (/home/httpd/html/res/....)
                   8023: 
                   8024: =back
                   8025: 
                   8026: =head2 Resource Information
                   8027: 
                   8028: =over 4
1.191     harris41 8029: 
                   8030: =item *
                   8031: 
1.243     albertel 8032: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8033: a vairety of different possible values, $varname should be a request
                   8034: string, and the other parameters can be used to specify who and what
                   8035: one is asking about.
                   8036: 
                   8037: Possible values for $varname are environment.lastname (or other item
                   8038: from the envirnment hash), user.name (or someother aspect about the
                   8039: user), resource.0.maxtries (or some other part and parameter of a
                   8040: resource)
1.204     albertel 8041: 
                   8042: =item *
                   8043: 
1.243     albertel 8044: directcondval($number) : get current value of a condition; reads from a state
                   8045: string
1.204     albertel 8046: 
                   8047: =item *
                   8048: 
1.243     albertel 8049: condval($condidx) : value of condition index based on state
1.204     albertel 8050: 
                   8051: =item *
                   8052: 
1.243     albertel 8053: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8054: resource's metadata, $what should be either a specific key, or either
                   8055: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8056: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8057: 
                   8058: this function automatically caches all requests
1.191     harris41 8059: 
                   8060: =item *
                   8061: 
1.243     albertel 8062: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8063: network of library servers; returns file handle of where SQL and regex results
                   8064: will be stored for query
1.191     harris41 8065: 
                   8066: =item *
                   8067: 
1.243     albertel 8068: symbread($filename) : return symbolic list entry (filename argument optional);
                   8069: returns the data handle
1.191     harris41 8070: 
                   8071: =item *
                   8072: 
1.243     albertel 8073: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8074: a possible symb for the URL in $thisfn, and if is an encryypted
                   8075: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8076: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8077: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8078: 
1.191     harris41 8079: 
                   8080: =item *
                   8081: 
1.243     albertel 8082: symbclean($symb) : removes versions numbers from a symb, returns the
                   8083: cleaned symb
1.191     harris41 8084: 
                   8085: =item *
                   8086: 
1.243     albertel 8087: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8088: course map, user must be in a course for it to work.
1.191     harris41 8089: 
                   8090: =item *
                   8091: 
1.243     albertel 8092: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8093: 
                   8094: =item *
                   8095: 
1.243     albertel 8096: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8097: a random seed, all arguments are optional, if they aren't sent it uses the
                   8098: environment to derive them. Note: if symb isn't sent and it can't get one
                   8099: from &symbread it will use the current time as its return value
1.191     harris41 8100: 
                   8101: =item *
                   8102: 
1.243     albertel 8103: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8104: unfakeable, receipt
1.191     harris41 8105: 
                   8106: =item *
                   8107: 
1.620     albertel 8108: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8109: 
                   8110: =item *
                   8111: 
1.243     albertel 8112: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8113: 
                   8114: =item *
                   8115: 
1.243     albertel 8116: 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 8117: 
                   8118: =item *
                   8119: 
1.243     albertel 8120: 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 8121: 
                   8122: =item *
                   8123: 
1.243     albertel 8124: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8125: 
                   8126: =item *
                   8127: 
1.243     albertel 8128: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8129: forcing spreadsheet to reevaluate the resource scores next time.
                   8130: 
                   8131: =back
                   8132: 
                   8133: =head2 Storing/Retreiving Data
                   8134: 
                   8135: =over 4
1.191     harris41 8136: 
                   8137: =item *
                   8138: 
1.243     albertel 8139: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8140: for this url; hashref needs to be given and should be a \%hashname; the
                   8141: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8142: be derived from the env
1.191     harris41 8143: 
                   8144: =item *
                   8145: 
1.243     albertel 8146: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8147: uses critical subroutine
1.191     harris41 8148: 
                   8149: =item *
                   8150: 
1.243     albertel 8151: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8152: all args are optional
1.191     harris41 8153: 
                   8154: =item *
                   8155: 
1.717     albertel 8156: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8157: dumps the complete (or key matching regexp) namespace into a hash
                   8158: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8159: normally &store()ed into
                   8160: 
                   8161: $range should be either an integer '100' (give me the first 100
                   8162:                                            matching records)
                   8163:               or be  two integers sperated by a - with no spaces
                   8164:                  '30-50' (give me the 30th through the 50th matching
                   8165:                           records)
                   8166: 
                   8167: 
                   8168: =item *
                   8169: 
                   8170: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8171: replaces a &store() version of data with a replacement set of data
                   8172: for a particular resource in a namespace passed in the $storehash hash 
                   8173: reference
                   8174: 
                   8175: =item *
                   8176: 
1.243     albertel 8177: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8178: works very similar to store/cstore, but all data is stored in a
                   8179: temporary location and can be reset using tmpreset, $storehash should
                   8180: be a hash reference, returns nothing on success
1.191     harris41 8181: 
                   8182: =item *
                   8183: 
1.243     albertel 8184: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8185: similar to restore, but all data is stored in a temporary location and
                   8186: can be reset using tmpreset. Returns a hash of values on success,
                   8187: error string otherwise.
1.191     harris41 8188: 
                   8189: =item *
                   8190: 
1.243     albertel 8191: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8192: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8193: 
                   8194: =item *
                   8195: 
1.243     albertel 8196: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8197: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8198: 
                   8199: =item *
                   8200: 
1.243     albertel 8201: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8202: namesp ($udom and $uname are optional)
1.191     harris41 8203: 
                   8204: =item *
                   8205: 
1.702     albertel 8206: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8207: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8208: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8209: 
1.702     albertel 8210: $range should be either an integer '100' (give me the first 100
                   8211:                                            matching records)
                   8212:               or be  two integers sperated by a - with no spaces
                   8213:                  '30-50' (give me the 30th through the 50th matching
                   8214:                           records)
1.449     matthew  8215: =item *
                   8216: 
                   8217: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8218: $store can be a scalar, an array reference, or if the amount to be 
                   8219: incremented is > 1, a hash reference.
                   8220: 
                   8221: ($udom and $uname are optional)
1.191     harris41 8222: 
                   8223: =item *
                   8224: 
1.243     albertel 8225: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8226: ($udom and $uname are optional)
1.191     harris41 8227: 
                   8228: =item *
                   8229: 
1.243     albertel 8230: cput($namespace,$storehash,$udom,$uname) : critical put
                   8231: ($udom and $uname are optional)
1.191     harris41 8232: 
                   8233: =item *
                   8234: 
1.748     albertel 8235: newput($namespace,$storehash,$udom,$uname) :
                   8236: 
                   8237: Attempts to store the items in the $storehash, but only if they don't
                   8238: currently exist, if this succeeds you can be certain that you have 
                   8239: successfully created a new key value pair in the $namespace db.
                   8240: 
                   8241: 
                   8242: Args:
                   8243:  $namespace: name of database to store values to
                   8244:  $storehash: hashref to store to the db
                   8245:  $udom: (optional) domain of user containing the db
                   8246:  $uname: (optional) name of user caontaining the db
                   8247: 
                   8248: Returns:
                   8249:  'ok' -> succeeded in storing all keys of $storehash
                   8250:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8251:                         least <key> already existed in the db (other
                   8252:                         requested keys may also already exist)
                   8253:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8254:  'con_lost' -> unable to contact request server
                   8255:  'refused' -> action was not allowed by remote machine
                   8256: 
                   8257: 
                   8258: =item *
                   8259: 
1.243     albertel 8260: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8261: reference filled in from namesp (encrypts the return communication)
                   8262: ($udom and $uname are optional)
1.191     harris41 8263: 
                   8264: =item *
                   8265: 
1.243     albertel 8266: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8267: critical subroutine
                   8268: 
1.806     raeburn  8269: =item *
                   8270: 
                   8271: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8272: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8273: 
                   8274: =item *
                   8275: 
                   8276: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8277: 
1.243     albertel 8278: =back
                   8279: 
                   8280: =head2 Network Status Functions
                   8281: 
                   8282: =over 4
1.191     harris41 8283: 
                   8284: =item *
                   8285: 
                   8286: dirlist($uri) : return directory list based on URI
                   8287: 
                   8288: =item *
                   8289: 
1.243     albertel 8290: spareserver() : find server with least workload from spare.tab
                   8291: 
                   8292: =back
                   8293: 
                   8294: =head2 Apache Request
                   8295: 
                   8296: =over 4
1.191     harris41 8297: 
                   8298: =item *
                   8299: 
1.243     albertel 8300: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8301: localhost, posts hash
                   8302: 
                   8303: =back
                   8304: 
                   8305: =head2 Data to String to Data
                   8306: 
                   8307: =over 4
1.191     harris41 8308: 
                   8309: =item *
                   8310: 
1.243     albertel 8311: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8312: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8313: 
                   8314: =item *
                   8315: 
1.243     albertel 8316: hashref2str($hashref) : convert a hashref into a string complete with
                   8317: escaping and '=' and '&' separators, supports elements that are
                   8318: arrayrefs and hashrefs
1.191     harris41 8319: 
                   8320: =item *
                   8321: 
1.243     albertel 8322: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8323: with escaping and '&' separators, supports elements that are arrayrefs
                   8324: and hashrefs
1.191     harris41 8325: 
                   8326: =item *
                   8327: 
1.243     albertel 8328: str2hash($string) : convert string to hash using unescaping and
                   8329: splitting on '=' and '&', supports elements that are arrayrefs and
                   8330: hashrefs
1.191     harris41 8331: 
                   8332: =item *
                   8333: 
1.243     albertel 8334: str2array($string) : convert string to hash using unescaping and
                   8335: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8336: 
                   8337: =back
                   8338: 
                   8339: =head2 Logging Routines
                   8340: 
                   8341: =over 4
                   8342: 
                   8343: These routines allow one to make log messages in the lonnet.log and
                   8344: lonnet.perm logfiles.
1.191     harris41 8345: 
                   8346: =item *
                   8347: 
1.243     albertel 8348: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8349: 
                   8350: =item *
                   8351: 
1.243     albertel 8352: logthis() : append message to the normal lonnet.log file, it gets
                   8353: preiodically rolled over and deleted.
1.191     harris41 8354: 
                   8355: =item *
                   8356: 
1.243     albertel 8357: logperm() : append a permanent message to lonnet.perm.log, this log
                   8358: file never gets deleted by any automated portion of the system, only
                   8359: messages of critical importance should go in here.
                   8360: 
                   8361: =back
                   8362: 
                   8363: =head2 General File Helper Routines
                   8364: 
                   8365: =over 4
1.191     harris41 8366: 
                   8367: =item *
                   8368: 
1.481     raeburn  8369: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8370: (a) files in /uploaded
                   8371:   (i) If a local copy of the file exists - 
                   8372:       compares modification date of local copy with last-modified date for 
                   8373:       definitive version stored on home server for course. If local copy is 
                   8374:       stale, requests a new version from the home server and stores it. 
                   8375:       If the original has been removed from the home server, then local copy 
                   8376:       is unlinked.
                   8377:   (ii) If local copy does not exist -
                   8378:       requests the file from the home server and stores it. 
                   8379:   
                   8380:   If $caller is 'uploadrep':  
                   8381:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8382:     for request for files originally uploaded via DOCS. 
                   8383:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8384:   
                   8385:   Otherwise:
                   8386:      This indicates a call from the content generation phase of the request.
                   8387:      -  returns the entire contents of the file or -1.
                   8388:      
                   8389: (b) files in /res
                   8390:    - returns the entire contents of a file or -1; 
                   8391:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8392: 
1.712     albertel 8393: 
                   8394: =item *
                   8395: 
                   8396: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8397:                   reference
                   8398: 
                   8399: returns either a stat() list of data about the file or an empty list
                   8400: if the file doesn't exist or couldn't find out about it (connection
                   8401: problems or user unknown)
                   8402: 
1.191     harris41 8403: =item *
                   8404: 
1.243     albertel 8405: filelocation($dir,$file) : returns file system location of a file
                   8406: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8407: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8408: and a file of ../bob will become /a/bob)
1.191     harris41 8409: 
                   8410: =item *
                   8411: 
                   8412: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8413: filelocation except for hrefs
                   8414: 
                   8415: =item *
                   8416: 
                   8417: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8418: 
1.243     albertel 8419: =back
                   8420: 
1.608     albertel 8421: =head2 Usererfile file routines (/uploaded*)
                   8422: 
                   8423: =over 4
                   8424: 
                   8425: =item *
                   8426: 
                   8427: userfileupload(): main rotine for putting a file in a user or course's
                   8428:                   filespace, arguments are,
                   8429: 
1.620     albertel 8430:  formname - required - this is the name of the element in $env where the
1.608     albertel 8431:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8432:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8433:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8434:  coursedoc - if true, store the file in the course of the active role
                   8435:              of the current user
                   8436:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8437:          if undefined, it will be placed in "unknown"
                   8438: 
                   8439:  (This routine calls clean_filename() to remove any dangerous
                   8440:  characters from the filename, and then calls finuserfileupload() to
                   8441:  complete the transaction)
                   8442: 
                   8443:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8444:  and /adm/notfound.html if unsuccessful
                   8445: 
                   8446: =item *
                   8447: 
                   8448: clean_filename(): routine for cleaing a filename up for storage in
                   8449:                  userfile space, argument is:
                   8450: 
                   8451:  filename - proposed filename
                   8452: 
                   8453: returns: the new clean filename
                   8454: 
                   8455: =item *
                   8456: 
                   8457: finishuserfileupload(): routine that creaes and sends the file to
                   8458: userspace, probably shouldn't be called directly
                   8459: 
                   8460:   docuname: username or courseid of destination for the file
                   8461:   docudom: domain of user/course of destination for the file
                   8462:   formname: same as for userfileupload()
                   8463:   fname: filename (inculding subdirectories) for the file
                   8464: 
                   8465:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8466:  and /adm/notfound.html if unsuccessful
                   8467: 
                   8468: =item *
                   8469: 
                   8470: renameuserfile(): renames an existing userfile to a new name
                   8471: 
                   8472:   Args:
                   8473:    docuname: username or courseid of destination for the file
                   8474:    docudom: domain of user/course of destination for the file
                   8475:    old: current file name (including any subdirs under userfiles)
                   8476:    new: desired file name (including any subdirs under userfiles)
                   8477: 
                   8478: =item *
                   8479: 
                   8480: mkdiruserfile(): creates a directory is a userfiles dir
                   8481: 
                   8482:   Args:
                   8483:    docuname: username or courseid of destination for the file
                   8484:    docudom: domain of user/course of destination for the file
                   8485:    dir: dir to create (including any subdirs under userfiles)
                   8486: 
                   8487: =item *
                   8488: 
                   8489: removeuserfile(): removes a file that exists in userfiles
                   8490: 
                   8491:   Args:
                   8492:    docuname: username or courseid of destination for the file
                   8493:    docudom: domain of user/course of destination for the file
                   8494:    fname: filname to delete (including any subdirs under userfiles)
                   8495: 
                   8496: =item *
                   8497: 
                   8498: removeuploadedurl(): convience function for removeuserfile()
                   8499: 
                   8500:   Args:
                   8501:    url:  a full /uploaded/... url to delete
                   8502: 
1.747     albertel 8503: =item * 
                   8504: 
                   8505: get_portfile_permissions():
                   8506:   Args:
                   8507:     domain: domain of user or course contain the portfolio files
                   8508:     user: name of user or num of course contain the portfolio files
                   8509:   Returns:
                   8510:     hashref of a dump of the proper file_permissions.db
                   8511:    
                   8512: 
                   8513: =item * 
                   8514: 
                   8515: get_access_controls():
                   8516: 
                   8517: Args:
                   8518:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8519:   group: (optional) the group you want the files associated with
                   8520:   file: (optional) the file you want access info on
                   8521: 
                   8522: Returns:
1.749     raeburn  8523:     a hash (keys are file names) of hashes containing
                   8524:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8525:         values are XML containing access control settings (see below) 
1.747     albertel 8526: 
                   8527: Internal notes:
                   8528: 
1.749     raeburn  8529:  access controls are stored in file_permissions.db as key=value pairs.
                   8530:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8531:         where scope -> public,guest,course,group,domains or users.
                   8532:               end -> UNIX time for end of access (0 -> no end date)
                   8533:               start -> UNIX time for start of access
                   8534: 
                   8535:     value -> XML description of access control
                   8536:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8537:             <start></start>
                   8538:             <end></end>
                   8539: 
                   8540:             <password></password>  for scope type = guest
                   8541: 
                   8542:             <domain></domain>     for scope type = course or group
                   8543:             <number></number>
                   8544:             <roles id="">
                   8545:              <role></role>
                   8546:              <access></access>
                   8547:              <section></section>
                   8548:              <group></group>
                   8549:             </roles>
                   8550: 
                   8551:             <dom></dom>         for scope type = domains
                   8552: 
                   8553:             <users>             for scope type = users
                   8554:              <user>
                   8555:               <uname></uname>
                   8556:               <udom></udom>
                   8557:              </user>
                   8558:             </users>
                   8559:            </scope> 
                   8560:               
                   8561:  Access data is also aggregated for each file in an additional key=value pair:
                   8562:  key -> path to file/file_name\0accesscontrol 
                   8563:  value -> reference to hash
                   8564:           hash contains key = value pairs
                   8565:           where key = uniqueID:scope_end_start
                   8566:                 value = UNIX time record was last updated
                   8567: 
                   8568:           Used to improve speed of look-ups of access controls for each file.  
                   8569:  
                   8570:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8571: 
                   8572: modify_access_controls():
                   8573: 
                   8574: Modifies access controls for a portfolio file
                   8575: Args
                   8576: 1. file name
                   8577: 2. reference to hash of required changes,
                   8578: 3. domain
                   8579: 4. username
                   8580:   where domain,username are the domain of the portfolio owner 
                   8581:   (either a user or a course) 
                   8582: 
                   8583: Returns:
                   8584: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8585: 2. result of deletions ('ok' or 'error', with error message).
                   8586: 3. reference to hash of any new or updated access controls.
                   8587: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8588:    key = integer (inbound ID)
                   8589:    value = uniqueID  
1.747     albertel 8590: 
1.608     albertel 8591: =back
                   8592: 
1.243     albertel 8593: =head2 HTTP Helper Routines
                   8594: 
                   8595: =over 4
                   8596: 
1.191     harris41 8597: =item *
                   8598: 
                   8599: escape() : unpack non-word characters into CGI-compatible hex codes
                   8600: 
                   8601: =item *
                   8602: 
                   8603: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8604: 
1.243     albertel 8605: =back
                   8606: 
                   8607: =head1 PRIVATE SUBROUTINES
                   8608: 
                   8609: =head2 Underlying communication routines (Shouldn't call)
                   8610: 
                   8611: =over 4
                   8612: 
                   8613: =item *
                   8614: 
                   8615: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8616: 
                   8617: =item *
                   8618: 
                   8619: reply() : uses subreply to send a message to remote machine, logs all failures
                   8620: 
                   8621: =item *
                   8622: 
                   8623: critical() : passes a critical message to another server; if cannot
                   8624: get through then place message in connection buffer directory and
                   8625: returns con_delayed, if incapable of saving message, returns
                   8626: con_failed
                   8627: 
                   8628: =item *
                   8629: 
                   8630: reconlonc() : tries to reconnect lonc client processes.
                   8631: 
                   8632: =back
                   8633: 
                   8634: =head2 Resource Access Logging
                   8635: 
                   8636: =over 4
                   8637: 
                   8638: =item *
                   8639: 
                   8640: flushcourselogs() : flush (save) buffer logs and access logs
                   8641: 
                   8642: =item *
                   8643: 
                   8644: courselog($what) : save message for course in hash
                   8645: 
                   8646: =item *
                   8647: 
                   8648: courseacclog($what) : save message for course using &courselog().  Perform
                   8649: special processing for specific resource types (problems, exams, quizzes, etc).
                   8650: 
1.191     harris41 8651: =item *
                   8652: 
                   8653: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8654: as a PerlChildExitHandler
1.243     albertel 8655: 
                   8656: =back
                   8657: 
                   8658: =head2 Other
                   8659: 
                   8660: =over 4
                   8661: 
                   8662: =item *
                   8663: 
                   8664: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8665: 
                   8666: =back
                   8667: 
                   8668: =cut

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