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

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

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