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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.824.2.3! albertel    4: # $Id: lonnet.pm,v 1.824.2.2 2007/01/25 21:45:44 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.807     albertel   56: use LONCAPA qw(:DEFAULT :match);
1.740     www        57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.783     albertel  295: sub convert_and_load_session_env {
                    296:     my ($lonidsdir,$handle)=@_;
                    297:     my @profile;
                    298:     {
                    299: 	open(my $idf,"$lonidsdir/$handle.id");
                    300: 	flock($idf,LOCK_SH);
                    301: 	@profile=<$idf>;
                    302: 	close($idf);
                    303:     }
                    304:     my %temp_env;
                    305:     foreach my $line (@profile) {
1.786     albertel  306: 	if ($line !~ m/=/) {
                    307: 	    return 0;
                    308: 	}
1.783     albertel  309: 	chomp($line);
                    310: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    311: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    312:     }
                    313:     unlink("$lonidsdir/$handle.id");
                    314:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    315: 	    0640)) {
                    316: 	%disk_env = %temp_env;
                    317: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    318: 	untie(%disk_env);
                    319:     }
1.786     albertel  320:     return 1;
1.783     albertel  321: }
                    322: 
1.374     www       323: # ------------------------------------------- Transfer profile into environment
1.780     albertel  324: my $env_loaded;
                    325: sub transfer_profile_to_env {
1.788     albertel  326:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    327:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       328: 
1.720     albertel  329:     if (!defined($lonidsdir)) {
                    330: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    331:     }
                    332:     if (!defined($handle)) {
                    333:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    334:     }
                    335: 
1.786     albertel  336:     my $convert;
                    337:     {
                    338:     	open(my $idf,"$lonidsdir/$handle.id");
                    339: 	flock($idf,LOCK_SH);
                    340: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    341: 		&GDBM_READER(),0640)) {
                    342: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    343: 	    untie(%disk_env);
                    344: 	} else {
                    345: 	    $convert = 1;
                    346: 	}
                    347:     }
                    348:     if ($convert) {
                    349: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    350: 	    &logthis("Failed to load session, or convert session.");
                    351: 	}
1.374     www       352:     }
1.783     albertel  353: 
1.786     albertel  354:     my %remove;
1.783     albertel  355:     while ( my $envname = each(%env) ) {
1.433     matthew   356:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    357:             if ($time < time-300) {
1.783     albertel  358:                 $remove{$key}++;
1.433     matthew   359:             }
                    360:         }
                    361:     }
1.783     albertel  362: 
1.619     albertel  363:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  364:     $env_loaded=1;
1.783     albertel  365:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   366:         &delenv($expired_key);
1.374     www       367:     }
1.1       albertel  368: }
                    369: 
1.824.2.1  albertel  370: sub timed_flock {
                    371:     my ($file,$lock_type) = @_;
                    372:     my $failed=0;
                    373:     eval {
                    374: 	local $SIG{__DIE__}='DEFAULT';
                    375: 	local $SIG{ALRM}=sub {
                    376: 	    $failed=1;
                    377: 	    die("failed lock");
                    378: 	};
                    379: 	alarm(13);
                    380: 	flock($file,$lock_type);
                    381: 	alarm(0);
                    382:     };
                    383:     if ($failed) {
                    384: 	return undef;
                    385:     } else {
                    386: 	return 1;
                    387:     }
                    388: }
                    389: 
1.5       www       390: # ---------------------------------------------------------- Append Environment
                    391: 
                    392: sub appenv {
1.6       www       393:     my %newenv=@_;
1.692     albertel  394:     foreach my $key (keys(%newenv)) {
                    395: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  396:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  397:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       398:                 .'</font>');
1.692     albertel  399: 	    delete($newenv{$key});
1.35      www       400:         } else {
1.692     albertel  401:             $env{$key}=$newenv{$key};
1.35      www       402:         }
1.191     harris41  403:     }
1.824.2.1  albertel  404:     open(my $env_file,$env{'user.environment'});
                    405:     if (&timed_flock($env_file,LOCK_EX)
                    406: 	&&
                    407: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    408: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  409: 	while (my ($key,$value) = each(%newenv)) {
                    410: 	    $disk_env{$key} = $value;
1.448     albertel  411: 	}
1.783     albertel  412: 	untie(%disk_env);
1.56      www       413:     }
                    414:     return 'ok';
                    415: }
                    416: # ----------------------------------------------------- Delete from Environment
                    417: 
                    418: sub delenv {
                    419:     my $delthis=shift;
                    420:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  421:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       422:                 "Attempt to delete from environment ".$delthis);
                    423:         return 'error';
                    424:     }
1.824.2.1  albertel  425:     open(my $env_file,$env{'user.environment'});
                    426:     if (&timed_flock($env_file,LOCK_EX)
                    427: 	&&
                    428: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    429: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  430: 	foreach my $key (keys(%disk_env)) {
                    431: 	    if ($key=~/^$delthis/) { 
1.619     albertel  432:                 delete($env{$key});
1.783     albertel  433:                 delete($disk_env{$key});
1.473     matthew   434:             }
1.448     albertel  435: 	}
1.783     albertel  436: 	untie(%disk_env);
1.5       www       437:     }
                    438:     return 'ok';
1.369     albertel  439: }
                    440: 
1.790     albertel  441: sub get_env_multiple {
                    442:     my ($name) = @_;
                    443:     my @values;
                    444:     if (defined($env{$name})) {
                    445:         # exists is it an array
                    446:         if (ref($env{$name})) {
                    447:             @values=@{ $env{$name} };
                    448:         } else {
                    449:             $values[0]=$env{$name};
                    450:         }
                    451:     }
                    452:     return(@values);
                    453: }
                    454: 
1.369     albertel  455: # ------------------------------------------ Find out current server userload
                    456: # there is a copy in lond
                    457: sub userload {
                    458:     my $numusers=0;
                    459:     {
                    460: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    461: 	my $filename;
                    462: 	my $curtime=time;
                    463: 	while ($filename=readdir(LONIDS)) {
                    464: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  465: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  466: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  467: 	}
                    468: 	closedir(LONIDS);
                    469:     }
                    470:     my $userloadpercent=0;
                    471:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    472:     if ($maxuserload) {
1.371     albertel  473: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  474:     }
1.372     albertel  475:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  476:     return $userloadpercent;
1.283     www       477: }
                    478: 
                    479: # ------------------------------------------ Fight off request when overloaded
                    480: 
                    481: sub overloaderror {
                    482:     my ($r,$checkserver)=@_;
                    483:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    484:     my $loadavg;
                    485:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  486:        open(my $loadfile,'/proc/loadavg');
1.283     www       487:        $loadavg=<$loadfile>;
                    488:        $loadavg =~ s/\s.*//g;
1.285     matthew   489:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  490:        close($loadfile);
1.283     www       491:     } else {
                    492:        $loadavg=&reply('load',$checkserver);
                    493:     }
1.285     matthew   494:     my $overload=$loadavg-100;
1.283     www       495:     if ($overload>0) {
1.285     matthew   496: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       497:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       498:         return 413;
1.283     www       499:     }    
                    500:     return '';
1.5       www       501: }
1.1       albertel  502: 
                    503: # ------------------------------ Find server with least workload from spare.tab
1.11      www       504: 
1.1       albertel  505: sub spareserver {
1.670     albertel  506:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  507:     my $spare_server;
1.370     albertel  508:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  509:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    510:                                                      :  $userloadpercent;
                    511:     
                    512:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    513: 	($spare_server, $lowest_load) =
                    514: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    515:     }
                    516: 
                    517:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    518: 
                    519:     if (!$found_server) {
                    520: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    521: 	    ($spare_server, $lowest_load) =
                    522: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    523: 	}
                    524:     }
                    525: 
                    526:     if (!$want_server_name) {
                    527: 	$spare_server="http://$hostname{$spare_server}";
                    528:     }
                    529:     return $spare_server;
                    530: }
                    531: 
                    532: sub compare_server_load {
                    533:     my ($try_server, $spare_server, $lowest_load) = @_;
                    534: 
                    535:     my $loadans     = &reply('load',    $try_server);
                    536:     my $userloadans = &reply('userload',$try_server);
                    537: 
                    538:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    539: 	next; #didn't get a number from the server
                    540:     }
                    541: 
                    542:     my $load;
                    543:     if ($loadans =~ /\d/) {
                    544: 	if ($userloadans =~ /\d/) {
                    545: 	    #both are numbers, pick the bigger one
                    546: 	    $load = ($loadans > $userloadans) ? $loadans 
                    547: 		                              : $userloadans;
1.411     albertel  548: 	} else {
1.784     albertel  549: 	    $load = $loadans;
1.411     albertel  550: 	}
1.784     albertel  551:     } else {
                    552: 	$load = $userloadans;
                    553:     }
                    554: 
                    555:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    556: 	$spare_server = $try_server;
                    557: 	$lowest_load  = $load;
1.370     albertel  558:     }
1.784     albertel  559:     return ($spare_server,$lowest_load);
1.202     matthew   560: }
                    561: # --------------------------------------------- Try to change a user's password
                    562: 
                    563: sub changepass {
1.799     raeburn   564:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   565:     $currentpass = &escape($currentpass);
                    566:     $newpass     = &escape($newpass);
1.799     raeburn   567:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   568: 		       $server);
                    569:     if (! $answer) {
                    570: 	&logthis("No reply on password change request to $server ".
                    571: 		 "by $uname in domain $udom.");
                    572:     } elsif ($answer =~ "^ok") {
                    573:         &logthis("$uname in $udom successfully changed their password ".
                    574: 		 "on $server.");
                    575:     } elsif ($answer =~ "^pwchange_failure") {
                    576: 	&logthis("$uname in $udom was unable to change their password ".
                    577: 		 "on $server.  The action was blocked by either lcpasswd ".
                    578: 		 "or pwchange");
                    579:     } elsif ($answer =~ "^non_authorized") {
                    580:         &logthis("$uname in $udom did not get their password correct when ".
                    581: 		 "attempting to change it on $server.");
                    582:     } elsif ($answer =~ "^auth_mode_error") {
                    583:         &logthis("$uname in $udom attempted to change their password despite ".
                    584: 		 "not being locally or internally authenticated on $server.");
                    585:     } elsif ($answer =~ "^unknown_user") {
                    586:         &logthis("$uname in $udom attempted to change their password ".
                    587: 		 "on $server but were unable to because $server is not ".
                    588: 		 "their home server.");
                    589:     } elsif ($answer =~ "^refused") {
                    590: 	&logthis("$server refused to change $uname in $udom password because ".
                    591: 		 "it was sent an unencrypted request to change the password.");
                    592:     }
                    593:     return $answer;
1.1       albertel  594: }
                    595: 
1.169     harris41  596: # ----------------------- Try to determine user's current authentication scheme
                    597: 
                    598: sub queryauthenticate {
                    599:     my ($uname,$udom)=@_;
1.456     albertel  600:     my $uhome=&homeserver($uname,$udom);
                    601:     if (!$uhome) {
                    602: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    603: 	return 'no_host';
                    604:     }
                    605:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    606:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    607: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  608:     }
1.456     albertel  609:     return $answer;
1.169     harris41  610: }
                    611: 
1.1       albertel  612: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       613: 
1.1       albertel  614: sub authenticate {
                    615:     my ($uname,$upass,$udom)=@_;
1.807     albertel  616:     $upass=&escape($upass);
                    617:     $uname= &LONCAPA::clean_username($uname);
1.471     albertel  618:     my $uhome=&homeserver($uname,$udom);
                    619:     if (!$uhome) {
                    620: 	&logthis("User $uname at $udom is unknown in authenticate");
                    621: 	return 'no_host';
1.1       albertel  622:     }
1.471     albertel  623:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    624:     if ($answer eq 'authorized') {
                    625: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    626: 	return $uhome; 
                    627:     }
                    628:     if ($answer eq 'non_authorized') {
                    629: 	&logthis("User $uname at $udom rejected by $uhome");
                    630: 	return 'no_host'; 
1.9       www       631:     }
1.471     albertel  632:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  633:     return 'no_host';
                    634: }
                    635: 
                    636: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       637: 
1.599     albertel  638: my %homecache;
1.1       albertel  639: sub homeserver {
1.230     stredwic  640:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  641:     my $index="$uname:$udom";
1.426     albertel  642: 
1.599     albertel  643:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  644:     my $tryserver;
                    645:     foreach $tryserver (keys %libserv) {
1.230     stredwic  646:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  647: 		 exists($badServerCache{$tryserver}));
1.1       albertel  648: 	if ($hostdom{$tryserver} eq $udom) {
                    649:            my $answer=reply("home:$udom:$uname",$tryserver);
                    650:            if ($answer eq 'found') { 
1.599     albertel  651: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  652:            } elsif ($answer eq 'no_host') {
                    653: 	       $badServerCache{$tryserver}=1;
1.221     matthew   654:            }
1.1       albertel  655:        }
                    656:     }    
                    657:     return 'no_host';
1.70      www       658: }
                    659: 
                    660: # ------------------------------------- Find the usernames behind a list of IDs
                    661: 
                    662: sub idget {
                    663:     my ($udom,@ids)=@_;
                    664:     my %returnhash=();
                    665:     
                    666:     my $tryserver;
                    667:     foreach $tryserver (keys %libserv) {
                    668:        if ($hostdom{$tryserver} eq $udom) {
                    669: 	  my $idlist=join('&',@ids);
                    670:           $idlist=~tr/A-Z/a-z/; 
                    671: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    672:           my @answer=();
1.76      www       673:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       674: 	      @answer=split(/\&/,$reply);
                    675:           }                    ;
                    676:           my $i;
                    677:           for ($i=0;$i<=$#ids;$i++) {
                    678:               if ($answer[$i]) {
                    679: 		  $returnhash{$ids[$i]}=$answer[$i];
                    680:               } 
                    681:           }
                    682:        }
                    683:     }    
                    684:     return %returnhash;
                    685: }
                    686: 
                    687: # ------------------------------------- Find the IDs behind a list of usernames
                    688: 
                    689: sub idrget {
                    690:     my ($udom,@unames)=@_;
                    691:     my %returnhash=();
1.800     albertel  692:     foreach my $uname (@unames) {
                    693:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  694:     }
1.70      www       695:     return %returnhash;
                    696: }
                    697: 
                    698: # ------------------------------- Store away a list of names and associated IDs
                    699: 
                    700: sub idput {
                    701:     my ($udom,%ids)=@_;
                    702:     my %servers=();
1.800     albertel  703:     foreach my $uname (keys(%ids)) {
                    704: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    705:         my $uhom=&homeserver($uname,$udom);
1.70      www       706:         if ($uhom ne 'no_host') {
1.800     albertel  707:             my $id=&escape($ids{$uname});
1.70      www       708:             $id=~tr/A-Z/a-z/;
1.800     albertel  709:             my $esc_unam=&escape($uname);
1.70      www       710: 	    if ($servers{$uhom}) {
1.800     albertel  711: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       712:             } else {
1.800     albertel  713:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       714:             }
                    715:         }
1.191     harris41  716:     }
1.800     albertel  717:     foreach my $server (keys(%servers)) {
                    718:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  719:     }
1.344     www       720: }
                    721: 
1.806     raeburn   722: # ------------------------------------------- get items from domain db files   
                    723: 
                    724: sub get_dom {
                    725:     my ($namespace,$storearr,$udom)=@_;
                    726:     my $items='';
                    727:     foreach my $item (@$storearr) {
                    728:         $items.=&escape($item).'&';
                    729:     }
                    730:     $items=~s/\&$//;
                    731:     if (!$udom) { $udom=$env{'user.domain'}; }
                    732:     if (exists($domain_primary{$udom})) {
                    733:         my $uhome=$domain_primary{$udom};
                    734:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    735:         my @pairs=split(/\&/,$rep);
                    736:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    737:             return @pairs;
                    738:         }
                    739:         my %returnhash=();
                    740:         my $i=0;
                    741:         foreach my $item (@$storearr) {
                    742:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    743:             $i++;
                    744:         }
                    745:         return %returnhash;
                    746:     } else {
                    747:         &logthis("get_dom failed - no primary domain server for $udom");
                    748:     }
                    749: }
                    750: 
                    751: # -------------------------------------------- put items in domain db files 
                    752: 
                    753: sub put_dom {
                    754:     my ($namespace,$storehash,$udom)=@_;
                    755:     if (!$udom) { $udom=$env{'user.domain'}; }
                    756:     if (exists($domain_primary{$udom})) {
                    757:         my $uhome=$domain_primary{$udom};
                    758:         my $items='';
                    759:         foreach my $item (keys(%$storehash)) {
                    760:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    761:         }
                    762:         $items=~s/\&$//;
                    763:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    764:     } else {
                    765:         &logthis("put_dom failed - no primary domain server for $udom");
                    766:     }
                    767: }
                    768: 
1.344     www       769: # --------------------------------------------------- Assign a key to a student
                    770: 
                    771: sub assign_access_key {
1.364     www       772: #
                    773: # a valid key looks like uname:udom#comments
                    774: # comments are being appended
                    775: #
1.498     www       776:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    777:     $kdom=
1.620     albertel  778:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       779:     $knum=
1.620     albertel  780:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       781:     $cdom=
1.620     albertel  782:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       783:     $cnum=
1.620     albertel  784:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    785:     $udom=$env{'user.name'} unless (defined($udom));
                    786:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       787:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       788:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  789:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       790:                                                   # assigned to this person
                    791:                                                   # - this should not happen,
1.345     www       792:                                                   # unless something went wrong
                    793:                                                   # the first time around
                    794: # ready to assign
1.364     www       795:         $logentry=$1.'; '.$logentry;
1.496     www       796:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       797:                                                  $kdom,$knum) eq 'ok') {
1.345     www       798: # key now belongs to user
1.346     www       799: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       800:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    801:                 &appenv('environment.'.$envkey => $ckey);
                    802:                 return 'ok';
                    803:             } else {
                    804:                 return 
                    805:   'error: Count not permanently assign key, will need to be re-entered later.';
                    806: 	    }
                    807:         } else {
                    808:             return 'error: Could not assign key, try again later.';
                    809:         }
1.364     www       810:     } elsif (!$existing{$ckey}) {
1.345     www       811: # the key does not exist
                    812: 	return 'error: The key does not exist';
                    813:     } else {
                    814: # the key is somebody else's
                    815: 	return 'error: The key is already in use';
                    816:     }
1.344     www       817: }
                    818: 
1.364     www       819: # ------------------------------------------ put an additional comment on a key
                    820: 
                    821: sub comment_access_key {
                    822: #
                    823: # a valid key looks like uname:udom#comments
                    824: # comments are being appended
                    825: #
                    826:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    827:     $cdom=
1.620     albertel  828:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       829:     $cnum=
1.620     albertel  830:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       831:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    832:     if ($existing{$ckey}) {
                    833:         $existing{$ckey}.='; '.$logentry;
                    834: # ready to assign
1.367     www       835:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       836:                                                  $cdom,$cnum) eq 'ok') {
                    837: 	    return 'ok';
                    838:         } else {
                    839: 	    return 'error: Count not store comment.';
                    840:         }
                    841:     } else {
                    842: # the key does not exist
                    843: 	return 'error: The key does not exist';
                    844:     }
                    845: }
                    846: 
1.344     www       847: # ------------------------------------------------------ Generate a set of keys
                    848: 
                    849: sub generate_access_keys {
1.364     www       850:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       851:     $cdom=
1.620     albertel  852:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       853:     $cnum=
1.620     albertel  854:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       855:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       856:     unless (($cdom) && ($cnum)) { return 0; }
                    857:     if ($number>10000) { return 0; }
                    858:     sleep(2); # make sure don't get same seed twice
                    859:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    860:     my $total=0;
                    861:     for (my $i=1;$i<=$number;$i++) {
                    862:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    863:                   sprintf("%lx",int(100000*rand)).'-'.
                    864:                   sprintf("%lx",int(100000*rand));
                    865:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    866:        $newkey=~s/0/h/g; # and also 0 and O
                    867:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    868:        if ($existing{$newkey}) {
                    869:            $i--;
                    870:        } else {
1.364     www       871: 	  if (&put('accesskeys',
                    872:               { $newkey => '# generated '.localtime().
1.620     albertel  873:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       874:                            '; '.$logentry },
                    875: 		   $cdom,$cnum) eq 'ok') {
1.344     www       876:               $total++;
                    877: 	  }
                    878:        }
                    879:     }
1.620     albertel  880:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       881:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    882:     return $total;
                    883: }
                    884: 
                    885: # ------------------------------------------------------- Validate an accesskey
                    886: 
                    887: sub validate_access_key {
                    888:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    889:     $cdom=
1.620     albertel  890:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       891:     $cnum=
1.620     albertel  892:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    893:     $udom=$env{'user.domain'} unless (defined($udom));
                    894:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       895:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  896:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       897: }
                    898: 
                    899: # ------------------------------------- Find the section of student in a course
1.652     albertel  900: sub devalidate_getsection_cache {
                    901:     my ($udom,$unam,$courseid)=@_;
                    902:     my $hashid="$udom:$unam:$courseid";
                    903:     &devalidate_cache_new('getsection',$hashid);
                    904: }
1.298     matthew   905: 
1.815     albertel  906: sub courseid_to_courseurl {
                    907:     my ($courseid) = @_;
                    908:     #already url style courseid
                    909:     return $courseid if ($courseid =~ m{^/});
                    910: 
                    911:     if (exists($env{'course.'.$courseid.'.num'})) {
                    912: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    913: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    914: 	return "/$cdom/$cnum";
                    915:     }
                    916: 
                    917:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    918:     if (exists($courseinfo{'num'})) {
                    919: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    920:     }
                    921: 
                    922:     return undef;
                    923: }
                    924: 
1.298     matthew   925: sub getsection {
                    926:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  927:     my $cachetime=1800;
1.551     albertel  928: 
                    929:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  930:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  931:     if (defined($cached)) { return $result; }
                    932: 
1.298     matthew   933:     my %Pending; 
                    934:     my %Expired;
                    935:     #
                    936:     # Each role can either have not started yet (pending), be active, 
                    937:     #    or have expired.
                    938:     #
                    939:     # If there is an active role, we are done.
                    940:     #
                    941:     # If there is more than one role which has not started yet, 
                    942:     #     choose the one which will start sooner
                    943:     # If there is one role which has not started yet, return it.
                    944:     #
                    945:     # If there is more than one expired role, choose the one which ended last.
                    946:     # If there is a role which has expired, return it.
                    947:     #
1.815     albertel  948:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   949:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    950:     foreach my $key (keys(%roleshash)) {
1.479     albertel  951:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   952:         my $section=$1;
                    953:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   954:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   955:         my $now=time;
1.548     albertel  956:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   957:             $Expired{$end}=$section;
                    958:             next;
                    959:         }
1.548     albertel  960:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   961:             $Pending{$start}=$section;
                    962:             next;
                    963:         }
1.599     albertel  964:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   965:     }
                    966:     #
                    967:     # Presumedly there will be few matching roles from the above
                    968:     # loop and the sorting time will be negligible.
                    969:     if (scalar(keys(%Pending))) {
                    970:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  971:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   972:     } 
                    973:     if (scalar(keys(%Expired))) {
                    974:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    975:         my $time = pop(@sorted);
1.599     albertel  976:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   977:     }
1.599     albertel  978:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   979: }
1.70      www       980: 
1.599     albertel  981: sub save_cache {
                    982:     &purge_remembered();
1.722     albertel  983:     #&Apache::loncommon::validate_page();
1.620     albertel  984:     undef(%env);
1.780     albertel  985:     undef($env_loaded);
1.599     albertel  986: }
1.452     albertel  987: 
1.599     albertel  988: my $to_remember=-1;
                    989: my %remembered;
                    990: my %accessed;
                    991: my $kicks=0;
                    992: my $hits=0;
1.824.2.3! albertel  993: sub make_key {
        !           994:     my ($name,$id) = @_;
        !           995:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
        !           996:     return &escape($name.':'.$id);
        !           997: }
        !           998: 
1.599     albertel  999: sub devalidate_cache_new {
                   1000:     my ($name,$id,$debug) = @_;
                   1001:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.824.2.3! albertel 1002:     $id=&make_key($name,$id);
1.599     albertel 1003:     $memcache->delete($id);
                   1004:     delete($remembered{$id});
                   1005:     delete($accessed{$id});
                   1006: }
                   1007: 
                   1008: sub is_cached_new {
                   1009:     my ($name,$id,$debug) = @_;
1.824.2.3! albertel 1010:     $id=&make_key($name,$id);
1.599     albertel 1011:     if (exists($remembered{$id})) {
                   1012: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1013: 	$accessed{$id}=[&gettimeofday()];
                   1014: 	$hits++;
                   1015: 	return ($remembered{$id},1);
                   1016:     }
                   1017:     my $value = $memcache->get($id);
                   1018:     if (!(defined($value))) {
                   1019: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1020: 	return (undef,undef);
1.416     albertel 1021:     }
1.599     albertel 1022:     if ($value eq '__undef__') {
                   1023: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1024: 	$value=undef;
                   1025:     }
                   1026:     &make_room($id,$value,$debug);
                   1027:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1028:     return ($value,1);
                   1029: }
                   1030: 
                   1031: sub do_cache_new {
                   1032:     my ($name,$id,$value,$time,$debug) = @_;
1.824.2.3! albertel 1033:     $id=&make_key($name,$id);
1.599     albertel 1034:     my $setvalue=$value;
                   1035:     if (!defined($setvalue)) {
                   1036: 	$setvalue='__undef__';
                   1037:     }
1.623     albertel 1038:     if (!defined($time) ) {
                   1039: 	$time=600;
                   1040:     }
1.599     albertel 1041:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1042:     $memcache->set($id,$setvalue,$time);
                   1043:     # need to make a copy of $value
                   1044:     #&make_room($id,$value,$debug);
1.599     albertel 1045:     return $value;
                   1046: }
                   1047: 
                   1048: sub make_room {
                   1049:     my ($id,$value,$debug)=@_;
                   1050:     $remembered{$id}=$value;
                   1051:     if ($to_remember<0) { return; }
                   1052:     $accessed{$id}=[&gettimeofday()];
                   1053:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1054:     my $to_kick;
                   1055:     my $max_time=0;
                   1056:     foreach my $other (keys(%accessed)) {
                   1057: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1058: 	    $to_kick=$other;
                   1059: 	    $max_time=&tv_interval($accessed{$other});
                   1060: 	}
                   1061:     }
                   1062:     delete($remembered{$to_kick});
                   1063:     delete($accessed{$to_kick});
                   1064:     $kicks++;
                   1065:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1066:     return;
                   1067: }
                   1068: 
1.599     albertel 1069: sub purge_remembered {
1.604     albertel 1070:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1071:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1072:     undef(%remembered);
                   1073:     undef(%accessed);
1.428     albertel 1074: }
1.70      www      1075: # ------------------------------------- Read an entry from a user's environment
                   1076: 
                   1077: sub userenvironment {
                   1078:     my ($udom,$unam,@what)=@_;
                   1079:     my %returnhash=();
                   1080:     my @answer=split(/\&/,
                   1081:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1082:                       &homeserver($unam,$udom)));
                   1083:     my $i;
                   1084:     for ($i=0;$i<=$#what;$i++) {
                   1085: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1086:     }
                   1087:     return %returnhash;
1.1       albertel 1088: }
                   1089: 
1.617     albertel 1090: # ---------------------------------------------------------- Get a studentphoto
                   1091: sub studentphoto {
                   1092:     my ($udom,$unam,$ext) = @_;
                   1093:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1094:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1095:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1096:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1097:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1098:             } else {
                   1099:                 my ($result,$perm_reqd)=
1.707     albertel 1100: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1101:                 if ($result eq 'ok') {
                   1102:                     if (!($perm_reqd eq 'yes')) {
                   1103:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1104:                     }
                   1105:                 }
                   1106:             }
                   1107:         }
                   1108:     } else {
                   1109:         my ($result,$perm_reqd) = 
1.707     albertel 1110: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1111:         if ($result eq 'ok') {
                   1112:             if (!($perm_reqd eq 'yes')) {
                   1113:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1114:             }
                   1115:         }
                   1116:     }
                   1117:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1118: }
                   1119: 
                   1120: sub retrievestudentphoto {
                   1121:     my ($udom,$unam,$ext,$type) = @_;
                   1122:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1123:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1124:     if ($ret eq 'ok') {
                   1125:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1126:         if ($type eq 'thumbnail') {
                   1127:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1128:         }
                   1129:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1130:         return $tokenurl;
                   1131:     } else {
                   1132:         if ($type eq 'thumbnail') {
                   1133:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1134:         } else { 
                   1135:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1136:         }
1.617     albertel 1137:     }
                   1138: }
                   1139: 
1.263     www      1140: # -------------------------------------------------------------------- New chat
                   1141: 
                   1142: sub chatsend {
1.724     raeburn  1143:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1144:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1145:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1146:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1147:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1148: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1149: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1150: }
                   1151: 
                   1152: # ------------------------------------------ Find current version of a resource
                   1153: 
                   1154: sub getversion {
                   1155:     my $fname=&clutter(shift);
                   1156:     unless ($fname=~/^\/res\//) { return -1; }
                   1157:     return &currentversion(&filelocation('',$fname));
                   1158: }
                   1159: 
                   1160: sub currentversion {
                   1161:     my $fname=shift;
1.599     albertel 1162:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1163:     if (defined($cached)) { return $result; }
1.292     www      1164:     my $author=$fname;
                   1165:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1166:     my ($udom,$uname)=split(/\//,$author);
                   1167:     my $home=homeserver($uname,$udom);
                   1168:     if ($home eq 'no_host') { 
                   1169:         return -1; 
                   1170:     }
                   1171:     my $answer=reply("currentversion:$fname",$home);
                   1172:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1173: 	return -1;
                   1174:     }
1.599     albertel 1175:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1176: }
                   1177: 
1.1       albertel 1178: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1179: 
1.1       albertel 1180: sub subscribe {
                   1181:     my $fname=shift;
1.761     raeburn  1182:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1183:     $fname=~s/[\n\r]//g;
1.1       albertel 1184:     my $author=$fname;
                   1185:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1186:     my ($udom,$uname)=split(/\//,$author);
                   1187:     my $home=homeserver($uname,$udom);
1.335     albertel 1188:     if ($home eq 'no_host') {
                   1189:         return 'not_found';
1.1       albertel 1190:     }
                   1191:     my $answer=reply("sub:$fname",$home);
1.64      www      1192:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1193: 	$answer.=' by '.$home;
                   1194:     }
1.1       albertel 1195:     return $answer;
                   1196: }
                   1197:     
1.8       www      1198: # -------------------------------------------------------------- Replicate file
                   1199: 
                   1200: sub repcopy {
                   1201:     my $filename=shift;
1.23      www      1202:     $filename=~s/\/+/\//g;
1.607     raeburn  1203:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1204:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1205:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1206: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1207: 	return &repcopy_userfile($filename);
                   1208:     }
1.532     albertel 1209:     $filename=~s/[\n\r]//g;
1.8       www      1210:     my $transname="$filename.in.transfer";
1.607     raeburn  1211:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1212:     my $remoteurl=subscribe($filename);
1.64      www      1213:     if ($remoteurl =~ /^con_lost by/) {
                   1214: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1215:            return 'unavailable';
1.8       www      1216:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1217: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1218: 	   return 'not_found';
1.64      www      1219:     } elsif ($remoteurl =~ /^rejected by/) {
                   1220: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1221:            return 'forbidden';
1.20      www      1222:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1223:            return 'ok';
1.8       www      1224:     } else {
1.290     www      1225:         my $author=$filename;
                   1226:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1227:         my ($udom,$uname)=split(/\//,$author);
                   1228:         my $home=homeserver($uname,$udom);
                   1229:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1230:            my @parts=split(/\//,$filename);
                   1231:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1232:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1233:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1234: 	       return 'bad_request';
1.8       www      1235:            }
                   1236:            my $count;
                   1237:            for ($count=5;$count<$#parts;$count++) {
                   1238:                $path.="/$parts[$count]";
                   1239:                if ((-e $path)!=1) {
                   1240: 		   mkdir($path,0777);
                   1241:                }
                   1242:            }
                   1243:            my $ua=new LWP::UserAgent;
                   1244:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1245:            my $response=$ua->request($request,$transname);
                   1246:            if ($response->is_error()) {
                   1247: 	       unlink($transname);
                   1248:                my $message=$response->status_line;
1.672     albertel 1249:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1250:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1251:                return 'unavailable';
1.8       www      1252:            } else {
1.16      www      1253: 	       if ($remoteurl!~/\.meta$/) {
                   1254:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1255:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1256:                   if ($mresponse->is_error()) {
                   1257: 		      unlink($filename.'.meta');
                   1258:                       &logthis(
1.672     albertel 1259:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1260:                   }
                   1261: 	       }
1.8       www      1262:                rename($transname,$filename);
1.607     raeburn  1263:                return 'ok';
1.8       www      1264:            }
1.290     www      1265:        }
1.8       www      1266:     }
1.330     www      1267: }
                   1268: 
                   1269: # ------------------------------------------------ Get server side include body
                   1270: sub ssi_body {
1.381     albertel 1271:     my ($filelink,%form)=@_;
1.606     matthew  1272:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1273:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1274:     }
1.330     www      1275:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1276:                                      &ssi($filelink,%form));
1.778     albertel 1277:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1278:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1279:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1280:     return $output;
1.8       www      1281: }
                   1282: 
1.15      www      1283: # --------------------------------------------------------- Server Side Include
                   1284: 
1.782     albertel 1285: sub absolute_url {
                   1286:     my ($host_name) = @_;
                   1287:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1288:     if ($host_name eq '') {
                   1289: 	$host_name = $ENV{'SERVER_NAME'};
                   1290:     }
                   1291:     return $protocol.$host_name;
                   1292: }
                   1293: 
1.15      www      1294: sub ssi {
                   1295: 
1.23      www      1296:     my ($fn,%form)=@_;
1.15      www      1297: 
                   1298:     my $ua=new LWP::UserAgent;
1.23      www      1299:     
                   1300:     my $request;
1.711     albertel 1301: 
                   1302:     $form{'no_update_last_known'}=1;
                   1303: 
1.23      www      1304:     if (%form) {
1.782     albertel 1305:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1306:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1307:     } else {
1.782     albertel 1308:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1309:     }
                   1310: 
1.15      www      1311:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1312:     my $response=$ua->request($request);
                   1313: 
1.324     www      1314:     return $response->content;
                   1315: }
                   1316: 
                   1317: sub externalssi {
                   1318:     my ($url)=@_;
                   1319:     my $ua=new LWP::UserAgent;
                   1320:     my $request=new HTTP::Request('GET',$url);
                   1321:     my $response=$ua->request($request);
1.15      www      1322:     return $response->content;
                   1323: }
1.254     www      1324: 
1.492     albertel 1325: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1326: 
                   1327: sub allowuploaded {
                   1328:     my ($srcurl,$url)=@_;
                   1329:     $url=&clutter(&declutter($url));
                   1330:     my $dir=$url;
                   1331:     $dir=~s/\/[^\/]+$//;
                   1332:     my %httpref=();
                   1333:     my $httpurl=&hreflocation('',$url);
                   1334:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1335:     &Apache::lonnet::appenv(%httpref);
1.254     www      1336: }
1.477     raeburn  1337: 
1.478     albertel 1338: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1339: # input: action, courseID, current domain, intended
1.637     raeburn  1340: #        path to file, source of file, instruction to parse file for objects,
                   1341: #        ref to hash for embedded objects,
                   1342: #        ref to hash for codebase of java objects.
                   1343: #
1.485     raeburn  1344: # output: url to file (if action was uploaddoc), 
                   1345: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1346: #
1.478     albertel 1347: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1348: # course.
1.477     raeburn  1349: #
1.478     albertel 1350: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1351: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1352: #          course's home server.
1.477     raeburn  1353: #
1.478     albertel 1354: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1355: #          be copied from $source (current location) to 
                   1356: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1357: #         and will then be copied to
                   1358: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1359: #         course's home server.
1.485     raeburn  1360: #
1.481     raeburn  1361: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1362: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1363: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1364: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1365: #         in course's home server.
1.637     raeburn  1366: #
1.477     raeburn  1367: 
                   1368: sub process_coursefile {
1.638     albertel 1369:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1370:     my $fetchresult;
1.638     albertel 1371:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1372:     if ($action eq 'propagate') {
1.638     albertel 1373:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1374: 			     $home);
1.481     raeburn  1375:     } else {
1.477     raeburn  1376:         my $fpath = '';
                   1377:         my $fname = $file;
1.478     albertel 1378:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1379:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1380:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1381:         if ($action eq 'copy') {
                   1382:             if ($source eq '') {
                   1383:                 $fetchresult = 'no source file';
                   1384:                 return $fetchresult;
                   1385:             } else {
                   1386:                 my $destination = $filepath.'/'.$fname;
                   1387:                 rename($source,$destination);
                   1388:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1389:                                  $home);
1.481     raeburn  1390:             }
                   1391:         } elsif ($action eq 'uploaddoc') {
                   1392:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1393:             print $fh $env{'form.'.$source};
1.481     raeburn  1394:             close($fh);
1.637     raeburn  1395:             if ($parser eq 'parse') {
                   1396:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1397:                 unless ($parse_result eq 'ok') {
                   1398:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1399:                 }
                   1400:             }
1.477     raeburn  1401:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1402:                                  $home);
1.481     raeburn  1403:             if ($fetchresult eq 'ok') {
                   1404:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1405:             } else {
                   1406:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1407:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1408:                 return '/adm/notfound.html';
                   1409:             }
1.477     raeburn  1410:         }
                   1411:     }
1.485     raeburn  1412:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1413:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1414:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1415:     }
                   1416:     return $fetchresult;
                   1417: }
                   1418: 
1.637     raeburn  1419: sub build_filepath {
                   1420:     my ($fpath) = @_;
                   1421:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1422:     unless ($fpath eq '') {
                   1423:         my @parts=split('/',$fpath);
                   1424:         foreach my $part (@parts) {
                   1425:             $filepath.= '/'.$part;
                   1426:             if ((-e $filepath)!=1) {
                   1427:                 mkdir($filepath,0777);
                   1428:             }
                   1429:         }
                   1430:     }
                   1431:     return $filepath;
                   1432: }
                   1433: 
                   1434: sub store_edited_file {
1.638     albertel 1435:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1436:     my $file = $primary_url;
                   1437:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1438:     my $fpath = '';
                   1439:     my $fname = $file;
                   1440:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1441:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1442:     my $filepath = &build_filepath($fpath);
                   1443:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1444:     print $fh $content;
                   1445:     close($fh);
1.638     albertel 1446:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1447:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1448: 			  $home);
1.637     raeburn  1449:     if ($$fetchresult eq 'ok') {
                   1450:         return '/uploaded/'.$fpath.'/'.$fname;
                   1451:     } else {
1.638     albertel 1452:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1453: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1454:         return '/adm/notfound.html';
                   1455:     }
                   1456: }
                   1457: 
1.531     albertel 1458: sub clean_filename {
                   1459:     my ($fname)=@_;
1.315     www      1460: # Replace Windows backslashes by forward slashes
1.257     www      1461:     $fname=~s/\\/\//g;
1.315     www      1462: # Get rid of everything but the actual filename
1.257     www      1463:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1464: # Replace spaces by underscores
                   1465:     $fname=~s/\s+/\_/g;
                   1466: # Replace all other weird characters by nothing
1.317     www      1467:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1468: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1469: # numbers
                   1470:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1471:     return $fname;
                   1472: }
                   1473: 
1.608     albertel 1474: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1475: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1476: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1477: #        $coursedoc - if true up to the current course
                   1478: #                     if false
                   1479: #        $subdir - directory in userfile to store the file into
                   1480: #        $parser, $allfiles, $codebase - unknown
                   1481: #
                   1482: # output: url of file in userspace, or error: <message> 
                   1483: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1484: 
                   1485: 
1.531     albertel 1486: sub userfileupload {
1.719     banghart 1487:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1488:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1489:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1490:     $fname=&clean_filename($fname);
1.315     www      1491: # See if there is anything left
1.257     www      1492:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1493:     chop($env{'form.'.$formname});
1.523     raeburn  1494:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1495:         my $now = time;
                   1496:         my $filepath = 'tmp/helprequests/'.$now;
                   1497:         my @parts=split(/\//,$filepath);
                   1498:         my $fullpath = $perlvar{'lonDaemons'};
                   1499:         for (my $i=0;$i<@parts;$i++) {
                   1500:             $fullpath .= '/'.$parts[$i];
                   1501:             if ((-e $fullpath)!=1) {
                   1502:                 mkdir($fullpath,0777);
                   1503:             }
                   1504:         }
                   1505:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1506:         print $fh $env{'form.'.$formname};
1.523     raeburn  1507:         close($fh);
1.741     raeburn  1508:         return $fullpath.'/'.$fname;
                   1509:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1510:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1511:                        '_'.$env{'user.domain'}.'/pending';
                   1512:         my @parts=split(/\//,$filepath);
                   1513:         my $fullpath = $perlvar{'lonDaemons'};
                   1514:         for (my $i=0;$i<@parts;$i++) {
                   1515:             $fullpath .= '/'.$parts[$i];
                   1516:             if ((-e $fullpath)!=1) {
                   1517:                 mkdir($fullpath,0777);
                   1518:             }
                   1519:         }
                   1520:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1521:         print $fh $env{'form.'.$formname};
                   1522:         close($fh);
                   1523:         return $fullpath.'/'.$fname;
1.523     raeburn  1524:     }
1.719     banghart 1525:     
1.258     www      1526: # Create the directory if not present
1.493     albertel 1527:     $fname="$subdir/$fname";
1.259     www      1528:     if ($coursedoc) {
1.638     albertel 1529: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1530: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1531:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1532:             return &finishuserfileupload($docuname,$docudom,
                   1533: 					 $formname,$fname,$parser,$allfiles,
                   1534: 					 $codebase);
1.481     raeburn  1535:         } else {
1.620     albertel 1536:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1537:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1538: 				       $fname,$formname,$parser,
                   1539: 				       $allfiles,$codebase);
1.481     raeburn  1540:         }
1.719     banghart 1541:     } elsif (defined($destuname)) {
                   1542:         my $docuname=$destuname;
                   1543:         my $docudom=$destudom;
                   1544: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1545: 				     $fname,$parser,$allfiles,$codebase);
                   1546:         
1.259     www      1547:     } else {
1.638     albertel 1548:         my $docuname=$env{'user.name'};
                   1549:         my $docudom=$env{'user.domain'};
1.714     raeburn  1550:         if (exists($env{'form.group'})) {
                   1551:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1552:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1553:         }
1.638     albertel 1554: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1555: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1556:     }
1.271     www      1557: }
                   1558: 
                   1559: sub finishuserfileupload {
1.638     albertel 1560:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1561:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1562:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1563:     my ($fnamepath,$file);
                   1564:     $file=$fname;
                   1565:     if ($fname=~m|/|) {
                   1566:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1567: 	$path.=$fnamepath.'/';
                   1568:     }
1.259     www      1569:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1570:     my $count;
                   1571:     for ($count=4;$count<=$#parts;$count++) {
                   1572:         $filepath.="/$parts[$count]";
                   1573:         if ((-e $filepath)!=1) {
                   1574: 	    mkdir($filepath,0777);
                   1575:         }
                   1576:     }
                   1577: # Save the file
                   1578:     {
1.701     albertel 1579: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1580: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1581: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1582: 	    return '/adm/notfound.html';
                   1583: 	}
                   1584: 	if (!print FH ($env{'form.'.$formname})) {
                   1585: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1586: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1587: 	    return '/adm/notfound.html';
                   1588: 	}
1.570     albertel 1589: 	close(FH);
1.258     www      1590:     }
1.637     raeburn  1591:     if ($parser eq 'parse') {
1.638     albertel 1592:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1593: 						   $codebase);
1.637     raeburn  1594:         unless ($parse_result eq 'ok') {
1.638     albertel 1595:             &logthis('Failed to parse '.$filepath.$file.
                   1596: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1597:         }
                   1598:     }
1.259     www      1599: # Notify homeserver to grep it
                   1600: #
1.638     albertel 1601:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1602:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1603:     if ($fetchresult eq 'ok') {
1.259     www      1604: #
1.258     www      1605: # Return the URL to it
1.494     albertel 1606:         return '/uploaded/'.$path.$file;
1.263     www      1607:     } else {
1.494     albertel 1608:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1609: 		 ': '.$fetchresult);
1.263     www      1610:         return '/adm/notfound.html';
                   1611:     }    
1.493     albertel 1612: }
                   1613: 
1.637     raeburn  1614: sub extract_embedded_items {
1.648     raeburn  1615:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1616:     my @state = ();
                   1617:     my %javafiles = (
                   1618:                       codebase => '',
                   1619:                       code => '',
                   1620:                       archive => ''
                   1621:                     );
                   1622:     my %mediafiles = (
                   1623:                       src => '',
                   1624:                       movie => '',
                   1625:                      );
1.648     raeburn  1626:     my $p;
                   1627:     if ($content) {
                   1628:         $p = HTML::LCParser->new($content);
                   1629:     } else {
                   1630:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1631:     }
1.641     albertel 1632:     while (my $t=$p->get_token()) {
1.640     albertel 1633: 	if ($t->[0] eq 'S') {
                   1634: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1635: 	    push (@state, $tagname);
1.648     raeburn  1636:             if (lc($tagname) eq 'allow') {
                   1637:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1638:             }
1.640     albertel 1639: 	    if (lc($tagname) eq 'img') {
                   1640: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1641: 	    }
1.645     raeburn  1642:             if (lc($tagname) eq 'script') {
                   1643:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1644:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1645:                 } else {
                   1646:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1647:                 }
                   1648:             }
                   1649:             if (lc($tagname) eq 'link') {
                   1650:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1651:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1652:                 }
                   1653:             }
1.640     albertel 1654: 	    if (lc($tagname) eq 'object' ||
                   1655: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1656: 		foreach my $item (keys(%javafiles)) {
                   1657: 		    $javafiles{$item} = '';
                   1658: 		}
                   1659: 	    }
                   1660: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1661: 		my $name = lc($attr->{'name'});
                   1662: 		foreach my $item (keys(%javafiles)) {
                   1663: 		    if ($name eq $item) {
                   1664: 			$javafiles{$item} = $attr->{'value'};
                   1665: 			last;
                   1666: 		    }
                   1667: 		}
                   1668: 		foreach my $item (keys(%mediafiles)) {
                   1669: 		    if ($name eq $item) {
                   1670: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1671: 			last;
                   1672: 		    }
                   1673: 		}
                   1674: 	    }
                   1675: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1676: 		foreach my $item (keys(%javafiles)) {
                   1677: 		    if ($attr->{$item}) {
                   1678: 			$javafiles{$item} = $attr->{$item};
                   1679: 			last;
                   1680: 		    }
                   1681: 		}
                   1682: 		foreach my $item (keys(%mediafiles)) {
                   1683: 		    if ($attr->{$item}) {
                   1684: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1685: 			last;
                   1686: 		    }
                   1687: 		}
                   1688: 	    }
                   1689: 	} elsif ($t->[0] eq 'E') {
                   1690: 	    my ($tagname) = ($t->[1]);
                   1691: 	    if ($javafiles{'codebase'} ne '') {
                   1692: 		$javafiles{'codebase'} .= '/';
                   1693: 	    }  
                   1694: 	    if (lc($tagname) eq 'applet' ||
                   1695: 		lc($tagname) eq 'object' ||
                   1696: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1697: 		) {
                   1698: 		foreach my $item (keys(%javafiles)) {
                   1699: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1700: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1701: 			&add_filetype($allfiles,$file,$item);
                   1702: 		    }
                   1703: 		}
                   1704: 	    } 
                   1705: 	    pop @state;
                   1706: 	}
                   1707:     }
1.637     raeburn  1708:     return 'ok';
                   1709: }
                   1710: 
1.639     albertel 1711: sub add_filetype {
                   1712:     my ($allfiles,$file,$type)=@_;
                   1713:     if (exists($allfiles->{$file})) {
                   1714: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1715: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1716: 	}
                   1717:     } else {
                   1718: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1719:     }
                   1720: }
                   1721: 
1.493     albertel 1722: sub removeuploadedurl {
                   1723:     my ($url)=@_;
                   1724:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1725:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1726: }
                   1727: 
                   1728: sub removeuserfile {
                   1729:     my ($docuname,$docudom,$fname)=@_;
                   1730:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1731:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1732:     if ($result eq 'ok') {
                   1733:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1734:             my $metafile = $fname.'.meta';
                   1735:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1736: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1737:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1738:             my $sqlresult = 
1.823     albertel 1739:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1740:                                         'portfolio_metadata',$group,
                   1741:                                         'delete');
1.798     raeburn  1742:         }
                   1743:     }
                   1744:     return $result;
1.257     www      1745: }
1.15      www      1746: 
1.530     albertel 1747: sub mkdiruserfile {
                   1748:     my ($docuname,$docudom,$dir)=@_;
                   1749:     my $home=&homeserver($docuname,$docudom);
                   1750:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1751: }
                   1752: 
1.531     albertel 1753: sub renameuserfile {
                   1754:     my ($docuname,$docudom,$old,$new)=@_;
                   1755:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1756:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1757:                         &escape("$old").':'.&escape("$new"),$home);
                   1758:     if ($result eq 'ok') {
                   1759:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1760:             my $oldmeta = $old.'.meta';
                   1761:             my $newmeta = $new.'.meta';
                   1762:             my $metaresult = 
                   1763:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1764: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1765:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1766:             my $sqlresult = 
1.823     albertel 1767:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1768:                                         'portfolio_metadata',$group,
                   1769:                                         'delete');
1.798     raeburn  1770:         }
                   1771:     }
                   1772:     return $result;
1.531     albertel 1773: }
                   1774: 
1.14      www      1775: # ------------------------------------------------------------------------- Log
                   1776: 
                   1777: sub log {
                   1778:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1779:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1780: }
                   1781: 
                   1782: # ------------------------------------------------------------------ Course Log
1.352     www      1783: #
                   1784: # This routine flushes several buffers of non-mission-critical nature
                   1785: #
1.157     www      1786: 
                   1787: sub flushcourselogs {
1.352     www      1788:     &logthis('Flushing log buffers');
                   1789: #
                   1790: # course logs
                   1791: # This is a log of all transactions in a course, which can be used
                   1792: # for data mining purposes
                   1793: #
                   1794: # It also collects the courseid database, which lists last transaction
                   1795: # times and course titles for all courseids
                   1796: #
                   1797:     my %courseidbuffer=();
1.800     albertel 1798:     foreach my $crsid (keys %courselogs) {
1.352     www      1799:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1800: 		          &escape($courselogs{$crsid}),
                   1801: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1802: 	    delete $courselogs{$crsid};
                   1803:         } else {
                   1804:             &logthis('Failed to flush log buffer for '.$crsid);
                   1805:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1806:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1807:                         " exceeded maximum size, deleting.</font>");
                   1808:                delete $courselogs{$crsid};
                   1809:             }
1.352     www      1810:         }
                   1811:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1812:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1813: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1814:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1815:         } else {
                   1816:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1817: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1818:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1819:         }
1.191     harris41 1820:     }
1.352     www      1821: #
                   1822: # Write course id database (reverse lookup) to homeserver of courses 
                   1823: # Is used in pickcourse
                   1824: #
1.800     albertel 1825:     foreach my $crsid (keys(%courseidbuffer)) {
                   1826:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1827:     }
                   1828: #
                   1829: # File accesses
                   1830: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1831: #
1.449     matthew  1832:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1833:         if ($entry =~ /___count$/) {
                   1834:             my ($dom,$name);
1.807     albertel 1835:             ($dom,$name,undef)=
1.811     albertel 1836: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1837:             if (! defined($dom) || $dom eq '' || 
                   1838:                 ! defined($name) || $name eq '') {
1.620     albertel 1839:                 my $cid = $env{'request.course.id'};
                   1840:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1841:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1842:             }
1.450     matthew  1843:             my $value = $accesshash{$entry};
                   1844:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1845:             my %temphash=($url => $value);
1.449     matthew  1846:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1847:             if ($result eq 'ok') {
                   1848:                 delete $accesshash{$entry};
                   1849:             } elsif ($result eq 'unknown_cmd') {
                   1850:                 # Target server has old code running on it.
1.450     matthew  1851:                 my %temphash=($entry => $value);
1.449     matthew  1852:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1853:                     delete $accesshash{$entry};
                   1854:                 }
                   1855:             }
                   1856:         } else {
1.811     albertel 1857:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1858:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1859:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1860:                 delete $accesshash{$entry};
                   1861:             }
1.185     www      1862:         }
1.191     harris41 1863:     }
1.352     www      1864: #
                   1865: # Roles
                   1866: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1867: #
1.800     albertel 1868:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1869:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1870: 	    split(/\:/,$entry);
                   1871:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1872:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1873:                 $rudom,$runame) eq 'ok') {
                   1874: 	    delete $userrolehash{$entry};
                   1875:         }
                   1876:     }
1.662     raeburn  1877: #
                   1878: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1879: #
                   1880:     my %domrolebuffer = ();
                   1881:     foreach my $entry (keys %domainrolehash) {
                   1882:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1883:         if ($domrolebuffer{$rudom}) {
                   1884:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1885:                       '='.&escape($domainrolehash{$entry});
                   1886:         } else {
                   1887:             $domrolebuffer{$rudom}.=&escape($entry).
                   1888:                       '='.&escape($domainrolehash{$entry});
                   1889:         }
                   1890:         delete $domainrolehash{$entry};
                   1891:     }
                   1892:     foreach my $dom (keys(%domrolebuffer)) {
                   1893:         foreach my $tryserver (keys %libserv) {
                   1894:             if ($hostdom{$tryserver} eq $dom) {
                   1895:                 unless (&reply('domroleput:'.$dom.':'.
                   1896:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1897:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1898:                 }
                   1899:             }
                   1900:         }
                   1901:     }
1.186     www      1902:     $dumpcount++;
1.157     www      1903: }
                   1904: 
                   1905: sub courselog {
                   1906:     my $what=shift;
1.158     www      1907:     $what=time.':'.$what;
1.620     albertel 1908:     unless ($env{'request.course.id'}) { return ''; }
                   1909:     $coursedombuf{$env{'request.course.id'}}=
                   1910:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1911:     $coursenumbuf{$env{'request.course.id'}}=
                   1912:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1913:     $coursehombuf{$env{'request.course.id'}}=
                   1914:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1915:     $coursedescrbuf{$env{'request.course.id'}}=
                   1916:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1917:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1918:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1919:     $courseownerbuf{$env{'request.course.id'}}=
                   1920:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1921:     $coursetypebuf{$env{'request.course.id'}}=
                   1922:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1923:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1924: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1925:     } else {
1.620     albertel 1926: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1927:     }
1.620     albertel 1928:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1929: 	&flushcourselogs();
                   1930:     }
1.158     www      1931: }
                   1932: 
                   1933: sub courseacclog {
                   1934:     my $fnsymb=shift;
1.620     albertel 1935:     unless ($env{'request.course.id'}) { return ''; }
                   1936:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1937:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1938:         $what.=':POST';
1.583     matthew  1939:         # FIXME: Probably ought to escape things....
1.800     albertel 1940: 	foreach my $key (keys(%env)) {
                   1941:             if ($key=~/^form\.(.*)/) {
                   1942: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1943:             }
1.191     harris41 1944:         }
1.583     matthew  1945:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1946:         # FIXME: We should not be depending on a form parameter that someone
                   1947:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1948:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1949:             $what.= ':POST';
                   1950:             # FIXME: Probably ought to escape things....
                   1951:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1952:                                  'crsdiscuss') {
1.620     albertel 1953:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1954:             }
                   1955:         }
1.158     www      1956:     }
                   1957:     &courselog($what);
1.149     www      1958: }
                   1959: 
1.185     www      1960: sub countacc {
                   1961:     my $url=&declutter(shift);
1.458     matthew  1962:     return if (! defined($url) || $url eq '');
1.620     albertel 1963:     unless ($env{'request.course.id'}) { return ''; }
                   1964:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1965:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1966:     $accesshash{$key}++;
1.185     www      1967: }
1.349     www      1968: 
1.361     www      1969: sub linklog {
                   1970:     my ($from,$to)=@_;
                   1971:     $from=&declutter($from);
                   1972:     $to=&declutter($to);
                   1973:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1974:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1975: }
                   1976:   
1.349     www      1977: sub userrolelog {
                   1978:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1979:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1980:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1981:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1982:         ($trole=~/^ta/)) {
1.350     www      1983:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1984:        $userrolehash
                   1985:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1986:                     =$tend.':'.$tstart;
1.662     raeburn  1987:     }
                   1988:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1989:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1990:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1991:         ($trole=~/^sc/)) {
                   1992:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1993:        $domainrolehash
                   1994:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1995:                     = $tend.':'.$tstart;
                   1996:     }
1.351     www      1997: }
                   1998: 
                   1999: sub get_course_adv_roles {
                   2000:     my $cid=shift;
1.620     albertel 2001:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2002:     my %coursehash=&coursedescription($cid);
1.470     www      2003:     my %nothide=();
1.800     albertel 2004:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2005: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2006:     }
1.351     www      2007:     my %returnhash=();
                   2008:     my %dumphash=
                   2009:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2010:     my $now=time;
1.800     albertel 2011:     foreach my $entry (keys %dumphash) {
                   2012: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2013:         if (($tstart) && ($tstart<0)) { next; }
                   2014:         if (($tend) && ($tend<$now)) { next; }
                   2015:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2016:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2017: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2018: 	if ((&privileged($username,$domain)) && 
                   2019: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2020: 	if ($role eq 'cr') { next; }
1.351     www      2021:         my $key=&plaintext($role);
                   2022:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2023:         if ($returnhash{$key}) {
                   2024: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2025:         } else {
                   2026:             $returnhash{$key}=$username.':'.$domain;
                   2027:         }
1.400     www      2028:      }
                   2029:     return %returnhash;
                   2030: }
                   2031: 
                   2032: sub get_my_roles {
                   2033:     my ($uname,$udom)=@_;
1.620     albertel 2034:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2035:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2036:     my %dumphash=
                   2037:             &dump('nohist_userroles',$udom,$uname);
                   2038:     my %returnhash=();
                   2039:     my $now=time;
1.800     albertel 2040:     foreach my $entry (keys(%dumphash)) {
                   2041: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2042:         if (($tstart) && ($tstart<0)) { next; }
                   2043:         if (($tend) && ($tend<$now)) { next; }
                   2044:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2045:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2046: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2047:      }
                   2048:     return %returnhash;
1.399     www      2049: }
                   2050: 
                   2051: # ----------------------------------------------------- Frontpage Announcements
                   2052: #
                   2053: #
                   2054: 
                   2055: sub postannounce {
                   2056:     my ($server,$text)=@_;
                   2057:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2058:     unless ($text=~/\w/) { $text=''; }
                   2059:     return &reply('setannounce:'.&escape($text),$server);
                   2060: }
                   2061: 
                   2062: sub getannounce {
1.448     albertel 2063: 
                   2064:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2065: 	my $announcement='';
1.800     albertel 2066: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2067: 	close($fh);
1.399     www      2068: 	if ($announcement=~/\w/) { 
                   2069: 	    return 
                   2070:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2071:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2072: 	} else {
                   2073: 	    return '';
                   2074: 	}
                   2075:     } else {
                   2076: 	return '';
                   2077:     }
1.351     www      2078: }
1.353     www      2079: 
                   2080: # ---------------------------------------------------------- Course ID routines
                   2081: # Deal with domain's nohist_courseid.db files
                   2082: #
                   2083: 
                   2084: sub courseidput {
                   2085:     my ($domain,$what,$coursehome)=@_;
                   2086:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2087: }
                   2088: 
                   2089: sub courseiddump {
1.791     raeburn  2090:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2091:     my %returnhash=();
1.355     www      2092:     unless ($domfilter) { $domfilter=''; }
1.353     www      2093:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2094:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2095: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2096: 	        foreach my $line (
1.506     raeburn  2097:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2098: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2099:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2100:                                $tryserver))) {
1.800     albertel 2101: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2102:                     if (($key) && ($value)) {
1.516     raeburn  2103: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2104:                     }
1.353     www      2105:                 }
                   2106:             }
                   2107:         }
                   2108:     }
                   2109:     return %returnhash;
                   2110: }
                   2111: 
1.658     raeburn  2112: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2113: 
                   2114: sub dcmailput {
1.685     raeburn  2115:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2116:     my $status = &Apache::lonnet::critical(
1.740     www      2117:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2118:        &escape($message),$server);
1.662     raeburn  2119:     return $status;
                   2120: }
                   2121: 
1.658     raeburn  2122: sub dcmaildump {
                   2123:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2124:     my %returnhash=();
                   2125:     if (exists($domain_primary{$dom})) {
                   2126:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2127:                                                          &escape($enddate).':';
                   2128: 	my @esc_senders=map { &escape($_)} @$senders;
                   2129: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2130: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2131:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2132:             if (($key) && ($value)) {
                   2133:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2134:             }
                   2135:         }
                   2136:     }
                   2137:     return %returnhash;
                   2138: }
1.662     raeburn  2139: # ---------------------------------------------------------- Domain roles
                   2140: 
                   2141: sub get_domain_roles {
                   2142:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2143:     if (undef($startdate) || $startdate eq '') {
                   2144:         $startdate = '.';
                   2145:     }
                   2146:     if (undef($enddate) || $enddate eq '') {
                   2147:         $enddate = '.';
                   2148:     }
                   2149:     my $rolelist = join(':',@{$roles});
                   2150:     my %personnel = ();
                   2151:     foreach my $tryserver (keys(%libserv)) {
                   2152:         if ($hostdom{$tryserver} eq $dom) {
                   2153:             %{$personnel{$tryserver}}=();
1.800     albertel 2154:             foreach my $line (
1.662     raeburn  2155:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2156:                    &escape($startdate).':'.&escape($enddate).':'.
                   2157:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2158:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2159:                 if (($key) && ($value)) {
                   2160:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2161:                 }
                   2162:             }
                   2163:         }
                   2164:     }
                   2165:     return %personnel;
                   2166: }
1.658     raeburn  2167: 
1.149     www      2168: # ----------------------------------------------------------- Check out an item
                   2169: 
1.504     albertel 2170: sub get_first_access {
                   2171:     my ($type,$argsymb)=@_;
1.790     albertel 2172:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2173:     if ($argsymb) { $symb=$argsymb; }
                   2174:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2175:     if ($type eq 'map') {
                   2176: 	$res=&symbread($map);
                   2177:     } else {
                   2178: 	$res=$symb;
                   2179:     }
                   2180:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2181:     return $times{"$courseid\0$res"};
1.504     albertel 2182: }
                   2183: 
                   2184: sub set_first_access {
                   2185:     my ($type)=@_;
1.790     albertel 2186:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2187:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2188:     if ($type eq 'map') {
                   2189: 	$res=&symbread($map);
                   2190:     } else {
                   2191: 	$res=$symb;
                   2192:     }
                   2193:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2194:     if (!$firstaccess) {
1.588     albertel 2195: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2196:     }
                   2197:     return 'already_set';
1.504     albertel 2198: }
                   2199: 
1.149     www      2200: sub checkout {
                   2201:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2202:     my $now=time;
                   2203:     my $lonhost=$perlvar{'lonHostID'};
                   2204:     my $infostr=&escape(
1.234     www      2205:                  'CHECKOUTTOKEN&'.
1.149     www      2206:                  $tuname.'&'.
                   2207:                  $tudom.'&'.
                   2208:                  $tcrsid.'&'.
                   2209:                  $symb.'&'.
                   2210: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2211:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2212:     if ($token=~/^error\:/) { 
1.672     albertel 2213:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2214:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2215:                  "</font>");
                   2216:         return ''; 
                   2217:     }
                   2218: 
1.149     www      2219:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2220:     $token=~tr/a-z/A-Z/;
                   2221: 
1.153     www      2222:     my %infohash=('resource.0.outtoken' => $token,
                   2223:                   'resource.0.checkouttime' => $now,
                   2224:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2225: 
                   2226:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2227:        return '';
1.151     www      2228:     } else {
1.672     albertel 2229:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2230:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2231:                  "</font>");
1.149     www      2232:     }    
                   2233: 
                   2234:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2235:                          &escape('Checkout '.$infostr.' - '.
                   2236:                                                  $token)) ne 'ok') {
                   2237: 	return '';
1.151     www      2238:     } else {
1.672     albertel 2239:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2240:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2241:                  "</font>");
1.149     www      2242:     }
1.151     www      2243:     return $token;
1.149     www      2244: }
                   2245: 
                   2246: # ------------------------------------------------------------ Check in an item
                   2247: 
                   2248: sub checkin {
                   2249:     my $token=shift;
1.150     www      2250:     my $now=time;
                   2251:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2252:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2253:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2254:     $dtoken=~s/\W/\_/g;
1.234     www      2255:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2256:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2257: 
1.154     www      2258:     unless (($tuname) && ($tudom)) {
                   2259:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2260:         return '';
                   2261:     }
                   2262:     
                   2263:     unless (&allowed('mgr',$tcrsid)) {
                   2264:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2265:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2266:         return '';
                   2267:     }
                   2268: 
1.153     www      2269:     my %infohash=('resource.0.intoken' => $token,
                   2270:                   'resource.0.checkintime' => $now,
                   2271:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2272: 
                   2273:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2274:        return '';
                   2275:     }    
                   2276: 
                   2277:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2278:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2279: 	return '';
                   2280:     }
                   2281: 
                   2282:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2283: }
                   2284: 
                   2285: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2286: 
                   2287: sub expirespread {
                   2288:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2289:     my $cid=$env{'request.course.id'}; 
1.110     www      2290:     if ($cid) {
                   2291:        my $now=time;
                   2292:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2293:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2294:                             $env{'course.'.$cid.'.num'}.
1.110     www      2295: 	        	    ':nohist_expirationdates:'.
                   2296:                             &escape($key).'='.$now,
1.620     albertel 2297:                             $env{'course.'.$cid.'.home'})
1.110     www      2298:     }
                   2299:     return 'ok';
1.14      www      2300: }
                   2301: 
1.109     www      2302: # ----------------------------------------------------- Devalidate Spreadsheets
                   2303: 
                   2304: sub devalidate {
1.325     www      2305:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2306:     my $cid=$env{'request.course.id'}; 
1.109     www      2307:     if ($cid) {
1.391     matthew  2308:         # delete the stored spreadsheets for
                   2309:         # - the student level sheet of this user in course's homespace
                   2310:         # - the assessment level sheet for this resource 
                   2311:         #   for this user in user's homespace
1.553     albertel 2312: 	# - current conditional state info
1.325     www      2313: 	my $key=$uname.':'.$udom.':';
1.109     www      2314:         my $status=
1.299     matthew  2315: 	    &del('nohist_calculatedsheets',
1.391     matthew  2316: 		 [$key.'studentcalc:'],
1.620     albertel 2317: 		 $env{'course.'.$cid.'.domain'},
                   2318: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2319: 		.' '.
                   2320: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2321: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2322:         unless ($status eq 'ok ok') {
                   2323:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2324:                     $uname.' at '.$udom.' for '.
1.109     www      2325: 		    $symb.': '.$status);
1.133     albertel 2326:         }
1.553     albertel 2327: 	&delenv('user.state.'.$cid);
1.109     www      2328:     }
                   2329: }
                   2330: 
1.265     albertel 2331: sub get_scalar {
                   2332:     my ($string,$end) = @_;
                   2333:     my $value;
                   2334:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2335: 	$value = $1;
                   2336:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2337: 	$value = $1;
                   2338:     }
                   2339:     return &unescape($value);
                   2340: }
                   2341: 
                   2342: sub array2str {
                   2343:   my (@array) = @_;
                   2344:   my $result=&arrayref2str(\@array);
                   2345:   $result=~s/^__ARRAY_REF__//;
                   2346:   $result=~s/__END_ARRAY_REF__$//;
                   2347:   return $result;
                   2348: }
                   2349: 
1.204     albertel 2350: sub arrayref2str {
                   2351:   my ($arrayref) = @_;
1.265     albertel 2352:   my $result='__ARRAY_REF__';
1.204     albertel 2353:   foreach my $elem (@$arrayref) {
1.265     albertel 2354:     if(ref($elem) eq 'ARRAY') {
                   2355:       $result.=&arrayref2str($elem).'&';
                   2356:     } elsif(ref($elem) eq 'HASH') {
                   2357:       $result.=&hashref2str($elem).'&';
                   2358:     } elsif(ref($elem)) {
                   2359:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2360:     } else {
                   2361:       $result.=&escape($elem).'&';
                   2362:     }
                   2363:   }
                   2364:   $result=~s/\&$//;
1.265     albertel 2365:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2366:   return $result;
                   2367: }
                   2368: 
1.168     albertel 2369: sub hash2str {
1.204     albertel 2370:   my (%hash) = @_;
                   2371:   my $result=&hashref2str(\%hash);
1.265     albertel 2372:   $result=~s/^__HASH_REF__//;
                   2373:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2374:   return $result;
                   2375: }
                   2376: 
                   2377: sub hashref2str {
                   2378:   my ($hashref)=@_;
1.265     albertel 2379:   my $result='__HASH_REF__';
1.800     albertel 2380:   foreach my $key (sort(keys(%$hashref))) {
                   2381:     if (ref($key) eq 'ARRAY') {
                   2382:       $result.=&arrayref2str($key).'=';
                   2383:     } elsif (ref($key) eq 'HASH') {
                   2384:       $result.=&hashref2str($key).'=';
                   2385:     } elsif (ref($key)) {
1.265     albertel 2386:       $result.='=';
1.800     albertel 2387:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2388:     } else {
1.800     albertel 2389: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2390:     }
                   2391: 
1.800     albertel 2392:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2393:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2394:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2395:       $result.=&hashref2str($hashref->{$key}).'&';
                   2396:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2397:        $result.='&';
1.800     albertel 2398:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2399:     } else {
1.800     albertel 2400:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2401:     }
                   2402:   }
1.168     albertel 2403:   $result=~s/\&$//;
1.265     albertel 2404:   $result .= '__END_HASH_REF__';
1.168     albertel 2405:   return $result;
                   2406: }
                   2407: 
                   2408: sub str2hash {
1.265     albertel 2409:     my ($string)=@_;
                   2410:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2411:     return %$hash;
                   2412: }
                   2413: 
                   2414: sub str2hashref {
1.168     albertel 2415:   my ($string) = @_;
1.265     albertel 2416: 
                   2417:   my %hash;
                   2418: 
                   2419:   if($string !~ /^__HASH_REF__/) {
                   2420:       if (! ($string eq '' || !defined($string))) {
                   2421: 	  $hash{'error'}='Not hash reference';
                   2422:       }
                   2423:       return (\%hash, $string);
                   2424:   }
                   2425: 
                   2426:   $string =~ s/^__HASH_REF__//;
                   2427: 
                   2428:   while($string !~ /^__END_HASH_REF__/) {
                   2429:       #key
                   2430:       my $key='';
                   2431:       if($string =~ /^__HASH_REF__/) {
                   2432:           ($key, $string)=&str2hashref($string);
                   2433:           if(defined($key->{'error'})) {
                   2434:               $hash{'error'}='Bad data';
                   2435:               return (\%hash, $string);
                   2436:           }
                   2437:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2438:           ($key, $string)=&str2arrayref($string);
                   2439:           if($key->[0] eq 'Array reference error') {
                   2440:               $hash{'error'}='Bad data';
                   2441:               return (\%hash, $string);
                   2442:           }
                   2443:       } else {
                   2444:           $string =~ s/^(.*?)=//;
1.267     albertel 2445: 	  $key=&unescape($1);
1.265     albertel 2446:       }
                   2447:       $string =~ s/^=//;
                   2448: 
                   2449:       #value
                   2450:       my $value='';
                   2451:       if($string =~ /^__HASH_REF__/) {
                   2452:           ($value, $string)=&str2hashref($string);
                   2453:           if(defined($value->{'error'})) {
                   2454:               $hash{'error'}='Bad data';
                   2455:               return (\%hash, $string);
                   2456:           }
                   2457:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2458:           ($value, $string)=&str2arrayref($string);
                   2459:           if($value->[0] eq 'Array reference error') {
                   2460:               $hash{'error'}='Bad data';
                   2461:               return (\%hash, $string);
                   2462:           }
                   2463:       } else {
                   2464: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2465:       }
                   2466:       $string =~ s/^&//;
                   2467: 
                   2468:       $hash{$key}=$value;
1.204     albertel 2469:   }
1.265     albertel 2470: 
                   2471:   $string =~ s/^__END_HASH_REF__//;
                   2472: 
                   2473:   return (\%hash, $string);
1.204     albertel 2474: }
                   2475: 
                   2476: sub str2array {
1.265     albertel 2477:     my ($string)=@_;
                   2478:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2479:     return @$array;
                   2480: }
                   2481: 
                   2482: sub str2arrayref {
1.204     albertel 2483:   my ($string) = @_;
1.265     albertel 2484:   my @array;
                   2485: 
                   2486:   if($string !~ /^__ARRAY_REF__/) {
                   2487:       if (! ($string eq '' || !defined($string))) {
                   2488: 	  $array[0]='Array reference error';
                   2489:       }
                   2490:       return (\@array, $string);
                   2491:   }
                   2492: 
                   2493:   $string =~ s/^__ARRAY_REF__//;
                   2494: 
                   2495:   while($string !~ /^__END_ARRAY_REF__/) {
                   2496:       my $value='';
                   2497:       if($string =~ /^__HASH_REF__/) {
                   2498:           ($value, $string)=&str2hashref($string);
                   2499:           if(defined($value->{'error'})) {
                   2500:               $array[0] ='Array reference error';
                   2501:               return (\@array, $string);
                   2502:           }
                   2503:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2504:           ($value, $string)=&str2arrayref($string);
                   2505:           if($value->[0] eq 'Array reference error') {
                   2506:               $array[0] ='Array reference error';
                   2507:               return (\@array, $string);
                   2508:           }
                   2509:       } else {
                   2510: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2511:       }
                   2512:       $string =~ s/^&//;
                   2513: 
                   2514:       push(@array, $value);
1.191     harris41 2515:   }
1.265     albertel 2516: 
                   2517:   $string =~ s/^__END_ARRAY_REF__//;
                   2518: 
                   2519:   return (\@array, $string);
1.168     albertel 2520: }
                   2521: 
1.167     albertel 2522: # -------------------------------------------------------------------Temp Store
                   2523: 
1.168     albertel 2524: sub tmpreset {
                   2525:   my ($symb,$namespace,$domain,$stuname) = @_;
                   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: 
1.620     albertel 2532:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2533:   $namespace=~s/\//\_/g;
                   2534:   $namespace=~s/\W//g;
                   2535: 
1.620     albertel 2536:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2537:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2538:   if ($domain eq 'public' && $stuname eq 'public') {
                   2539:       $stuname=$ENV{'REMOTE_ADDR'};
                   2540:   }
1.168     albertel 2541:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2542:   my %hash;
                   2543:   if (tie(%hash,'GDBM_File',
                   2544: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2545: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2546:     foreach my $key (keys %hash) {
1.180     albertel 2547:       if ($key=~ /:$symb/) {
1.168     albertel 2548: 	delete($hash{$key});
                   2549:       }
                   2550:     }
                   2551:   }
                   2552: }
                   2553: 
1.167     albertel 2554: sub tmpstore {
1.168     albertel 2555:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2556: 
                   2557:   if (!$symb) {
                   2558:     $symb=&symbread();
1.620     albertel 2559:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2560:   }
                   2561:   $symb=escape($symb);
                   2562: 
                   2563:   if (!$namespace) {
                   2564:     # I don't think we would ever want to store this for a course.
                   2565:     # it seems this will only be used if we don't have a course.
1.620     albertel 2566:     #$namespace=$env{'request.course.id'};
1.168     albertel 2567:     #if (!$namespace) {
1.620     albertel 2568:       $namespace=$env{'request.state'};
1.168     albertel 2569:     #}
                   2570:   }
                   2571:   $namespace=~s/\//\_/g;
                   2572:   $namespace=~s/\W//g;
1.620     albertel 2573:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2574:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2575:   if ($domain eq 'public' && $stuname eq 'public') {
                   2576:       $stuname=$ENV{'REMOTE_ADDR'};
                   2577:   }
1.168     albertel 2578:   my $now=time;
                   2579:   my %hash;
                   2580:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2581:   if (tie(%hash,'GDBM_File',
                   2582: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2583: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2584:     $hash{"version:$symb"}++;
                   2585:     my $version=$hash{"version:$symb"};
                   2586:     my $allkeys=''; 
                   2587:     foreach my $key (keys(%$storehash)) {
                   2588:       $allkeys.=$key.':';
1.591     albertel 2589:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2590:     }
                   2591:     $hash{"$version:$symb:timestamp"}=$now;
                   2592:     $allkeys.='timestamp';
                   2593:     $hash{"$version:keys:$symb"}=$allkeys;
                   2594:     if (untie(%hash)) {
                   2595:       return 'ok';
                   2596:     } else {
                   2597:       return "error:$!";
                   2598:     }
                   2599:   } else {
                   2600:     return "error:$!";
                   2601:   }
                   2602: }
1.167     albertel 2603: 
1.168     albertel 2604: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2605: 
1.168     albertel 2606: sub tmprestore {
                   2607:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2608: 
1.168     albertel 2609:   if (!$symb) {
                   2610:     $symb=&symbread();
1.620     albertel 2611:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2612:   }
                   2613:   $symb=escape($symb);
                   2614: 
1.620     albertel 2615:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2616: 
1.620     albertel 2617:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2618:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2619:   if ($domain eq 'public' && $stuname eq 'public') {
                   2620:       $stuname=$ENV{'REMOTE_ADDR'};
                   2621:   }
1.168     albertel 2622:   my %returnhash;
                   2623:   $namespace=~s/\//\_/g;
                   2624:   $namespace=~s/\W//g;
                   2625:   my %hash;
                   2626:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2627:   if (tie(%hash,'GDBM_File',
                   2628: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2629: 	  &GDBM_READER(),0640)) {
1.168     albertel 2630:     my $version=$hash{"version:$symb"};
                   2631:     $returnhash{'version'}=$version;
                   2632:     my $scope;
                   2633:     for ($scope=1;$scope<=$version;$scope++) {
                   2634:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2635:       my @keys=split(/:/,$vkeys);
                   2636:       my $key;
                   2637:       $returnhash{"$scope:keys"}=$vkeys;
                   2638:       foreach $key (@keys) {
1.591     albertel 2639: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2640: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2641:       }
                   2642:     }
1.168     albertel 2643:     if (!(untie(%hash))) {
                   2644:       return "error:$!";
                   2645:     }
                   2646:   } else {
                   2647:     return "error:$!";
                   2648:   }
                   2649:   return %returnhash;
1.167     albertel 2650: }
                   2651: 
1.9       www      2652: # ----------------------------------------------------------------------- Store
                   2653: 
                   2654: sub store {
1.124     www      2655:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2656:     my $home='';
                   2657: 
1.168     albertel 2658:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2659: 
1.213     www      2660:     $symb=&symbclean($symb);
1.122     albertel 2661:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2662: 
1.620     albertel 2663:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2664:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2665: 
                   2666:     &devalidate($symb,$stuname,$domain);
1.109     www      2667: 
                   2668:     $symb=escape($symb);
1.187     www      2669:     if (!$namespace) { 
1.620     albertel 2670:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2671:           return ''; 
                   2672:        } 
                   2673:     }
1.620     albertel 2674:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2675: 
                   2676:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2677:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2678: 
1.12      www      2679:     my $namevalue='';
1.800     albertel 2680:     foreach my $key (keys(%$storehash)) {
                   2681:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2682:     }
1.12      www      2683:     $namevalue=~s/\&$//;
1.187     www      2684:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2685:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2686: }
                   2687: 
1.47      www      2688: # -------------------------------------------------------------- Critical Store
                   2689: 
                   2690: sub cstore {
1.124     www      2691:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2692:     my $home='';
                   2693: 
1.168     albertel 2694:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2695: 
1.213     www      2696:     $symb=&symbclean($symb);
1.122     albertel 2697:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2698: 
1.620     albertel 2699:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2700:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2701: 
                   2702:     &devalidate($symb,$stuname,$domain);
1.109     www      2703: 
                   2704:     $symb=escape($symb);
1.187     www      2705:     if (!$namespace) { 
1.620     albertel 2706:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2707:           return ''; 
                   2708:        } 
                   2709:     }
1.620     albertel 2710:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2711: 
                   2712:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2713:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2714: 
1.47      www      2715:     my $namevalue='';
1.800     albertel 2716:     foreach my $key (keys(%$storehash)) {
                   2717:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2718:     }
1.47      www      2719:     $namevalue=~s/\&$//;
1.187     www      2720:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2721:     return critical
                   2722:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2723: }
                   2724: 
1.9       www      2725: # --------------------------------------------------------------------- Restore
                   2726: 
                   2727: sub restore {
1.124     www      2728:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2729:     my $home='';
                   2730: 
1.168     albertel 2731:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2732: 
1.122     albertel 2733:     if (!$symb) {
                   2734:       unless ($symb=escape(&symbread())) { return ''; }
                   2735:     } else {
1.213     www      2736:       $symb=&escape(&symbclean($symb));
1.122     albertel 2737:     }
1.188     www      2738:     if (!$namespace) { 
1.620     albertel 2739:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2740:           return ''; 
                   2741:        } 
                   2742:     }
1.620     albertel 2743:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2744:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2745:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2746:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2747: 
1.12      www      2748:     my %returnhash=();
1.800     albertel 2749:     foreach my $line (split(/\&/,$answer)) {
                   2750: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2751:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2752:     }
1.75      www      2753:     my $version;
                   2754:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2755:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2756:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2757:        }
1.75      www      2758:     }
1.13      www      2759:     return %returnhash;
1.34      www      2760: }
                   2761: 
                   2762: # ---------------------------------------------------------- Course Description
                   2763: 
                   2764: sub coursedescription {
1.731     albertel 2765:     my ($courseid,$args)=@_;
1.34      www      2766:     $courseid=~s/^\///;
1.49      www      2767:     $courseid=~s/\_/\//g;
1.34      www      2768:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2769:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2770:     my $normalid=$cdomain.'_'.$cnum;
                   2771:     # need to always cache even if we get errors otherwise we keep 
                   2772:     # trying and trying and trying to get the course description.
                   2773:     my %envhash=();
                   2774:     my %returnhash=();
1.731     albertel 2775:     
                   2776:     my $expiretime=600;
                   2777:     if ($env{'request.course.id'} eq $normalid) {
                   2778: 	$expiretime=120;
                   2779:     }
                   2780: 
                   2781:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2782:     if (!$args->{'freshen_cache'}
                   2783: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2784: 	foreach my $key (keys(%env)) {
                   2785: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2786: 	    my ($setting) = $1;
                   2787: 	    $returnhash{$setting} = $env{$key};
                   2788: 	}
                   2789: 	return %returnhash;
                   2790:     }
                   2791: 
                   2792:     # get the data agin
                   2793:     if (!$args->{'one_time'}) {
                   2794: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2795:     }
1.811     albertel 2796: 
1.34      www      2797:     if ($chome ne 'no_host') {
1.302     albertel 2798:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2799:        if (!exists($returnhash{'con_lost'})) {
                   2800:            $returnhash{'home'}= $chome;
                   2801: 	   $returnhash{'domain'} = $cdomain;
                   2802: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2803:            if (!defined($returnhash{'type'})) {
                   2804:                $returnhash{'type'} = 'Course';
                   2805:            }
1.130     albertel 2806:            while (my ($name,$value) = each %returnhash) {
1.53      www      2807:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2808:            }
1.270     www      2809:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2810:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2811: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2812:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2813:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2814:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2815:        }
                   2816:     }
1.731     albertel 2817:     if (!$args->{'one_time'}) {
                   2818: 	&appenv(%envhash);
                   2819:     }
1.302     albertel 2820:     return %returnhash;
1.461     www      2821: }
                   2822: 
                   2823: # -------------------------------------------------See if a user is privileged
                   2824: 
                   2825: sub privileged {
                   2826:     my ($username,$domain)=@_;
                   2827:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2828: 			&homeserver($username,$domain));
                   2829:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2830:     my $now=time;
                   2831:     if ($rolesdump ne '') {
1.800     albertel 2832:         foreach my $entry (split(/&/,$rolesdump)) {
                   2833: 	    if ($entry!~/^rolesdef_/) {
                   2834: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2835: 		$area=~s/\_\w\w$//;
                   2836: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2837: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2838: 		    my $active=1;
                   2839: 		    if ($tend) {
                   2840: 			if ($tend<$now) { $active=0; }
                   2841: 		    }
                   2842: 		    if ($tstart) {
                   2843: 			if ($tstart>$now) { $active=0; }
                   2844: 		    }
                   2845: 		    if ($active) { return 1; }
                   2846: 		}
                   2847: 	    }
                   2848: 	}
                   2849:     }
                   2850:     return 0;
1.9       www      2851: }
1.1       albertel 2852: 
1.103     harris41 2853: # -------------------------------------------------------- Get user privileges
1.11      www      2854: 
                   2855: sub rolesinit {
                   2856:     my ($domain,$username,$authhost)=@_;
                   2857:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2858:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2859:     my %allroles=();
1.678     raeburn  2860:     my %allgroups=();   
1.11      www      2861:     my $now=time;
1.743     albertel 2862:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2863:     my $group_privs;
1.11      www      2864: 
                   2865:     if ($rolesdump ne '') {
1.800     albertel 2866:         foreach my $entry (split(/&/,$rolesdump)) {
                   2867: 	  if ($entry!~/^rolesdef_/) {
                   2868:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2869: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2870:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2871: 	    if ($role=~/^cr/) { 
1.807     albertel 2872: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2873: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2874: 		    ($tend,$tstart)=split('_',$trest);
                   2875: 		} else {
                   2876: 		    $trole=$role;
                   2877: 		}
1.678     raeburn  2878:             } elsif ($role =~ m|^gr/|) {
                   2879:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2880:                 ($trole,$group_privs) = split(/\//,$trole);
                   2881:                 $group_privs = &unescape($group_privs);
1.587     albertel 2882: 	    } else {
                   2883: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2884: 	    }
1.743     albertel 2885: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2886: 					 $username);
                   2887: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2888:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2889:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2890:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2891: 		my $spec=$trole.'.'.$area;
                   2892: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2893: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2894:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2895:                 } elsif ($trole eq 'gr') {
                   2896:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2897: 		} else {
1.567     raeburn  2898:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2899: 		}
1.12      www      2900:             }
1.662     raeburn  2901:           }
1.191     harris41 2902:         }
1.743     albertel 2903:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2904:         $userroles{'user.adv'}    = $adv;
                   2905: 	$userroles{'user.author'} = $author;
1.620     albertel 2906:         $env{'user.adv'}=$adv;
1.11      www      2907:     }
1.743     albertel 2908:     return \%userroles;  
1.11      www      2909: }
                   2910: 
1.567     raeburn  2911: sub set_arearole {
                   2912:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2913: # log the associated role with the area
                   2914:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2915:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2916: }
                   2917: 
                   2918: sub custom_roleprivs {
                   2919:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2920:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2921:     my $homsvr=homeserver($rauthor,$rdomain);
                   2922:     if ($hostname{$homsvr} ne '') {
                   2923:         my ($rdummy,$roledef)=
                   2924:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2925:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2926:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2927:             if (defined($syspriv)) {
                   2928:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2929:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2930:             }
                   2931:             if ($tdomain ne '') {
                   2932:                 if (defined($dompriv)) {
                   2933:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2934:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2935:                 }
                   2936:                 if (($trest ne '') && (defined($coursepriv))) {
                   2937:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2938:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2939:                 }
                   2940:             }
                   2941:         }
                   2942:     }
                   2943: }
                   2944: 
1.678     raeburn  2945: sub group_roleprivs {
                   2946:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2947:     my $access = 1;
                   2948:     my $now = time;
                   2949:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2950:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2951:     if ($access) {
1.811     albertel 2952:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2953:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2954:     }
                   2955: }
1.567     raeburn  2956: 
                   2957: sub standard_roleprivs {
                   2958:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2959:     if (defined($pr{$trole.':s'})) {
                   2960:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2961:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2962:     }
                   2963:     if ($tdomain ne '') {
                   2964:         if (defined($pr{$trole.':d'})) {
                   2965:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2966:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2967:         }
                   2968:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2969:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2970:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2971:         }
                   2972:     }
                   2973: }
                   2974: 
                   2975: sub set_userprivs {
1.678     raeburn  2976:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2977:     my $author=0;
                   2978:     my $adv=0;
1.678     raeburn  2979:     my %grouproles = ();
                   2980:     if (keys(%{$allgroups}) > 0) {
                   2981:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2982:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2983:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2984:                 $trole = $1;
                   2985:                 $area = $2;
1.681     raeburn  2986:                 $sec = $3;
                   2987:                 $extendedarea = $area.$sec;
                   2988:                 if (exists($$allgroups{$area})) {
                   2989:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2990:                         my $spec = $trole.'.'.$extendedarea;
                   2991:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2992:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2993:                     }
                   2994:                 }
                   2995:             }
                   2996:         }
                   2997:     }
1.800     albertel 2998:     foreach my $group (keys(%grouproles)) {
                   2999:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3000:     }
1.800     albertel 3001:     foreach my $role (keys(%{$allroles})) {
                   3002:         my %thesepriv;
                   3003:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3004:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3005:             if ($item ne '') {
                   3006:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3007:                 if ($restrictions eq '') {
                   3008:                     $thesepriv{$privilege}='F';
                   3009:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3010:                     $thesepriv{$privilege}.=$restrictions;
                   3011:                 }
                   3012:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3013:             }
                   3014:         }
                   3015:         my $thesestr='';
1.800     albertel 3016:         foreach my $priv (keys(%thesepriv)) {
                   3017: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3018: 	}
                   3019:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3020:     }
                   3021:     return ($author,$adv);
                   3022: }
                   3023: 
1.12      www      3024: # --------------------------------------------------------------- get interface
                   3025: 
                   3026: sub get {
1.131     albertel 3027:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3028:    my $items='';
1.800     albertel 3029:    foreach my $item (@$storearr) {
                   3030:        $items.=&escape($item).'&';
1.191     harris41 3031:    }
1.12      www      3032:    $items=~s/\&$//;
1.620     albertel 3033:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3034:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3035:    my $uhome=&homeserver($uname,$udomain);
                   3036: 
1.133     albertel 3037:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3038:    my @pairs=split(/\&/,$rep);
1.273     albertel 3039:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3040:      return @pairs;
                   3041:    }
1.15      www      3042:    my %returnhash=();
1.42      www      3043:    my $i=0;
1.800     albertel 3044:    foreach my $item (@$storearr) {
                   3045:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3046:       $i++;
1.191     harris41 3047:    }
1.15      www      3048:    return %returnhash;
1.27      www      3049: }
                   3050: 
                   3051: # --------------------------------------------------------------- del interface
                   3052: 
                   3053: sub del {
1.133     albertel 3054:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3055:    my $items='';
1.800     albertel 3056:    foreach my $item (@$storearr) {
                   3057:        $items.=&escape($item).'&';
1.191     harris41 3058:    }
1.27      www      3059:    $items=~s/\&$//;
1.620     albertel 3060:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3061:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3062:    my $uhome=&homeserver($uname,$udomain);
                   3063: 
                   3064:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3065: }
                   3066: 
                   3067: # -------------------------------------------------------------- dump interface
                   3068: 
                   3069: sub dump {
1.755     albertel 3070:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3071:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3072:     if (!$uname) { $uname=$env{'user.name'}; }
                   3073:     my $uhome=&homeserver($uname,$udomain);
                   3074:     if ($regexp) {
                   3075: 	$regexp=&escape($regexp);
                   3076:     } else {
                   3077: 	$regexp='.';
                   3078:     }
                   3079:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3080:     my @pairs=split(/\&/,$rep);
                   3081:     my %returnhash=();
                   3082:     foreach my $item (@pairs) {
                   3083: 	my ($key,$value)=split(/=/,$item,2);
                   3084: 	$key = &unescape($key);
                   3085: 	next if ($key =~ /^error: 2 /);
                   3086: 	$returnhash{$key}=&thaw_unescape($value);
                   3087:     }
                   3088:     return %returnhash;
1.407     www      3089: }
                   3090: 
1.717     albertel 3091: # --------------------------------------------------------- dumpstore interface
                   3092: 
                   3093: sub dumpstore {
                   3094:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3095:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3096:    if (!$uname) { $uname=$env{'user.name'}; }
                   3097:    my $uhome=&homeserver($uname,$udomain);
                   3098:    if ($regexp) {
                   3099:        $regexp=&escape($regexp);
                   3100:    } else {
                   3101:        $regexp='.';
                   3102:    }
                   3103:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3104:    my @pairs=split(/\&/,$rep);
                   3105:    my %returnhash=();
                   3106:    foreach my $item (@pairs) {
                   3107:        my ($key,$value)=split(/=/,$item,2);
                   3108:        next if ($key =~ /^error: 2 /);
                   3109:        $returnhash{$key}=&thaw_unescape($value);
                   3110:    }
                   3111:    return %returnhash;
1.717     albertel 3112: }
                   3113: 
1.407     www      3114: # -------------------------------------------------------------- keys interface
                   3115: 
                   3116: sub getkeys {
                   3117:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3118:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3119:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3120:    my $uhome=&homeserver($uname,$udomain);
                   3121:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3122:    my @keyarray=();
1.800     albertel 3123:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3124:       next if ($key =~ /^error: 2 /);
1.800     albertel 3125:       push(@keyarray,&unescape($key));
1.407     www      3126:    }
                   3127:    return @keyarray;
1.318     matthew  3128: }
                   3129: 
1.319     matthew  3130: # --------------------------------------------------------------- currentdump
                   3131: sub currentdump {
1.328     matthew  3132:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3133:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3134:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3135:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3136:    my $uhome = &homeserver($sname,$sdom);
                   3137:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3138:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3139:    #
1.318     matthew  3140:    my %returnhash=();
1.319     matthew  3141:    #
                   3142:    if ($rep eq "unknown_cmd") { 
                   3143:        # an old lond will not know currentdump
                   3144:        # Do a dump and make it look like a currentdump
1.822     albertel 3145:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3146:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3147:        my %hash = @tmp;
                   3148:        @tmp=();
1.424     matthew  3149:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3150:    } else {
                   3151:        my @pairs=split(/\&/,$rep);
1.800     albertel 3152:        foreach my $pair (@pairs) {
                   3153:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3154:            my ($symb,$param) = split(/:/,$key);
                   3155:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3156:                                                         &thaw_unescape($value);
1.319     matthew  3157:        }
1.191     harris41 3158:    }
1.12      www      3159:    return %returnhash;
1.424     matthew  3160: }
                   3161: 
                   3162: sub convert_dump_to_currentdump{
                   3163:     my %hash = %{shift()};
                   3164:     my %returnhash;
                   3165:     # Code ripped from lond, essentially.  The only difference
                   3166:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3167:     # we might run in to problems with parameter names =~ /^v\./
                   3168:     while (my ($key,$value) = each(%hash)) {
                   3169:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3170: 	$symb  = &unescape($symb);
                   3171: 	$param = &unescape($param);
1.424     matthew  3172:         next if ($v eq 'version' || $symb eq 'keys');
                   3173:         next if (exists($returnhash{$symb}) &&
                   3174:                  exists($returnhash{$symb}->{$param}) &&
                   3175:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3176:         $returnhash{$symb}->{$param}=$value;
                   3177:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3178:     }
                   3179:     #
                   3180:     # Remove all of the keys in the hashes which keep track of
                   3181:     # the version of the parameter.
                   3182:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3183:         # use a foreach because we are going to delete from the hash.
                   3184:         foreach my $key (keys(%$param_hash)) {
                   3185:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3186:         }
                   3187:     }
                   3188:     return \%returnhash;
1.12      www      3189: }
                   3190: 
1.627     albertel 3191: # ------------------------------------------------------ critical inc interface
                   3192: 
                   3193: sub cinc {
                   3194:     return &inc(@_,'critical');
                   3195: }
                   3196: 
1.449     matthew  3197: # --------------------------------------------------------------- inc interface
                   3198: 
                   3199: sub inc {
1.627     albertel 3200:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3201:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3202:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3203:     my $uhome=&homeserver($uname,$udomain);
                   3204:     my $items='';
                   3205:     if (! ref($store)) {
                   3206:         # got a single value, so use that instead
                   3207:         $items = &escape($store).'=&';
                   3208:     } elsif (ref($store) eq 'SCALAR') {
                   3209:         $items = &escape($$store).'=&';        
                   3210:     } elsif (ref($store) eq 'ARRAY') {
                   3211:         $items = join('=&',map {&escape($_);} @{$store});
                   3212:     } elsif (ref($store) eq 'HASH') {
                   3213:         while (my($key,$value) = each(%{$store})) {
                   3214:             $items.= &escape($key).'='.&escape($value).'&';
                   3215:         }
                   3216:     }
                   3217:     $items=~s/\&$//;
1.627     albertel 3218:     if ($critical) {
                   3219: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3220:     } else {
                   3221: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3222:     }
1.449     matthew  3223: }
                   3224: 
1.12      www      3225: # --------------------------------------------------------------- put interface
                   3226: 
                   3227: sub put {
1.134     albertel 3228:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3229:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3230:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3231:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3232:    my $items='';
1.800     albertel 3233:    foreach my $item (keys(%$storehash)) {
                   3234:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3235:    }
1.12      www      3236:    $items=~s/\&$//;
1.134     albertel 3237:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3238: }
                   3239: 
1.631     albertel 3240: # ------------------------------------------------------------ newput interface
                   3241: 
                   3242: sub newput {
                   3243:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3244:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3245:    if (!$uname) { $uname=$env{'user.name'}; }
                   3246:    my $uhome=&homeserver($uname,$udomain);
                   3247:    my $items='';
                   3248:    foreach my $key (keys(%$storehash)) {
                   3249:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3250:    }
                   3251:    $items=~s/\&$//;
                   3252:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3253: }
                   3254: 
                   3255: # ---------------------------------------------------------  putstore interface
                   3256: 
1.524     raeburn  3257: sub putstore {
1.715     albertel 3258:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3259:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3260:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3261:    my $uhome=&homeserver($uname,$udomain);
                   3262:    my $items='';
1.715     albertel 3263:    foreach my $key (keys(%$storehash)) {
                   3264:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3265:    }
1.715     albertel 3266:    $items=~s/\&$//;
1.716     albertel 3267:    my $esc_symb=&escape($symb);
                   3268:    my $esc_v=&escape($version);
1.715     albertel 3269:    my $reply =
1.716     albertel 3270:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3271: 	      $uhome);
                   3272:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3273:        # gfall back to way things use to be done
1.715     albertel 3274:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3275: 			    $uname);
1.524     raeburn  3276:    }
1.715     albertel 3277:    return $reply;
                   3278: }
                   3279: 
                   3280: sub old_putstore {
1.716     albertel 3281:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3282:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3283:     if (!$uname) { $uname=$env{'user.name'}; }
                   3284:     my $uhome=&homeserver($uname,$udomain);
                   3285:     my %newstorehash;
1.800     albertel 3286:     foreach my $item (keys(%$storehash)) {
                   3287: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3288: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3289:     }
                   3290:     my $items='';
                   3291:     my %allitems = ();
1.800     albertel 3292:     foreach my $item (keys(%newstorehash)) {
                   3293: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3294: 	    my $key = $1.':keys:'.$2;
                   3295: 	    $allitems{$key} .= $3.':';
                   3296: 	}
1.800     albertel 3297: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3298:     }
1.800     albertel 3299:     foreach my $item (keys(%allitems)) {
                   3300: 	$allitems{$item} =~ s/\:$//;
                   3301: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3302:     }
                   3303:     $items=~s/\&$//;
                   3304:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3305: }
                   3306: 
1.47      www      3307: # ------------------------------------------------------ critical put interface
                   3308: 
                   3309: sub cput {
1.134     albertel 3310:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3311:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3312:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3313:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3314:    my $items='';
1.800     albertel 3315:    foreach my $item (keys(%$storehash)) {
                   3316:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3317:    }
1.47      www      3318:    $items=~s/\&$//;
1.134     albertel 3319:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3320: }
                   3321: 
                   3322: # -------------------------------------------------------------- eget interface
                   3323: 
                   3324: sub eget {
1.133     albertel 3325:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3326:    my $items='';
1.800     albertel 3327:    foreach my $item (@$storearr) {
                   3328:        $items.=&escape($item).'&';
1.191     harris41 3329:    }
1.12      www      3330:    $items=~s/\&$//;
1.620     albertel 3331:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3332:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3333:    my $uhome=&homeserver($uname,$udomain);
                   3334:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3335:    my @pairs=split(/\&/,$rep);
                   3336:    my %returnhash=();
1.42      www      3337:    my $i=0;
1.800     albertel 3338:    foreach my $item (@$storearr) {
                   3339:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3340:       $i++;
1.191     harris41 3341:    }
1.12      www      3342:    return %returnhash;
                   3343: }
                   3344: 
1.667     albertel 3345: # ------------------------------------------------------------ tmpput interface
                   3346: sub tmpput {
1.802     raeburn  3347:     my ($storehash,$server,$context)=@_;
1.667     albertel 3348:     my $items='';
1.800     albertel 3349:     foreach my $item (keys(%$storehash)) {
                   3350: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3351:     }
                   3352:     $items=~s/\&$//;
1.802     raeburn  3353:     if (defined($context)) {
                   3354:         $items .= ':'.&escape($context);
                   3355:     }
1.667     albertel 3356:     return &reply("tmpput:$items",$server);
                   3357: }
                   3358: 
                   3359: # ------------------------------------------------------------ tmpget interface
                   3360: sub tmpget {
1.688     albertel 3361:     my ($token,$server)=@_;
                   3362:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3363:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3364:     my %returnhash;
                   3365:     foreach my $item (split(/\&/,$rep)) {
                   3366: 	my ($key,$value)=split(/=/,$item);
                   3367: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3368:     }
                   3369:     return %returnhash;
                   3370: }
                   3371: 
1.688     albertel 3372: # ------------------------------------------------------------ tmpget interface
                   3373: sub tmpdel {
                   3374:     my ($token,$server)=@_;
                   3375:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3376:     return &reply("tmpdel:$token",$server);
                   3377: }
                   3378: 
1.765     albertel 3379: # -------------------------------------------------- portfolio access checking
                   3380: 
                   3381: sub portfolio_access {
1.766     albertel 3382:     my ($requrl) = @_;
1.765     albertel 3383:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3384:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3385:     if ($result) {
                   3386:         my %setters;
                   3387:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3388:             my ($startblock,$endblock) =
                   3389:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3390:             if ($startblock && $endblock) {
                   3391:                 return 'B';
                   3392:             }
                   3393:         } else {
                   3394:             my ($startblock,$endblock) =
                   3395:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3396:             if ($startblock && $endblock) {
                   3397:                 return 'B';
                   3398:             }
                   3399:         }
                   3400:     }
1.765     albertel 3401:     if ($result eq 'ok') {
1.766     albertel 3402:        return 'F';
1.765     albertel 3403:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3404:        return 'A';
1.765     albertel 3405:     }
1.766     albertel 3406:     return '';
1.765     albertel 3407: }
                   3408: 
                   3409: sub get_portfolio_access {
1.767     albertel 3410:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3411: 
                   3412:     if (!ref($access_hash)) {
                   3413: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3414: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3415: 						   $file_name);
                   3416: 	$access_hash = $access_controls{$file_name};
                   3417:     }
                   3418: 
1.765     albertel 3419:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3420:     my $now = time;
                   3421:     if (ref($access_hash) eq 'HASH') {
                   3422:         foreach my $key (keys(%{$access_hash})) {
                   3423:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3424:             if ($start > $now) {
                   3425:                 next;
                   3426:             }
                   3427:             if ($end && $end<$now) {
                   3428:                 next;
                   3429:             }
                   3430:             if ($scope eq 'public') {
                   3431:                 $public = $key;
                   3432:                 last;
                   3433:             } elsif ($scope eq 'guest') {
                   3434:                 $guest = $key;
                   3435:             } elsif ($scope eq 'domains') {
                   3436:                 push(@domains,$key);
                   3437:             } elsif ($scope eq 'users') {
                   3438:                 push(@users,$key);
                   3439:             } elsif ($scope eq 'course') {
                   3440:                 push(@courses,$key);
                   3441:             } elsif ($scope eq 'group') {
                   3442:                 push(@groups,$key);
                   3443:             }
                   3444:         }
                   3445:         if ($public) {
                   3446:             return 'ok';
                   3447:         }
                   3448:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3449:             if ($guest) {
                   3450:                 return $guest;
                   3451:             }
                   3452:         } else {
                   3453:             if (@domains > 0) {
                   3454:                 foreach my $domkey (@domains) {
                   3455:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3456:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3457:                             return 'ok';
                   3458:                         }
                   3459:                     }
                   3460:                 }
                   3461:             }
                   3462:             if (@users > 0) {
                   3463:                 foreach my $userkey (@users) {
                   3464:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3465:                         return 'ok';
                   3466:                     }
                   3467:                 }
                   3468:             }
                   3469:             my %roleshash;
                   3470:             my @courses_and_groups = @courses;
                   3471:             push(@courses_and_groups,@groups); 
                   3472:             if (@courses_and_groups > 0) {
                   3473:                 my (%allgroups,%allroles); 
                   3474:                 my ($start,$end,$role,$sec,$group);
                   3475:                 foreach my $envkey (%env) {
1.811     albertel 3476:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3477:                         my $cid = $2.'_'.$3; 
                   3478:                         if ($1 eq 'gr') {
                   3479:                             $group = $4;
                   3480:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3481:                         } else {
                   3482:                             if ($4 eq '') {
                   3483:                                 $sec = 'none';
                   3484:                             } else {
                   3485:                                 $sec = $4;
                   3486:                             }
                   3487:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3488:                         }
1.811     albertel 3489:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3490:                         my $cid = $2.'_'.$3;
                   3491:                         if ($4 eq '') {
                   3492:                             $sec = 'none';
                   3493:                         } else {
                   3494:                             $sec = $4;
                   3495:                         }
                   3496:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3497:                     }
                   3498:                 }
                   3499:                 if (keys(%allroles) == 0) {
                   3500:                     return;
                   3501:                 }
                   3502:                 foreach my $key (@courses_and_groups) {
                   3503:                     my %content = %{$$access_hash{$key}};
                   3504:                     my $cnum = $content{'number'};
                   3505:                     my $cdom = $content{'domain'};
                   3506:                     my $cid = $cdom.'_'.$cnum;
                   3507:                     if (!exists($allroles{$cid})) {
                   3508:                         next;
                   3509:                     }    
                   3510:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3511:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3512:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3513:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3514:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3515:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3516:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3517:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3518:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3519:                                         if (grep/^all$/,@sections) {
                   3520:                                             return 'ok';
                   3521:                                         } else {
                   3522:                                             if (grep/^$sec$/,@sections) {
                   3523:                                                 return 'ok';
                   3524:                                             }
                   3525:                                         }
                   3526:                                     }
                   3527:                                 }
                   3528:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3529:                                     if (grep/^none$/,@groups) {
                   3530:                                         return 'ok';
                   3531:                                     }
                   3532:                                 } else {
                   3533:                                     if (grep/^all$/,@groups) {
                   3534:                                         return 'ok';
                   3535:                                     } 
                   3536:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3537:                                         if (grep/^$group$/,@groups) {
                   3538:                                             return 'ok';
                   3539:                                         }
                   3540:                                     }
                   3541:                                 } 
                   3542:                             }
                   3543:                         }
                   3544:                     }
                   3545:                 }
                   3546:             }
                   3547:             if ($guest) {
                   3548:                 return $guest;
                   3549:             }
                   3550:         }
                   3551:     }
                   3552:     return;
                   3553: }
                   3554: 
                   3555: sub course_group_datechecker {
                   3556:     my ($dates,$now,$status) = @_;
                   3557:     my ($start,$end) = split(/\./,$dates);
                   3558:     if (!$start && !$end) {
                   3559:         return 'ok';
                   3560:     }
                   3561:     if (grep/^active$/,@{$status}) {
                   3562:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3563:             return 'ok';
                   3564:         }
                   3565:     }
                   3566:     if (grep/^previous$/,@{$status}) {
                   3567:         if ($end > $now ) {
                   3568:             return 'ok';
                   3569:         }
                   3570:     }
                   3571:     if (grep/^future$/,@{$status}) {
                   3572:         if ($start > $now) {
                   3573:             return 'ok';
                   3574:         }
                   3575:     }
                   3576:     return; 
                   3577: }
                   3578: 
                   3579: sub parse_portfolio_url {
                   3580:     my ($url) = @_;
                   3581: 
                   3582:     my ($type,$udom,$unum,$group,$file_name);
                   3583:     
1.823     albertel 3584:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3585: 	$type = 1;
                   3586:         $udom = $1;
                   3587:         $unum = $2;
                   3588:         $file_name = $3;
1.823     albertel 3589:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3590: 	$type = 2;
                   3591:         $udom = $1;
                   3592:         $unum = $2;
                   3593:         $group = $3;
                   3594:         $file_name = $3.'/'.$4;
                   3595:     }
                   3596:     if (wantarray) {
                   3597: 	return ($type,$udom,$unum,$file_name,$group);
                   3598:     }
                   3599:     return $type;
                   3600: }
                   3601: 
                   3602: sub is_portfolio_url {
                   3603:     my ($url) = @_;
                   3604:     return scalar(&parse_portfolio_url($url));
                   3605: }
                   3606: 
1.798     raeburn  3607: sub is_portfolio_file {
                   3608:     my ($file) = @_;
1.820     raeburn  3609:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3610:         return 1;
                   3611:     }
                   3612:     return;
                   3613: }
                   3614: 
                   3615: 
1.341     www      3616: # ---------------------------------------------- Custom access rule evaluation
                   3617: 
                   3618: sub customaccess {
                   3619:     my ($priv,$uri)=@_;
1.807     albertel 3620:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3621:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3622:     $udom = &LONCAPA::clean_domain($udom);
                   3623:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3624:     my $access=0;
1.800     albertel 3625:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3626: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3627:         if ($role) {
                   3628: 	   if ($role ne $urole) { next; }
                   3629:         }
1.800     albertel 3630:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3631:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3632:             if ($tdom) {
                   3633: 		if ($tdom ne $udom) { next; }
                   3634:             }
                   3635:             if ($tcrs) {
                   3636: 		if ($tcrs ne $ucrs) { next; }
                   3637:             }
                   3638:             if ($tsec) {
                   3639: 		if ($tsec ne $usec) { next; }
                   3640:             }
                   3641:             $access=($effect eq 'allow');
                   3642:             last;
1.342     www      3643:         }
1.402     bowersj2 3644: 	if ($realm eq '' && $role eq '') {
                   3645:             $access=($effect eq 'allow');
                   3646: 	}
1.341     www      3647:     }
                   3648:     return $access;
                   3649: }
                   3650: 
1.103     harris41 3651: # ------------------------------------------------- Check for a user privilege
1.12      www      3652: 
                   3653: sub allowed {
1.810     raeburn  3654:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3655:     my $ver_orguri=$uri;
1.439     www      3656:     $uri=&deversion($uri);
1.152     www      3657:     my $orguri=$uri;
1.52      www      3658:     $uri=&declutter($uri);
1.809     raeburn  3659: 
1.810     raeburn  3660:     if ($priv eq 'evb') {
                   3661: # Evade communication block restrictions for specified role in a course
                   3662:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3663:             return $1;
                   3664:         } else {
                   3665:             return;
                   3666:         }
                   3667:     }
                   3668: 
1.620     albertel 3669:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3670: # Free bre access to adm and meta resources
1.775     albertel 3671:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3672: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3673: 	&& ($priv eq 'bre')) {
1.14      www      3674: 	return 'F';
1.159     www      3675:     }
                   3676: 
1.545     banghart 3677: # Free bre access to user's own portfolio contents
1.714     raeburn  3678:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3679:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3680: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3681:         my %setters;
                   3682:         my ($startblock,$endblock) = 
                   3683:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3684:         if ($startblock && $endblock) {
                   3685:             return 'B';
                   3686:         } else {
                   3687:             return 'F';
                   3688:         }
1.545     banghart 3689:     }
                   3690: 
1.762     raeburn  3691: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3692:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3693:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3694:         if (exists($env{'request.course.id'})) {
                   3695:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3696:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3697:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3698:                 my $courseprivid=$env{'request.course.id'};
                   3699:                 $courseprivid=~s/\_/\//;
                   3700:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3701:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3702:                     return $1; 
1.762     raeburn  3703:                 } else {
                   3704:                     if ($env{'request.course.sec'}) {
                   3705:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3706:                     }
                   3707:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3708:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3709:                         return $2;
                   3710:                     }
1.714     raeburn  3711:                 }
                   3712:             }
                   3713:         }
                   3714:     }
                   3715: 
1.159     www      3716: # Free bre to public access
                   3717: 
                   3718:     if ($priv eq 'bre') {
1.238     www      3719:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3720: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3721:            return 'F'; 
                   3722:         }
1.238     www      3723:         if ($copyright eq 'priv') {
                   3724:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3725: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3726: 		return '';
                   3727:             }
                   3728:         }
                   3729:         if ($copyright eq 'domain') {
                   3730:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3731: 	    unless (($env{'user.domain'} eq $1) ||
                   3732:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3733: 		return '';
                   3734:             }
1.262     matthew  3735:         }
1.620     albertel 3736:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3737:             # Library role, so allow browsing of resources in this domain.
                   3738:             return 'F';
1.238     www      3739:         }
1.341     www      3740:         if ($copyright eq 'custom') {
                   3741: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3742:         }
1.14      www      3743:     }
1.264     matthew  3744:     # Domain coordinator is trying to create a course
1.620     albertel 3745:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3746:         # uri is the requested domain in this case.
                   3747:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3748:         # a role of dc for the domain in question.
1.620     albertel 3749:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3750:     }
1.29      www      3751: 
1.52      www      3752:     my $thisallowed='';
                   3753:     my $statecond=0;
                   3754:     my $courseprivid='';
                   3755: 
                   3756: # Course
                   3757: 
1.620     albertel 3758:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3759:        $thisallowed.=$1;
                   3760:     }
1.29      www      3761: 
1.52      www      3762: # Domain
                   3763: 
1.620     albertel 3764:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3765:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3766:        $thisallowed.=$1;
                   3767:     }
1.52      www      3768: 
                   3769: # Course: uri itself is a course
1.66      www      3770:     my $courseuri=$uri;
                   3771:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3772:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3773: 
1.620     albertel 3774:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3775:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3776:        $thisallowed.=$1;
                   3777:     }
1.29      www      3778: 
1.665     albertel 3779: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3780: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3781:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3782: 	$thisallowed='';
1.671     raeburn  3783:         my ($match)=&is_on_map($uri);
                   3784:         if ($match) {
                   3785:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3786:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3787:                 $thisallowed.=$1;
                   3788:             }
                   3789:         } else {
1.705     albertel 3790:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3791:             if ($refuri) {
                   3792:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3793:                     $thisallowed='F';
1.671     raeburn  3794:                 } else {
                   3795:                     $refuri=&declutter($refuri);
                   3796:                     my ($match) = &is_on_map($refuri);
                   3797:                     if ($match) {
                   3798:                         $thisallowed='F';
                   3799:                     }
1.669     raeburn  3800:                 }
1.671     raeburn  3801:             }
                   3802:         }
1.314     www      3803:     }
1.492     albertel 3804: 
1.766     albertel 3805:     if ($priv eq 'bre'
                   3806: 	&& $thisallowed ne 'F' 
                   3807: 	&& $thisallowed ne '2'
                   3808: 	&& &is_portfolio_url($uri)) {
                   3809: 	$thisallowed = &portfolio_access($uri);
                   3810:     }
                   3811:     
1.52      www      3812: # Full access at system, domain or course-wide level? Exit.
1.29      www      3813: 
                   3814:     if ($thisallowed=~/F/) {
                   3815: 	return 'F';
                   3816:     }
                   3817: 
1.52      www      3818: # If this is generating or modifying users, exit with special codes
1.29      www      3819: 
1.643     www      3820:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3821: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3822: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3823: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3824: 	    unless ($auname) { return $thisallowed; }
                   3825: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3826: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3827: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3828: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3829: 	}
1.52      www      3830: 	return $thisallowed;
                   3831:     }
                   3832: #
1.103     harris41 3833: # Gathered so far: system, domain and course wide privileges
1.52      www      3834: #
                   3835: # Course: See if uri or referer is an individual resource that is part of 
                   3836: # the course
                   3837: 
1.620     albertel 3838:     if ($env{'request.course.id'}) {
1.232     www      3839: 
1.620     albertel 3840:        $courseprivid=$env{'request.course.id'};
                   3841:        if ($env{'request.course.sec'}) {
                   3842:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3843:        }
                   3844:        $courseprivid=~s/\_/\//;
                   3845:        my $checkreferer=1;
1.232     www      3846:        my ($match,$cond)=&is_on_map($uri);
                   3847:        if ($match) {
                   3848:            $statecond=$cond;
1.620     albertel 3849:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3850:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3851:                $thisallowed.=$1;
                   3852:                $checkreferer=0;
                   3853:            }
1.29      www      3854:        }
1.83      www      3855:        
1.148     www      3856:        if ($checkreferer) {
1.620     albertel 3857: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3858:             unless ($refuri) {
1.800     albertel 3859:                 foreach my $key (keys(%env)) {
                   3860: 		    if ($key=~/^httpref\..*\*/) {
                   3861: 			my $pattern=$key;
1.156     www      3862:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3863:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3864:                         $pattern=~s/\//\\\//g;
1.152     www      3865:                         if ($orguri=~/$pattern/) {
1.800     albertel 3866: 			    $refuri=$env{$key};
1.148     www      3867:                         }
                   3868:                     }
1.191     harris41 3869:                 }
1.148     www      3870:             }
1.232     www      3871: 
1.148     www      3872:          if ($refuri) { 
1.152     www      3873: 	  $refuri=&declutter($refuri);
1.232     www      3874:           my ($match,$cond)=&is_on_map($refuri);
                   3875:             if ($match) {
                   3876:               my $refstatecond=$cond;
1.620     albertel 3877:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3878:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3879:                   $thisallowed.=$1;
1.53      www      3880:                   $uri=$refuri;
                   3881:                   $statecond=$refstatecond;
1.52      www      3882:               }
                   3883:           }
1.148     www      3884:         }
1.29      www      3885:        }
1.52      www      3886:    }
1.29      www      3887: 
1.52      www      3888: #
1.103     harris41 3889: # Gathered now: all privileges that could apply, and condition number
1.52      www      3890: # 
                   3891: #
                   3892: # Full or no access?
                   3893: #
1.29      www      3894: 
1.52      www      3895:     if ($thisallowed=~/F/) {
                   3896: 	return 'F';
                   3897:     }
1.29      www      3898: 
1.52      www      3899:     unless ($thisallowed) {
                   3900:         return '';
                   3901:     }
1.29      www      3902: 
1.52      www      3903: # Restrictions exist, deal with them
                   3904: #
                   3905: #   C:according to course preferences
                   3906: #   R:according to resource settings
                   3907: #   L:unless locked
                   3908: #   X:according to user session state
                   3909: #
                   3910: 
                   3911: # Possibly locked functionality, check all courses
1.54      www      3912: # Locks might take effect only after 10 minutes cache expiration for other
                   3913: # courses, and 2 minutes for current course
1.52      www      3914: 
                   3915:     my $envkey;
                   3916:     if ($thisallowed=~/L/) {
1.620     albertel 3917:         foreach $envkey (keys %env) {
1.54      www      3918:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3919:                my $courseid=$2;
                   3920:                my $roleid=$1.'.'.$2;
1.92      www      3921:                $courseid=~s/^\///;
1.54      www      3922:                my $expiretime=600;
1.620     albertel 3923:                if ($env{'request.role'} eq $roleid) {
1.54      www      3924: 		  $expiretime=120;
                   3925:                }
                   3926: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3927:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3928:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3929: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3930:                }
1.620     albertel 3931:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3932:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3933: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3934:                        &log($env{'user.domain'},$env{'user.name'},
                   3935:                             $env{'user.home'},
1.57      www      3936:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3937:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3938:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3939: 		       return '';
                   3940:                    }
                   3941:                }
1.620     albertel 3942:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3943:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3944: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3945:                        &log($env{'user.domain'},$env{'user.name'},
                   3946:                             $env{'user.home'},
1.57      www      3947:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3948:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3949:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3950: 		       return '';
                   3951:                    }
                   3952:                }
                   3953: 	   }
1.29      www      3954:        }
1.52      www      3955:     }
                   3956:    
                   3957: #
                   3958: # Rest of the restrictions depend on selected course
                   3959: #
                   3960: 
1.620     albertel 3961:     unless ($env{'request.course.id'}) {
1.766     albertel 3962: 	if ($thisallowed eq 'A') {
                   3963: 	    return 'A';
1.814     raeburn  3964:         } elsif ($thisallowed eq 'B') {
                   3965:             return 'B';
1.766     albertel 3966: 	} else {
                   3967: 	    return '1';
                   3968: 	}
1.52      www      3969:     }
1.29      www      3970: 
1.52      www      3971: #
                   3972: # Now user is definitely in a course
                   3973: #
1.53      www      3974: 
                   3975: 
                   3976: # Course preferences
                   3977: 
                   3978:    if ($thisallowed=~/C/) {
1.620     albertel 3979:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3980:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3981:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3982: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3983: 	   if ($priv ne 'pch') { 
                   3984: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3985: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3986: 			$env{'request.course.id'});
                   3987: 	   }
1.237     www      3988:            return '';
                   3989:        }
                   3990: 
1.620     albertel 3991:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3992: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3993: 	   if ($priv ne 'pch') { 
                   3994: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3995: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3996: 			$env{'request.course.id'});
                   3997: 	   }
1.54      www      3998:            return '';
                   3999:        }
1.53      www      4000:    }
                   4001: 
                   4002: # Resource preferences
                   4003: 
                   4004:    if ($thisallowed=~/R/) {
1.620     albertel 4005:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4006:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4007: 	   if ($priv ne 'pch') { 
                   4008: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4009: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4010: 	   }
                   4011: 	   return '';
1.54      www      4012:        }
1.53      www      4013:    }
1.30      www      4014: 
1.246     www      4015: # Restricted by state or randomout?
1.30      www      4016: 
1.52      www      4017:    if ($thisallowed=~/X/) {
1.620     albertel 4018:       if ($env{'acc.randomout'}) {
1.579     albertel 4019: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4020:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4021:             return ''; 
                   4022:          }
1.247     www      4023:       }
                   4024:       if (&condval($statecond)) {
1.52      www      4025: 	 return '2';
                   4026:       } else {
                   4027:          return '';
                   4028:       }
                   4029:    }
1.30      www      4030: 
1.766     albertel 4031:     if ($thisallowed eq 'A') {
                   4032: 	return 'A';
1.814     raeburn  4033:     } elsif ($thisallowed eq 'B') {
                   4034:         return 'B';
1.766     albertel 4035:     }
1.52      www      4036:    return 'F';
1.232     www      4037: }
                   4038: 
1.710     albertel 4039: sub split_uri_for_cond {
                   4040:     my $uri=&deversion(&declutter(shift));
                   4041:     my @uriparts=split(/\//,$uri);
                   4042:     my $filename=pop(@uriparts);
                   4043:     my $pathname=join('/',@uriparts);
                   4044:     return ($pathname,$filename);
                   4045: }
1.232     www      4046: # --------------------------------------------------- Is a resource on the map?
                   4047: 
                   4048: sub is_on_map {
1.710     albertel 4049:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4050:     #Trying to find the conditional for the file
1.620     albertel 4051:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4052: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4053:     if ($match) {
1.289     bowersj2 4054: 	return (1,$1);
                   4055:     } else {
1.434     www      4056: 	return (0,0);
1.289     bowersj2 4057:     }
1.12      www      4058: }
                   4059: 
1.427     www      4060: # --------------------------------------------------------- Get symb from alias
                   4061: 
                   4062: sub get_symb_from_alias {
                   4063:     my $symb=shift;
                   4064:     my ($map,$resid,$url)=&decode_symb($symb);
                   4065: # Already is a symb
                   4066:     if ($url) { return $symb; }
                   4067: # Must be an alias
                   4068:     my $aliassymb='';
                   4069:     my %bighash;
1.620     albertel 4070:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4071:                             &GDBM_READER(),0640)) {
                   4072:         my $rid=$bighash{'mapalias_'.$symb};
                   4073: 	if ($rid) {
                   4074: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4075: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4076: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4077: 	}
                   4078:         untie %bighash;
                   4079:     }
                   4080:     return $aliassymb;
                   4081: }
                   4082: 
1.12      www      4083: # ----------------------------------------------------------------- Define Role
                   4084: 
                   4085: sub definerole {
                   4086:   if (allowed('mcr','/')) {
                   4087:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4088:     foreach my $role (split(':',$sysrole)) {
                   4089: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4090:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4091:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4092: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4093:                return "refused:s:$crole&$cqual"; 
                   4094:             }
                   4095:         }
1.191     harris41 4096:     }
1.800     albertel 4097:     foreach my $role (split(':',$domrole)) {
                   4098: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4099:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4100:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4101: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4102:                return "refused:d:$crole&$cqual"; 
                   4103:             }
                   4104:         }
1.191     harris41 4105:     }
1.800     albertel 4106:     foreach my $role (split(':',$courole)) {
                   4107: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4108:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4109:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4110: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4111:                return "refused:c:$crole&$cqual"; 
                   4112:             }
                   4113:         }
1.191     harris41 4114:     }
1.620     albertel 4115:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4116:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4117: 	        "rolesdef_$rolename=".
                   4118:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4119:     return reply($command,$env{'user.home'});
1.12      www      4120:   } else {
                   4121:     return 'refused';
                   4122:   }
1.105     harris41 4123: }
                   4124: 
                   4125: # ---------------- Make a metadata query against the network of library servers
                   4126: 
                   4127: sub metadata_query {
1.244     matthew  4128:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4129:     my %rhash;
1.244     matthew  4130:     my @server_list = (defined($server_array) ? @$server_array
                   4131:                                               : keys(%libserv) );
                   4132:     for my $server (@server_list) {
1.118     harris41 4133: 	unless ($custom or $customshow) {
                   4134: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4135: 	    $rhash{$server}=$reply;
                   4136: 	}
                   4137: 	else {
                   4138: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4139: 			     &escape($custom).':'.&escape($customshow),
                   4140: 			     $server);
                   4141: 	    $rhash{$server}=$reply;
                   4142: 	}
1.112     harris41 4143:     }
1.118     harris41 4144:     return \%rhash;
1.240     www      4145: }
                   4146: 
                   4147: # ----------------------------------------- Send log queries and wait for reply
                   4148: 
                   4149: sub log_query {
                   4150:     my ($uname,$udom,$query,%filters)=@_;
                   4151:     my $uhome=&homeserver($uname,$udom);
                   4152:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4153:     my $uhost=$hostname{$uhome};
1.800     albertel 4154:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4155:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4156:                        $uhome);
1.479     albertel 4157:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4158:     return get_query_reply($queryid);
                   4159: }
                   4160: 
1.818     raeburn  4161: # -------------------------- Update MySQL table for portfolio file
                   4162: 
                   4163: sub update_portfolio_table {
1.821     raeburn  4164:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4165:     my $homeserver = &homeserver($uname,$udom);
                   4166:     my $queryid=
1.821     raeburn  4167:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4168:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4169:     my $reply = &get_query_reply($queryid);
                   4170:     return $reply;
                   4171: }
                   4172: 
1.508     raeburn  4173: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4174: 
                   4175: sub fetch_enrollment_query {
1.511     raeburn  4176:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4177:     my $homeserver;
1.547     raeburn  4178:     my $maxtries = 1;
1.508     raeburn  4179:     if ($context eq 'automated') {
                   4180:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4181:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4182:     } else {
                   4183:         $homeserver = &homeserver($cnum,$dom);
                   4184:     }
1.506     raeburn  4185:     my $host=$hostname{$homeserver};
                   4186:     my $cmd = '';
1.800     albertel 4187:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4188:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4189:     }
                   4190:     $cmd =~ s/%%$//;
                   4191:     $cmd = &escape($cmd);
                   4192:     my $query = 'fetchenrollment';
1.620     albertel 4193:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4194:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4195:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4196:         return 'error: '.$queryid;
                   4197:     }
1.506     raeburn  4198:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4199:     my $tries = 1;
                   4200:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4201:         $reply = &get_query_reply($queryid);
                   4202:         $tries ++;
                   4203:     }
1.526     raeburn  4204:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4205:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4206:     } else {
1.515     raeburn  4207:         my @responses = split/:/,$reply;
                   4208:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4209:             foreach my $line (@responses) {
                   4210:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4211:                 $$replyref{$key} = $value;
                   4212:             }
                   4213:         } else {
1.506     raeburn  4214:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4215:             foreach my $line (@responses) {
                   4216:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4217:                 $$replyref{$key} = $value;
                   4218:                 if ($value > 0) {
1.800     albertel 4219:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4220:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4221:                         my $destname = $pathname.'/'.$filename;
                   4222:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4223:                         if ($xml_classlist =~ /^error/) {
                   4224:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4225:                         } else {
1.506     raeburn  4226:                             if ( open(FILE,">$destname") ) {
                   4227:                                 print FILE &unescape($xml_classlist);
                   4228:                                 close(FILE);
1.526     raeburn  4229:                             } else {
                   4230:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4231:                             }
                   4232:                         }
                   4233:                     }
                   4234:                 }
                   4235:             }
                   4236:         }
                   4237:         return 'ok';
                   4238:     }
                   4239:     return 'error';
                   4240: }
                   4241: 
1.242     www      4242: sub get_query_reply {
                   4243:     my $queryid=shift;
1.240     www      4244:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4245:     my $reply='';
                   4246:     for (1..100) {
                   4247: 	sleep 2;
                   4248:         if (-e $replyfile.'.end') {
1.448     albertel 4249: 	    if (open(my $fh,$replyfile)) {
1.240     www      4250:                $reply.=<$fh>;
1.448     albertel 4251:                close($fh);
1.240     www      4252: 	   } else { return 'error: reply_file_error'; }
1.242     www      4253:            return &unescape($reply);
                   4254: 	}
1.240     www      4255:     }
1.242     www      4256:     return 'timeout:'.$queryid;
1.240     www      4257: }
                   4258: 
                   4259: sub courselog_query {
1.241     www      4260: #
                   4261: # possible filters:
                   4262: # url: url or symb
                   4263: # username
                   4264: # domain
                   4265: # action: view, submit, grade
                   4266: # start: timestamp
                   4267: # end: timestamp
                   4268: #
1.240     www      4269:     my (%filters)=@_;
1.620     albertel 4270:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4271:     if ($filters{'url'}) {
                   4272: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4273:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4274:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4275:     }
1.620     albertel 4276:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4277:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4278:     return &log_query($cname,$cdom,'courselog',%filters);
                   4279: }
                   4280: 
                   4281: sub userlog_query {
                   4282:     my ($uname,$udom,%filters)=@_;
                   4283:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4284: }
                   4285: 
1.506     raeburn  4286: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4287: 
                   4288: sub auto_run {
1.508     raeburn  4289:     my ($cnum,$cdom) = @_;
                   4290:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4291:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4292:     return $response;
                   4293: }
1.776     albertel 4294: 
1.506     raeburn  4295: sub auto_get_sections {
1.508     raeburn  4296:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4297:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4298:     my @secs = ();
1.511     raeburn  4299:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4300:     unless ($response eq 'refused') {
                   4301:         @secs = split/:/,$response;
                   4302:     }
                   4303:     return @secs;
                   4304: }
1.776     albertel 4305: 
1.506     raeburn  4306: sub auto_new_course {
1.508     raeburn  4307:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4308:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4309:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4310:     return $response;
                   4311: }
1.776     albertel 4312: 
1.506     raeburn  4313: sub auto_validate_courseID {
1.508     raeburn  4314:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4315:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4316:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4317:     return $response;
                   4318: }
1.776     albertel 4319: 
1.506     raeburn  4320: sub auto_create_password {
1.508     raeburn  4321:     my ($cnum,$cdom,$authparam) = @_;
                   4322:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4323:     my $create_passwd = 0;
                   4324:     my $authchk = '';
1.511     raeburn  4325:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4326:     if ($response eq 'refused') {
                   4327:         $authchk = 'refused';
                   4328:     } else {
                   4329:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4330:     }
                   4331:     return ($authparam,$create_passwd,$authchk);
                   4332: }
                   4333: 
1.706     raeburn  4334: sub auto_photo_permission {
                   4335:     my ($cnum,$cdom,$students) = @_;
                   4336:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4337:     my ($outcome,$perm_reqd,$conditions) = 
                   4338: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4339:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4340: 	return (undef,undef);
                   4341:     }
1.706     raeburn  4342:     return ($outcome,$perm_reqd,$conditions);
                   4343: }
                   4344: 
                   4345: sub auto_checkphotos {
                   4346:     my ($uname,$udom,$pid) = @_;
                   4347:     my $homeserver = &homeserver($uname,$udom);
                   4348:     my ($result,$resulttype);
                   4349:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4350: 				   &escape($uname).':'.&escape($pid),
                   4351: 				   $homeserver));
1.709     albertel 4352:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4353: 	return (undef,undef);
                   4354:     }
1.706     raeburn  4355:     if ($outcome) {
                   4356:         ($result,$resulttype) = split(/:/,$outcome);
                   4357:     } 
                   4358:     return ($result,$resulttype);
                   4359: }
                   4360: 
                   4361: sub auto_photochoice {
                   4362:     my ($cnum,$cdom) = @_;
                   4363:     my $homeserver = &homeserver($cnum,$cdom);
                   4364:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4365: 						       &escape($cdom),
                   4366: 						       $homeserver)));
1.709     albertel 4367:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4368: 	return (undef,undef);
                   4369:     }
1.706     raeburn  4370:     return ($update,$comment);
                   4371: }
                   4372: 
                   4373: sub auto_photoupdate {
                   4374:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4375:     my $homeserver = &homeserver($cnum,$dom);
                   4376:     my $host=$hostname{$homeserver};
                   4377:     my $cmd = '';
                   4378:     my $maxtries = 1;
1.800     albertel 4379:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4380:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4381:     }
                   4382:     $cmd =~ s/%%$//;
                   4383:     $cmd = &escape($cmd);
                   4384:     my $query = 'institutionalphotos';
                   4385:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4386:     unless ($queryid=~/^\Q$host\E\_/) {
                   4387:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4388:         return 'error: '.$queryid;
                   4389:     }
                   4390:     my $reply = &get_query_reply($queryid);
                   4391:     my $tries = 1;
                   4392:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4393:         $reply = &get_query_reply($queryid);
                   4394:         $tries ++;
                   4395:     }
                   4396:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4397:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4398:     } else {
                   4399:         my @responses = split(/:/,$reply);
                   4400:         my $outcome = shift(@responses); 
                   4401:         foreach my $item (@responses) {
                   4402:             my ($key,$value) = split(/=/,$item);
                   4403:             $$photo{$key} = $value;
                   4404:         }
                   4405:         return $outcome;
                   4406:     }
                   4407:     return 'error';
                   4408: }
                   4409: 
1.521     raeburn  4410: sub auto_instcode_format {
1.793     albertel 4411:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4412: 	$cat_order) = @_;
1.521     raeburn  4413:     my $courses = '';
1.772     raeburn  4414:     my @homeservers;
1.521     raeburn  4415:     if ($caller eq 'global') {
1.793     albertel 4416:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4417:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4418:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4419:                     push(@homeservers,$tryserver);
                   4420:                 }
1.584     raeburn  4421:             }
                   4422:         }
1.521     raeburn  4423:     } else {
1.772     raeburn  4424:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4425:     }
1.793     albertel 4426:     foreach my $code (keys(%{$instcodes})) {
                   4427:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4428:     }
                   4429:     chop($courses);
1.772     raeburn  4430:     my $ok_response = 0;
                   4431:     my $response;
                   4432:     while (@homeservers > 0 && $ok_response == 0) {
                   4433:         my $server = shift(@homeservers); 
                   4434:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4435:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4436:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4437: 		split/:/,$response;
1.772     raeburn  4438:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4439:             push(@{$codetitles},&str2array($codetitles_str));
                   4440:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4441:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4442:             $ok_response = 1;
                   4443:         }
                   4444:     }
                   4445:     if ($ok_response) {
1.521     raeburn  4446:         return 'ok';
1.772     raeburn  4447:     } else {
                   4448:         return $response;
1.521     raeburn  4449:     }
                   4450: }
                   4451: 
1.792     raeburn  4452: sub auto_instcode_defaults {
                   4453:     my ($domain,$returnhash,$code_order) = @_;
                   4454:     my @homeservers;
1.793     albertel 4455:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4456:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4457:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4458:                 push(@homeservers,$tryserver);
                   4459:             }
                   4460:         }
                   4461:     }
                   4462:     my $ok_response = 0;
                   4463:     my $response;
                   4464:     while (@homeservers > 0 && $ok_response == 0) {
                   4465:         my $server = shift(@homeservers);
                   4466:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4467:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4468:             foreach my $pair (split(/\&/,$response)) {
                   4469:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4470:                 if ($name eq 'code_order') {
1.796     raeburn  4471:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4472:                 } else {
1.796     raeburn  4473:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4474:                 }
                   4475:             }
1.804     raeburn  4476:             $ok_response = 1;
1.792     raeburn  4477:         }
                   4478:     }
                   4479:     if ($ok_response) {
                   4480:         return 'ok';
                   4481:     } else {
                   4482:         return $response;
                   4483:     }
                   4484: } 
                   4485: 
1.777     albertel 4486: sub auto_validate_class_sec {
1.773     raeburn  4487:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4488:     my $homeserver = &homeserver($cnum,$cdom);
                   4489:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4490:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4491:     return $response;
                   4492: }
                   4493: 
1.679     raeburn  4494: # ------------------------------------------------------- Course Group routines
                   4495: 
                   4496: sub get_coursegroups {
1.809     raeburn  4497:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4498:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4499: }
                   4500: 
1.679     raeburn  4501: sub modify_coursegroup {
                   4502:     my ($cdom,$cnum,$groupsettings) = @_;
                   4503:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4504: }
                   4505: 
1.809     raeburn  4506: sub toggle_coursegroup_status {
                   4507:     my ($cdom,$cnum,$group,$action) = @_;
                   4508:     my ($from_namespace,$to_namespace);
                   4509:     if ($action eq 'delete') {
                   4510:         $from_namespace = 'coursegroups';
                   4511:         $to_namespace = 'deleted_groups';
                   4512:     } else {
                   4513:         $from_namespace = 'deleted_groups';
                   4514:         $to_namespace = 'coursegroups';
                   4515:     }
                   4516:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4517:     if (my $tmp = &error(%curr_group)) {
                   4518:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4519:         return ('read error',$tmp);
                   4520:     } else {
                   4521:         my %savedsettings = %curr_group; 
1.809     raeburn  4522:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4523:         my $deloutcome;
                   4524:         if ($result eq 'ok') {
1.809     raeburn  4525:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4526:         } else {
                   4527:             return ('write error',$result);
                   4528:         }
                   4529:         if ($deloutcome eq 'ok') {
                   4530:             return 'ok';
                   4531:         } else {
                   4532:             return ('delete error',$deloutcome);
                   4533:         }
                   4534:     }
                   4535: }
                   4536: 
1.679     raeburn  4537: sub modify_group_roles {
                   4538:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4539:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4540:     my $role = 'gr/'.&escape($userprivs);
                   4541:     my ($uname,$udom) = split(/:/,$user);
                   4542:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4543:     if ($result eq 'ok') {
                   4544:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4545:     }
1.679     raeburn  4546:     return $result;
                   4547: }
                   4548: 
                   4549: sub modify_coursegroup_membership {
                   4550:     my ($cdom,$cnum,$membership) = @_;
                   4551:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4552:     return $result;
                   4553: }
                   4554: 
1.682     raeburn  4555: sub get_active_groups {
                   4556:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4557:     my $now = time;
                   4558:     my %groups = ();
                   4559:     foreach my $key (keys(%env)) {
1.811     albertel 4560:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4561:             my ($start,$end) = split(/\./,$env{$key});
                   4562:             if (($end!=0) && ($end<$now)) { next; }
                   4563:             if (($start!=0) && ($start>$now)) { next; }
                   4564:             if ($1 eq $cdom && $2 eq $cnum) {
                   4565:                 $groups{$3} = $env{$key} ;
                   4566:             }
                   4567:         }
                   4568:     }
                   4569:     return %groups;
                   4570: }
                   4571: 
1.683     raeburn  4572: sub get_group_membership {
                   4573:     my ($cdom,$cnum,$group) = @_;
                   4574:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4575: }
                   4576: 
                   4577: sub get_users_groups {
                   4578:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4579:     my @usersgroups;
1.683     raeburn  4580:     my $cachetime=1800;
                   4581: 
                   4582:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4583:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4584:     if (defined($cached)) {
1.734     albertel 4585:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4586:     } else {  
                   4587:         $grouplist = '';
1.816     raeburn  4588:         my $courseurl = &courseid_to_courseurl($courseid);
                   4589:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4590:         my $access_end = $env{'course.'.$courseid.
                   4591:                               '.default_enrollment_end_date'};
                   4592:         my $now = time;
                   4593:         foreach my $key (keys(%roleshash)) {
                   4594:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4595:                 my $group = $1;
                   4596:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4597:                     my $start = $2;
                   4598:                     my $end = $1;
                   4599:                     if ($start == -1) { next; } # deleted from group
                   4600:                     if (($start!=0) && ($start>$now)) { next; }
                   4601:                     if (($end!=0) && ($end<$now)) {
                   4602:                         if ($access_end && $access_end < $now) {
                   4603:                             if ($access_end - $end < 86400) {
                   4604:                                 push(@usersgroups,$group);
1.733     raeburn  4605:                             }
                   4606:                         }
1.817     raeburn  4607:                         next;
1.733     raeburn  4608:                     }
1.817     raeburn  4609:                     push(@usersgroups,$group);
1.683     raeburn  4610:                 }
                   4611:             }
                   4612:         }
1.817     raeburn  4613:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4614:         $grouplist = join(':',@usersgroups);
                   4615:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4616:     }
1.733     raeburn  4617:     return @usersgroups;
1.683     raeburn  4618: }
                   4619: 
                   4620: sub devalidate_getgroups_cache {
                   4621:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4622:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4623: 
1.683     raeburn  4624:     my $hashid="$udom:$uname:$courseid";
                   4625:     &devalidate_cache_new('getgroups',$hashid);
                   4626: }
                   4627: 
1.12      www      4628: # ------------------------------------------------------------------ Plain Text
                   4629: 
                   4630: sub plaintext {
1.742     raeburn  4631:     my ($short,$type,$cid) = @_;
1.758     albertel 4632:     if ($short =~ /^cr/) {
                   4633: 	return (split('/',$short))[-1];
                   4634:     }
1.742     raeburn  4635:     if (!defined($cid)) {
                   4636:         $cid = $env{'request.course.id'};
                   4637:     }
                   4638:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4639:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4640:                                           '.plaintext'});
                   4641:     }
                   4642:     my %rolenames = (
                   4643:                       Course => 'std',
                   4644:                       Group => 'alt1',
                   4645:                     );
                   4646:     if (defined($type) && 
                   4647:          defined($rolenames{$type}) && 
                   4648:          defined($prp{$short}{$rolenames{$type}})) {
                   4649:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4650:     } else {
                   4651:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4652:     }
1.12      www      4653: }
                   4654: 
                   4655: # ----------------------------------------------------------------- Assign Role
                   4656: 
                   4657: sub assignrole {
1.357     www      4658:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4659:     my $mrole;
                   4660:     if ($role =~ /^cr\//) {
1.393     www      4661:         my $cwosec=$url;
1.811     albertel 4662:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4663: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4664:            &logthis('Refused custom assignrole: '.
                   4665:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4666: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4667:            return 'refused'; 
                   4668:         }
1.21      www      4669:         $mrole='cr';
1.678     raeburn  4670:     } elsif ($role =~ /^gr\//) {
                   4671:         my $cwogrp=$url;
1.811     albertel 4672:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4673:         unless (&allowed('mdg',$cwogrp)) {
                   4674:             &logthis('Refused group assignrole: '.
                   4675:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4676:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4677:             return 'refused';
                   4678:         }
                   4679:         $mrole='gr';
1.21      www      4680:     } else {
1.82      www      4681:         my $cwosec=$url;
1.811     albertel 4682:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4683:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4684:            &logthis('Refused assignrole: '.
                   4685:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4686: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4687:            return 'refused'; 
                   4688:         }
1.21      www      4689:         $mrole=$role;
                   4690:     }
1.620     albertel 4691:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4692:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4693:     if ($end) { $command.='_'.$end; }
1.21      www      4694:     if ($start) {
                   4695: 	if ($end) { 
1.81      www      4696:            $command.='_'.$start; 
1.21      www      4697:         } else {
1.81      www      4698:            $command.='_0_'.$start;
1.21      www      4699:         }
                   4700:     }
1.739     raeburn  4701:     my $origstart = $start;
                   4702:     my $origend = $end;
1.357     www      4703: # actually delete
                   4704:     if ($deleteflag) {
1.373     www      4705: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4706: # modify command to delete the role
1.620     albertel 4707:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4708:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4709: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4710: # set start and finish to negative values for userrolelog
                   4711:            $start=-1;
                   4712:            $end=-1;
                   4713:         }
                   4714:     }
                   4715: # send command
1.349     www      4716:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4717: # log new user role if status is ok
1.349     www      4718:     if ($answer eq 'ok') {
1.663     raeburn  4719: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4720: # for course roles, perform group memberships changes triggered by role change.
                   4721:         unless ($role =~ /^gr/) {
                   4722:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4723:                                              $origstart);
                   4724:         }
1.349     www      4725:     }
                   4726:     return $answer;
1.169     harris41 4727: }
                   4728: 
                   4729: # -------------------------------------------------- Modify user authentication
1.197     www      4730: # Overrides without validation
                   4731: 
1.169     harris41 4732: sub modifyuserauth {
                   4733:     my ($udom,$uname,$umode,$upass)=@_;
                   4734:     my $uhome=&homeserver($uname,$udom);
1.197     www      4735:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4736:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4737:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4738:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4739:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4740: 		     &escape($upass),$uhome);
1.620     albertel 4741:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4742:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4743:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4744:     &log($udom,,$uname,$uhome,
1.620     albertel 4745:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4746:                                      $env{'user.name'}.', '.$umode.
1.197     www      4747:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4748:     unless ($reply eq 'ok') {
1.197     www      4749:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4750: 	return 'error: '.$reply;
                   4751:     }   
1.170     harris41 4752:     return 'ok';
1.80      www      4753: }
                   4754: 
1.81      www      4755: # --------------------------------------------------------------- Modify a user
1.80      www      4756: 
1.81      www      4757: sub modifyuser {
1.206     matthew  4758:     my ($udom,    $uname, $uid,
                   4759:         $umode,   $upass, $first,
                   4760:         $middle,  $last,  $gene,
1.387     www      4761:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4762:     $udom= &LONCAPA::clean_domain($udom);
                   4763:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4764:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4765:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4766: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4767:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4768:                                      ' desiredhome not specified'). 
1.620     albertel 4769:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4770:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4771:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4772: # ----------------------------------------------------------------- Create User
1.406     albertel 4773:     if (($uhome eq 'no_host') && 
                   4774: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4775:         my $unhome='';
1.209     matthew  4776:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4777:             $unhome = $desiredhome;
1.620     albertel 4778: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4779: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4780:         } else { # load balancing routine for determining $unhome
1.80      www      4781:             my $tryserver;
1.81      www      4782:             my $loadm=10000000;
1.80      www      4783:             foreach $tryserver (keys %libserv) {
                   4784: 	       if ($hostdom{$tryserver} eq $udom) {
                   4785:                   my $answer=reply('load',$tryserver);
                   4786:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4787: 		      $loadm=$answer;
                   4788:                       $unhome=$tryserver;
                   4789:                   }
                   4790: 	       }
                   4791: 	    }
                   4792:         }
                   4793:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4794: 	    return 'error: unable to find a home server for '.$uname.
                   4795:                    ' in domain '.$udom;
1.80      www      4796:         }
                   4797:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4798:                          &escape($upass),$unhome);
                   4799: 	unless ($reply eq 'ok') {
                   4800:             return 'error: '.$reply;
                   4801:         }   
1.230     stredwic 4802:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4803:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4804: 	    return 'error: unable verify users home machine.';
1.80      www      4805:         }
1.209     matthew  4806:     }   # End of creation of new user
1.80      www      4807: # ---------------------------------------------------------------------- Add ID
                   4808:     if ($uid) {
                   4809:        $uid=~tr/A-Z/a-z/;
                   4810:        my %uidhash=&idrget($udom,$uname);
1.196     www      4811:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4812:          && (!$forceid)) {
1.80      www      4813: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4814: 	      return 'error: user id "'.$uid.'" does not match '.
                   4815:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4816:           }
                   4817:        } else {
                   4818: 	  &idput($udom,($uname => $uid));
                   4819:        }
                   4820:     }
                   4821: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4822:     my @tmp=&get('environment',
1.134     albertel 4823: 		   ['firstname','middlename','lastname','generation'],
                   4824: 		   $udom,$uname);
1.313     matthew  4825:     my %names;
                   4826:     if ($tmp[0] =~ m/^error:.*/) { 
                   4827:         %names=(); 
                   4828:     } else {
                   4829:         %names = @tmp;
                   4830:     }
1.388     www      4831: #
                   4832: # Make sure to not trash student environment if instructor does not bother
                   4833: # to supply name and email information
                   4834: #
                   4835:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4836:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4837:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4838:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4839:     if ($email) {
                   4840:        $email=~s/[^\w\@\.\-\,]//gs;
                   4841:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4842: 			   $names{'critnotification'} = $email;
                   4843: 			   $names{'permanentemail'} = $email; }
                   4844:     }
1.134     albertel 4845:     my $reply = &put('environment', \%names, $udom,$uname);
                   4846:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4847:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4848:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4849:              $umode.', '.$first.', '.$middle.', '.
                   4850: 	     $last.', '.$gene.' by '.
1.620     albertel 4851:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4852:     return 'ok';
1.80      www      4853: }
                   4854: 
1.81      www      4855: # -------------------------------------------------------------- Modify student
1.80      www      4856: 
1.81      www      4857: sub modifystudent {
                   4858:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4859:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4860:     if (!$cid) {
1.620     albertel 4861: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4862: 	    return 'not_in_class';
                   4863: 	}
1.80      www      4864:     }
                   4865: # --------------------------------------------------------------- Make the user
1.81      www      4866:     my $reply=&modifyuser
1.209     matthew  4867: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4868:          $desiredhome,$email);
1.80      www      4869:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4870:     # This will cause &modify_student_enrollment to get the uid from the
                   4871:     # students environment
                   4872:     $uid = undef if (!$forceid);
1.455     albertel 4873:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4874: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4875:     return $reply;
                   4876: }
                   4877: 
                   4878: sub modify_student_enrollment {
1.515     raeburn  4879:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4880:     my ($cdom,$cnum,$chome);
                   4881:     if (!$cid) {
1.620     albertel 4882: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4883: 	    return 'not_in_class';
                   4884: 	}
1.620     albertel 4885: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4886: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4887:     } else {
                   4888: 	($cdom,$cnum)=split(/_/,$cid);
                   4889:     }
1.620     albertel 4890:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4891:     if (!$chome) {
1.457     raeburn  4892: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4893:     }
1.455     albertel 4894:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4895:     # Make sure the user exists
1.81      www      4896:     my $uhome=&homeserver($uname,$udom);
                   4897:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4898: 	return 'error: no such user';
                   4899:     }
1.297     matthew  4900:     # Get student data if we were not given enough information
                   4901:     if (!defined($first)  || $first  eq '' || 
                   4902:         !defined($last)   || $last   eq '' || 
                   4903:         !defined($uid)    || $uid    eq '' || 
                   4904:         !defined($middle) || $middle eq '' || 
                   4905:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4906:         # They did not supply us with enough data to enroll the student, so
                   4907:         # we need to pick up more information.
1.297     matthew  4908:         my %tmp = &get('environment',
1.294     matthew  4909:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4910:                        ,$udom,$uname);
                   4911: 
1.800     albertel 4912:         #foreach my $key (keys(%tmp)) {
                   4913:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4914:         #}
1.294     matthew  4915:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4916:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4917:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4918:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4919:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4920:     }
1.556     albertel 4921:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4922:     my $reply=cput('classlist',
                   4923: 		   {"$uname:$udom" => 
1.515     raeburn  4924: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4925: 		   $cdom,$cnum);
1.81      www      4926:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4927: 	return 'error: '.$reply;
1.652     albertel 4928:     } else {
                   4929: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4930:     }
1.297     matthew  4931:     # Add student role to user
1.83      www      4932:     my $uurl='/'.$cid;
1.81      www      4933:     $uurl=~s/\_/\//g;
                   4934:     if ($usec) {
                   4935: 	$uurl.='/'.$usec;
                   4936:     }
                   4937:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4938: }
                   4939: 
1.556     albertel 4940: sub format_name {
                   4941:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4942:     my $name;
                   4943:     if ($first ne 'lastname') {
                   4944: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4945:     } else {
                   4946: 	if ($lastname=~/\S/) {
                   4947: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4948: 	    $name=~s/\s+,/,/;
                   4949: 	} else {
                   4950: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4951: 	}
                   4952:     }
                   4953:     $name=~s/^\s+//;
                   4954:     $name=~s/\s+$//;
                   4955:     $name=~s/\s+/ /g;
                   4956:     return $name;
                   4957: }
                   4958: 
1.84      www      4959: # ------------------------------------------------- Write to course preferences
                   4960: 
                   4961: sub writecoursepref {
                   4962:     my ($courseid,%prefs)=@_;
                   4963:     $courseid=~s/^\///;
                   4964:     $courseid=~s/\_/\//g;
                   4965:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4966:     my $chome=homeserver($cnum,$cdomain);
                   4967:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4968: 	return 'error: no such course';
                   4969:     }
                   4970:     my $cstring='';
1.800     albertel 4971:     foreach my $pref (keys(%prefs)) {
                   4972: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4973:     }
1.84      www      4974:     $cstring=~s/\&$//;
                   4975:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4976: }
                   4977: 
                   4978: # ---------------------------------------------------------- Make/modify course
                   4979: 
                   4980: sub createcourse {
1.741     raeburn  4981:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4982:         $course_owner,$crstype)=@_;
1.84      www      4983:     $url=&declutter($url);
                   4984:     my $cid='';
1.264     matthew  4985:     unless (&allowed('ccc',$udom)) {
1.84      www      4986:         return 'refused';
                   4987:     }
                   4988: # ------------------------------------------------------------------- Create ID
1.674     www      4989:    my $uname=int(1+rand(9)).
                   4990:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4991:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4992:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4993: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4994:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4995:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4996:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4997:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4998:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4999:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5000:            return 'error: unable to generate unique course-ID';
                   5001:        } 
                   5002:    }
1.264     matthew  5003: # ------------------------------------------------ Check supplied server name
1.620     albertel 5004:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  5005:     if (! exists($libserv{$course_server})) {
                   5006:         return 'error:bad server name '.$course_server;
                   5007:     }
1.84      www      5008: # ------------------------------------------------------------- Make the course
                   5009:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5010:                       $course_server);
1.84      www      5011:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5012:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5013:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5014: 	return 'error: no such course';
                   5015:     }
1.271     www      5016: # ----------------------------------------------------------------- Course made
1.516     raeburn  5017: # log existence
                   5018:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5019:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5020:                   &escape($crstype),$uhome);
1.358     www      5021:     &flushcourselogs();
                   5022: # set toplevel url
1.271     www      5023:     my $topurl=$url;
                   5024:     unless ($nonstandard) {
                   5025: # ------------------------------------------ For standard courses, make top url
                   5026:         my $mapurl=&clutter($url);
1.278     www      5027:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5028:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5029: <map>
                   5030: <resource id="1" type="start"></resource>
                   5031: <resource id="2" src="$mapurl"></resource>
                   5032: <resource id="3" type="finish"></resource>
                   5033: <link index="1" from="1" to="2"></link>
                   5034: <link index="2" from="2" to="3"></link>
                   5035: </map>
                   5036: ENDINITMAP
                   5037:         $topurl=&declutter(
1.638     albertel 5038:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5039:                           );
                   5040:     }
                   5041: # ----------------------------------------------------------- Write preferences
1.84      www      5042:     &writecoursepref($udom.'_'.$uname,
                   5043:                      ('description' => $description,
1.271     www      5044:                       'url'         => $topurl));
1.84      www      5045:     return '/'.$udom.'/'.$uname;
                   5046: }
                   5047: 
1.813     albertel 5048: sub is_course {
                   5049:     my ($cdom,$cnum) = @_;
                   5050:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5051: 				undef,'.');
                   5052:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5053:         return 1;
                   5054:     }
                   5055:     return 0;
                   5056: }
                   5057: 
1.21      www      5058: # ---------------------------------------------------------- Assign Custom Role
                   5059: 
                   5060: sub assigncustomrole {
1.357     www      5061:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5062:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5063:                        $end,$start,$deleteflag);
1.21      www      5064: }
                   5065: 
                   5066: # ----------------------------------------------------------------- Revoke Role
                   5067: 
                   5068: sub revokerole {
1.357     www      5069:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5070:     my $now=time;
1.357     www      5071:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5072: }
                   5073: 
                   5074: # ---------------------------------------------------------- Revoke Custom Role
                   5075: 
                   5076: sub revokecustomrole {
1.357     www      5077:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5078:     my $now=time;
1.357     www      5079:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5080:            $deleteflag);
1.17      www      5081: }
                   5082: 
1.533     banghart 5083: # ------------------------------------------------------------ Disk usage
1.535     albertel 5084: sub diskusage {
1.533     banghart 5085:     my ($udom,$uname,$directoryRoot)=@_;
                   5086:     $directoryRoot =~ s/\/$//;
1.535     albertel 5087:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5088:     return $listing;
1.512     banghart 5089: }
                   5090: 
1.566     banghart 5091: sub is_locked {
                   5092:     my ($file_name, $domain, $user) = @_;
                   5093:     my @check;
                   5094:     my $is_locked;
                   5095:     push @check, $file_name;
1.613     albertel 5096:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5097: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5098:     my ($tmp)=keys(%locked);
                   5099:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5100:     
1.566     banghart 5101:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5102:         $is_locked = 'false';
                   5103:         foreach my $entry (@{$locked{$file_name}}) {
                   5104:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5105:                $is_locked = 'true';
                   5106:                last;
1.745     raeburn  5107:            }
                   5108:        }
1.566     banghart 5109:     } else {
                   5110:         $is_locked = 'false';
                   5111:     }
                   5112: }
                   5113: 
1.759     albertel 5114: sub declutter_portfile {
                   5115:     my ($file) = @_;
                   5116:     &logthis("got $file");
                   5117:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5118:     &logthis("ret $file");
                   5119:     return $file;
                   5120: }
                   5121: 
1.559     banghart 5122: # ------------------------------------------------------------- Mark as Read Only
                   5123: 
                   5124: sub mark_as_readonly {
                   5125:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5126:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5127:     my ($tmp)=keys(%current_permissions);
                   5128:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5129:     foreach my $file (@{$files}) {
1.759     albertel 5130: 	$file = &declutter_portfile($file);
1.561     banghart 5131:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5132:     }
1.613     albertel 5133:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5134:     return;
                   5135: }
                   5136: 
1.572     banghart 5137: # ------------------------------------------------------------Save Selected Files
                   5138: 
                   5139: sub save_selected_files {
                   5140:     my ($user, $path, @files) = @_;
                   5141:     my $filename = $user."savedfiles";
1.573     banghart 5142:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5143:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5144:     foreach my $file (@files) {
1.620     albertel 5145:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5146:     }
                   5147:     foreach my $file (@other_files) {
1.574     banghart 5148:         print (OUT $file."\n");
1.572     banghart 5149:     }
1.574     banghart 5150:     close (OUT);
1.572     banghart 5151:     return 'ok';
                   5152: }
                   5153: 
1.574     banghart 5154: sub clear_selected_files {
                   5155:     my ($user) = @_;
                   5156:     my $filename = $user."savedfiles";
                   5157:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5158:     print (OUT undef);
                   5159:     close (OUT);
                   5160:     return ("ok");    
                   5161: }
                   5162: 
1.572     banghart 5163: sub files_in_path {
                   5164:     my ($user, $path) = @_;
                   5165:     my $filename = $user."savedfiles";
                   5166:     my %return_files;
1.574     banghart 5167:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5168:     while (my $line_in = <IN>) {
1.574     banghart 5169:         chomp ($line_in);
                   5170:         my @paths_and_file = split (m!/!, $line_in);
                   5171:         my $file_part = pop (@paths_and_file);
                   5172:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5173:         $path_part.='/';
                   5174:         my $path_and_file = $path_part.$file_part;
                   5175:         if ($path_part eq $path) {
                   5176:             $return_files{$file_part}= 'selected';
                   5177:         }
                   5178:     }
1.574     banghart 5179:     close (IN);
                   5180:     return (\%return_files);
1.572     banghart 5181: }
                   5182: 
                   5183: # called in portfolio select mode, to show files selected NOT in current directory
                   5184: sub files_not_in_path {
                   5185:     my ($user, $path) = @_;
                   5186:     my $filename = $user."savedfiles";
                   5187:     my @return_files;
                   5188:     my $path_part;
1.800     albertel 5189:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5190:     while (my $line = <IN>) {
1.572     banghart 5191:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5192:         my @paths_and_file = split(m|/|, $line);
                   5193:         my $file_part = pop(@paths_and_file);
                   5194:         chomp($file_part);
                   5195:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5196:         $path_part .= '/';
                   5197:         my $path_and_file = $path_part.$file_part;
                   5198:         if ($path_part ne $path) {
1.800     albertel 5199:             push(@return_files, ($path_and_file));
1.572     banghart 5200:         }
                   5201:     }
1.800     albertel 5202:     close(OUT);
1.574     banghart 5203:     return (@return_files);
1.572     banghart 5204: }
                   5205: 
1.745     raeburn  5206: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5207: 
1.745     raeburn  5208: sub get_portfile_permissions {
                   5209:     my ($domain,$user) = @_;
1.613     albertel 5210:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5211:     my ($tmp)=keys(%current_permissions);
                   5212:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5213:     return \%current_permissions;
                   5214: }
                   5215: 
                   5216: #---------------------------------------------Get portfolio file access controls
                   5217: 
1.749     raeburn  5218: sub get_access_controls {
1.745     raeburn  5219:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5220:     my %access;
                   5221:     my $real_file = $file;
                   5222:     $file =~ s/\.meta$//;
1.745     raeburn  5223:     if (defined($file)) {
1.749     raeburn  5224:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5225:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5226:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5227:             }
                   5228:         }
1.745     raeburn  5229:     } else {
1.749     raeburn  5230:         foreach my $key (keys(%{$current_permissions})) {
                   5231:             if ($key =~ /\0accesscontrol$/) {
                   5232:                 if (defined($group)) {
                   5233:                     if ($key !~ m-^\Q$group\E/-) {
                   5234:                         next;
                   5235:                     }
                   5236:                 }
                   5237:                 my ($fullpath) = split(/\0/,$key);
                   5238:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5239:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5240:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5241:                     }
                   5242:                 }
                   5243:             }
                   5244:         }
                   5245:     }
                   5246:     return %access;
                   5247: }
                   5248: 
                   5249: sub modify_access_controls {
                   5250:     my ($file_name,$changes,$domain,$user)=@_;
                   5251:     my ($outcome,$deloutcome);
                   5252:     my %store_permissions;
                   5253:     my %new_values;
                   5254:     my %new_control;
                   5255:     my %translation;
                   5256:     my @deletions = ();
                   5257:     my $now = time;
                   5258:     if (exists($$changes{'activate'})) {
                   5259:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5260:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5261:             my $numnew = scalar(@newitems);
                   5262:             for (my $i=0; $i<$numnew; $i++) {
                   5263:                 my $newkey = $newitems[$i];
                   5264:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5265:                 if ($newkey =~ /^\d+:/) { 
                   5266:                     $newkey =~ s/^(\d+)/$newid/;
                   5267:                     $translation{$1} = $newid;
                   5268:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5269:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5270:                     $translation{$1} = $newid;
                   5271:                 }
1.749     raeburn  5272:                 $new_values{$file_name."\0".$newkey} = 
                   5273:                                           $$changes{'activate'}{$newitems[$i]};
                   5274:                 $new_control{$newkey} = $now;
                   5275:             }
                   5276:         }
                   5277:     }
                   5278:     my %todelete;
                   5279:     my %changed_items;
                   5280:     foreach my $action ('delete','update') {
                   5281:         if (exists($$changes{$action})) {
                   5282:             if (ref($$changes{$action}) eq 'HASH') {
                   5283:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5284:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5285:                     if ($action eq 'delete') { 
                   5286:                         $todelete{$itemnum} = 1;
                   5287:                     } else {
                   5288:                         $changed_items{$itemnum} = $key;
                   5289:                     }
                   5290:                 }
1.745     raeburn  5291:             }
                   5292:         }
1.749     raeburn  5293:     }
                   5294:     # get lock on access controls for file.
                   5295:     my $lockhash = {
                   5296:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5297:                                                        ':'.$env{'user.domain'},
                   5298:                    }; 
                   5299:     my $tries = 0;
                   5300:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5301:    
                   5302:     while (($gotlock ne 'ok') && $tries <3) {
                   5303:         $tries ++;
                   5304:         sleep 1;
                   5305:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5306:     }
                   5307:     if ($gotlock eq 'ok') {
                   5308:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5309:         my ($tmp)=keys(%curr_permissions);
                   5310:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5311:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5312:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5313:             if (ref($curr_controls) eq 'HASH') {
                   5314:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5315:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5316:                     if (defined($todelete{$itemnum})) {
                   5317:                         push(@deletions,$file_name."\0".$control_item);
                   5318:                     } else {
                   5319:                         if (defined($changed_items{$itemnum})) {
                   5320:                             $new_control{$changed_items{$itemnum}} = $now;
                   5321:                             push(@deletions,$file_name."\0".$control_item);
                   5322:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5323:                         } else {
                   5324:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5325:                         }
                   5326:                     }
1.745     raeburn  5327:                 }
                   5328:             }
                   5329:         }
1.749     raeburn  5330:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5331:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5332:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5333:         #  remove lock
                   5334:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5335:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5336:         my ($file,$group);
                   5337:         if (&is_course($domain,$user)) {
                   5338:             ($group,$file) = split(/\//,$file_name,2);
                   5339:         } else {
                   5340:             $file = $file_name;
                   5341:         }
                   5342:         my $sqlresult =
                   5343:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5344:                                     $group);
1.749     raeburn  5345:     } else {
                   5346:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5347:     }
1.749     raeburn  5348:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5349: }
                   5350: 
                   5351: #------------------------------------------------------Get Marked as Read Only
                   5352: 
                   5353: sub get_marked_as_readonly {
                   5354:     my ($domain,$user,$what,$group) = @_;
                   5355:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5356:     my @readonly_files;
1.629     banghart 5357:     my $cmp1=$what;
                   5358:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5359:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5360:         if (defined($group)) {
                   5361:             if ($file_name !~ m-^\Q$group\E/-) {
                   5362:                 next;
                   5363:             }
                   5364:         }
1.561     banghart 5365:         if (ref($value) eq "ARRAY"){
                   5366:             foreach my $stored_what (@{$value}) {
1.629     banghart 5367:                 my $cmp2=$stored_what;
1.759     albertel 5368:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5369:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5370:                 }
1.629     banghart 5371:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5372:                     push(@readonly_files, $file_name);
1.745     raeburn  5373:                     last;
1.563     banghart 5374:                 } elsif (!defined($what)) {
                   5375:                     push(@readonly_files, $file_name);
1.745     raeburn  5376:                     last;
1.561     banghart 5377:                 }
                   5378:             }
1.745     raeburn  5379:         }
1.561     banghart 5380:     }
                   5381:     return @readonly_files;
                   5382: }
1.577     banghart 5383: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5384: 
1.577     banghart 5385: sub get_marked_as_readonly_hash {
1.745     raeburn  5386:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5387:     my %readonly_files;
1.745     raeburn  5388:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5389:         if (defined($group)) {
                   5390:             if ($file_name !~ m-^\Q$group\E/-) {
                   5391:                 next;
                   5392:             }
                   5393:         }
1.577     banghart 5394:         if (ref($value) eq "ARRAY"){
                   5395:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5396:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5397:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5398:                         if ($lock_descriptor eq 'graded') {
                   5399:                             $readonly_files{$file_name} = 'graded';
                   5400:                         } elsif ($lock_descriptor eq 'handback') {
                   5401:                             $readonly_files{$file_name} = 'handback';
                   5402:                         } else {
                   5403:                             if (!exists($readonly_files{$file_name})) {
                   5404:                                 $readonly_files{$file_name} = 'locked';
                   5405:                             }
                   5406:                         }
1.745     raeburn  5407:                     }
1.750     banghart 5408:                 } 
1.577     banghart 5409:             }
                   5410:         } 
                   5411:     }
                   5412:     return %readonly_files;
                   5413: }
1.559     banghart 5414: # ------------------------------------------------------------ Unmark as Read Only
                   5415: 
                   5416: sub unmark_as_readonly {
1.629     banghart 5417:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5418:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5419:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5420:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5421:     my $symb_crs = $what;
                   5422:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5423:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5424:     my ($tmp)=keys(%current_permissions);
                   5425:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5426:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5427:     foreach my $file (@readonly_files) {
1.759     albertel 5428: 	my $clean_file = &declutter_portfile($file);
                   5429: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5430: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5431:         my @new_locks;
                   5432:         my @del_keys;
                   5433:         if (ref($current_locks) eq "ARRAY"){
                   5434:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5435:                 my $compare=$locker;
1.749     raeburn  5436:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5437:                     $compare=join('',@{$locker});
1.746     raeburn  5438:                     if ($compare ne $symb_crs) {
                   5439:                         push(@new_locks, $locker);
                   5440:                     }
1.563     banghart 5441:                 }
                   5442:             }
1.650     albertel 5443:             if (scalar(@new_locks) > 0) {
1.563     banghart 5444:                 $current_permissions{$file} = \@new_locks;
                   5445:             } else {
                   5446:                 push(@del_keys, $file);
1.613     albertel 5447:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5448:                 delete($current_permissions{$file});
1.563     banghart 5449:             }
                   5450:         }
1.561     banghart 5451:     }
1.613     albertel 5452:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5453:     return;
                   5454: }
1.512     banghart 5455: 
1.17      www      5456: # ------------------------------------------------------------ Directory lister
                   5457: 
                   5458: sub dirlist {
1.253     stredwic 5459:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5460: 
1.18      www      5461:     $uri=~s/^\///;
                   5462:     $uri=~s/\/$//;
1.253     stredwic 5463:     my ($udom, $uname);
                   5464:     (undef,$udom,$uname)=split(/\//,$uri);
                   5465:     if(defined($userdomain)) {
                   5466:         $udom = $userdomain;
                   5467:     }
                   5468:     if(defined($username)) {
                   5469:         $uname = $username;
                   5470:     }
                   5471: 
                   5472:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5473:     if(defined($alternateDirectoryRoot)) {
                   5474:         $dirRoot = $alternateDirectoryRoot;
                   5475:         $dirRoot =~ s/\/$//;
1.751     banghart 5476:     }
1.253     stredwic 5477: 
                   5478:     if($udom) {
                   5479:         if($uname) {
1.800     albertel 5480:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5481: 				 &homeserver($uname,$udom));
1.605     matthew  5482:             my @listing_results;
                   5483:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5484:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5485: 				  &homeserver($uname,$udom));
1.605     matthew  5486:                 @listing_results = split(/:/,$listing);
                   5487:             } else {
                   5488:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5489:             }
                   5490:             return @listing_results;
1.253     stredwic 5491:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5492:             my %allusers;
                   5493:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5494:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5495:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5496: 					 $udom, $tryserver);
1.605     matthew  5497:                     my @listing_results;
                   5498:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5499:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5500: 					  $udom, $tryserver);
1.605     matthew  5501:                         @listing_results = split(/:/,$listing);
                   5502:                     } else {
                   5503:                         @listing_results =
                   5504:                             map { &unescape($_); } split(/:/,$listing);
                   5505:                     }
                   5506:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5507:                         $listing_results[0] ne 'empty'       &&
                   5508:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5509:                         foreach my $line (@listing_results) {
                   5510:                             my ($entry) = split(/&/,$line,2);
                   5511:                             $allusers{$entry} = 1;
1.253     stredwic 5512:                         }
                   5513:                     }
1.191     harris41 5514:                 }
1.253     stredwic 5515:             }
                   5516:             my $alluserstr='';
1.800     albertel 5517:             foreach my $user (sort(keys(%allusers))) {
                   5518:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5519:             }
                   5520:             $alluserstr=~s/:$//;
                   5521:             return split(/:/,$alluserstr);
                   5522:         } else {
1.800     albertel 5523:             return ('missing user name');
1.253     stredwic 5524:         }
                   5525:     } elsif(!defined($alternateDirectoryRoot)) {
                   5526:         my $tryserver;
                   5527:         my %alldom=();
1.800     albertel 5528:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5529:             $alldom{$hostdom{$tryserver}}=1;
                   5530:         }
                   5531:         my $alldomstr='';
1.800     albertel 5532:         foreach my $domain (sort(keys(%alldom))) {
                   5533:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5534:         }
                   5535:         $alldomstr=~s/:$//;
                   5536:         return split(/:/,$alldomstr);       
                   5537:     } else {
1.800     albertel 5538:         return ('missing domain');
1.275     stredwic 5539:     }
                   5540: }
                   5541: 
                   5542: # --------------------------------------------- GetFileTimestamp
                   5543: # This function utilizes dirlist and returns the date stamp for
                   5544: # when it was last modified.  It will also return an error of -1
                   5545: # if an error occurs
                   5546: 
1.410     matthew  5547: ##
                   5548: ## FIXME: This subroutine assumes its caller knows something about the
                   5549: ## directory structure of the home server for the student ($root).
                   5550: ## Not a good assumption to make.  Since this is for looking up files
                   5551: ## in user directories, the full path should be constructed by lond, not
                   5552: ## whatever machine we request data from.
                   5553: ##
1.275     stredwic 5554: sub GetFileTimestamp {
                   5555:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5556:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5557:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5558:     my $subdir=$studentName.'__';
                   5559:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5560:     my $proname="$studentDomain/$subdir/$studentName";
                   5561:     $proname .= '/'.$filename;
1.375     matthew  5562:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5563:                                               $studentName, $root);
1.275     stredwic 5564:     my @stats = split('&', $fileStat);
                   5565:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5566:         # @stats contains first the filename, then the stat output
                   5567:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5568:     } else {
                   5569:         return -1;
1.253     stredwic 5570:     }
1.26      www      5571: }
                   5572: 
1.712     albertel 5573: sub stat_file {
                   5574:     my ($uri) = @_;
1.787     albertel 5575:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5576: 
1.712     albertel 5577:     my ($udom,$uname,$file,$dir);
                   5578:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5579: 	($udom,$uname,$file) =
1.811     albertel 5580: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5581: 	$file = 'userfiles/'.$file;
1.740     www      5582: 	$dir = &propath($udom,$uname);
1.712     albertel 5583:     }
                   5584:     if ($uri =~ m-^/res/-) {
                   5585: 	($udom,$uname) = 
1.807     albertel 5586: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5587: 	$file = $uri;
                   5588:     }
                   5589: 
                   5590:     if (!$udom || !$uname || !$file) {
                   5591: 	# unable to handle the uri
                   5592: 	return ();
                   5593:     }
                   5594: 
                   5595:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5596:     my @stats = split('&', $result);
1.721     banghart 5597:     
1.712     albertel 5598:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5599: 	shift(@stats); #filename is first
                   5600: 	return @stats;
                   5601:     }
                   5602:     return ();
                   5603: }
                   5604: 
1.26      www      5605: # -------------------------------------------------------- Value of a Condition
                   5606: 
1.713     albertel 5607: # gets the value of a specific preevaluated condition
                   5608: #    stored in the string  $env{user.state.<cid>}
                   5609: # or looks up a condition reference in the bighash and if if hasn't
                   5610: # already been evaluated recurses into docondval to get the value of
                   5611: # the condition, then memoizing it to 
                   5612: #   $env{user.state.<cid>.<condition>}
1.40      www      5613: sub directcondval {
                   5614:     my $number=shift;
1.620     albertel 5615:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5616: 	&Apache::lonuserstate::evalstate();
                   5617:     }
1.713     albertel 5618:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5619: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5620:     } elsif ($number =~ /^_/) {
                   5621: 	my $sub_condition;
                   5622: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5623: 		&GDBM_READER(),0640)) {
                   5624: 	    $sub_condition=$bighash{'conditions'.$number};
                   5625: 	    untie(%bighash);
                   5626: 	}
                   5627: 	my $value = &docondval($sub_condition);
                   5628: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5629: 	return $value;
                   5630:     }
1.620     albertel 5631:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5632:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5633:     } else {
                   5634:        return 2;
                   5635:     }
                   5636: }
                   5637: 
1.713     albertel 5638: # get the collection of conditions for this resource
1.26      www      5639: sub condval {
                   5640:     my $condidx=shift;
1.54      www      5641:     my $allpathcond='';
1.713     albertel 5642:     foreach my $cond (split(/\|/,$condidx)) {
                   5643: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5644: 	    $allpathcond.=
                   5645: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5646: 	}
1.191     harris41 5647:     }
1.54      www      5648:     $allpathcond=~s/\|$//;
1.713     albertel 5649:     return &docondval($allpathcond);
                   5650: }
                   5651: 
                   5652: #evaluates an expression of conditions
                   5653: sub docondval {
                   5654:     my ($allpathcond) = @_;
                   5655:     my $result=0;
                   5656:     if ($env{'request.course.id'}
                   5657: 	&& defined($allpathcond)) {
                   5658: 	my $operand='|';
                   5659: 	my @stack;
                   5660: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5661: 	    if ($chunk eq '(') {
                   5662: 		push @stack,($operand,$result);
                   5663: 	    } elsif ($chunk eq ')') {
                   5664: 		my $before=pop @stack;
                   5665: 		if (pop @stack eq '&') {
                   5666: 		    $result=$result>$before?$before:$result;
                   5667: 		} else {
                   5668: 		    $result=$result>$before?$result:$before;
                   5669: 		}
                   5670: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5671: 		$operand=$chunk;
                   5672: 	    } else {
                   5673: 		my $new=directcondval($chunk);
                   5674: 		if ($operand eq '&') {
                   5675: 		    $result=$result>$new?$new:$result;
                   5676: 		} else {
                   5677: 		    $result=$result>$new?$result:$new;
                   5678: 		}
                   5679: 	    }
                   5680: 	}
1.26      www      5681:     }
                   5682:     return $result;
1.421     albertel 5683: }
                   5684: 
                   5685: # ---------------------------------------------------- Devalidate courseresdata
                   5686: 
                   5687: sub devalidatecourseresdata {
                   5688:     my ($coursenum,$coursedomain)=@_;
                   5689:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5690:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5691: }
                   5692: 
1.763     www      5693: 
1.200     www      5694: # --------------------------------------------------- Course Resourcedata Query
                   5695: 
1.624     albertel 5696: sub get_courseresdata {
                   5697:     my ($coursenum,$coursedomain)=@_;
1.200     www      5698:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5699:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5700:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5701:     my %dumpreply;
1.417     albertel 5702:     unless (defined($cached)) {
1.624     albertel 5703: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5704: 	$result=\%dumpreply;
1.251     albertel 5705: 	my ($tmp) = keys(%dumpreply);
                   5706: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5707: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5708: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5709: 	    return $tmp;
1.416     albertel 5710: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5711: 	    $result=undef;
1.599     albertel 5712: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5713: 	}
                   5714:     }
1.624     albertel 5715:     return $result;
                   5716: }
                   5717: 
1.633     albertel 5718: sub devalidateuserresdata {
                   5719:     my ($uname,$udom)=@_;
                   5720:     my $hashid="$udom:$uname";
                   5721:     &devalidate_cache_new('userres',$hashid);
                   5722: }
                   5723: 
1.624     albertel 5724: sub get_userresdata {
                   5725:     my ($uname,$udom)=@_;
                   5726:     #most student don\'t have any data set, check if there is some data
                   5727:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5728: 
                   5729:     my $hashid="$udom:$uname";
                   5730:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5731:     if (!defined($cached)) {
                   5732: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5733: 	$result=\%resourcedata;
                   5734: 	&do_cache_new('userres',$hashid,$result,600);
                   5735:     }
                   5736:     my ($tmp)=keys(%$result);
                   5737:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5738: 	return $result;
                   5739:     }
                   5740:     #error 2 occurs when the .db doesn't exist
                   5741:     if ($tmp!~/error: 2 /) {
1.672     albertel 5742: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5743: 		 " Trying to get resource data for ".
                   5744: 		 $uname." at ".$udom.": ".
                   5745: 		 $tmp."</font>");
                   5746:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5747: 	#&EXT_cache_set($udom,$uname);
                   5748: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5749: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5750:     }
                   5751:     return $tmp;
                   5752: }
                   5753: 
                   5754: sub resdata {
                   5755:     my ($name,$domain,$type,@which)=@_;
                   5756:     my $result;
                   5757:     if ($type eq 'course') {
                   5758: 	$result=&get_courseresdata($name,$domain);
                   5759:     } elsif ($type eq 'user') {
                   5760: 	$result=&get_userresdata($name,$domain);
                   5761:     }
                   5762:     if (!ref($result)) { return $result; }    
1.251     albertel 5763:     foreach my $item (@which) {
1.417     albertel 5764: 	if (defined($result->{$item})) {
                   5765: 	    return $result->{$item};
1.251     albertel 5766: 	}
1.250     albertel 5767:     }
1.291     albertel 5768:     return undef;
1.200     www      5769: }
                   5770: 
1.379     matthew  5771: #
                   5772: # EXT resource caching routines
                   5773: #
                   5774: 
                   5775: sub clear_EXT_cache_status {
1.383     albertel 5776:     &delenv('cache.EXT.');
1.379     matthew  5777: }
                   5778: 
                   5779: sub EXT_cache_status {
                   5780:     my ($target_domain,$target_user) = @_;
1.383     albertel 5781:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5782:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5783:         # We know already the user has no data
                   5784:         return 1;
                   5785:     } else {
                   5786:         return 0;
                   5787:     }
                   5788: }
                   5789: 
                   5790: sub EXT_cache_set {
                   5791:     my ($target_domain,$target_user) = @_;
1.383     albertel 5792:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5793:     #&appenv($cachename => time);
1.379     matthew  5794: }
                   5795: 
1.28      www      5796: # --------------------------------------------------------- Value of a Variable
1.58      www      5797: sub EXT {
1.715     albertel 5798: 
1.395     albertel 5799:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5800:     unless ($varname) { return ''; }
1.218     albertel 5801:     #get real user name/domain, courseid and symb
                   5802:     my $courseid;
1.359     albertel 5803:     my $publicuser;
1.427     www      5804:     if ($symbparm) {
                   5805: 	$symbparm=&get_symb_from_alias($symbparm);
                   5806:     }
1.218     albertel 5807:     if (!($uname && $udom)) {
1.790     albertel 5808:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5809:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5810:     } else {
1.620     albertel 5811: 	$courseid=$env{'request.course.id'};
1.218     albertel 5812:     }
1.48      www      5813:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5814:     my $rest;
1.320     albertel 5815:     if (defined($therest[0])) {
1.48      www      5816:        $rest=join('.',@therest);
                   5817:     } else {
                   5818:        $rest='';
                   5819:     }
1.320     albertel 5820: 
1.57      www      5821:     my $qualifierrest=$qualifier;
                   5822:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5823:     my $spacequalifierrest=$space;
                   5824:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5825:     if ($realm eq 'user') {
1.48      www      5826: # --------------------------------------------------------------- user.resource
                   5827: 	if ($space eq 'resource') {
1.651     albertel 5828: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5829: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5830: 		 &&
1.744     albertel 5831: 		 ($symbparm eq &symbread()) ) {	
                   5832: 		# if we are in the middle of processing the resource the
                   5833: 		# get the value we are planning on committing
                   5834:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5835:                     return $Apache::lonhomework::results{$qualifierrest};
                   5836:                 } else {
                   5837:                     return $Apache::lonhomework::history{$qualifierrest};
                   5838:                 }
1.335     albertel 5839: 	    } else {
1.359     albertel 5840: 		my %restored;
1.620     albertel 5841: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5842: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5843: 		} else {
                   5844: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5845: 		}
1.335     albertel 5846: 		return $restored{$qualifierrest};
                   5847: 	    }
1.48      www      5848: # ----------------------------------------------------------------- user.access
                   5849:         } elsif ($space eq 'access') {
1.218     albertel 5850: 	    # FIXME - not supporting calls for a specific user
1.48      www      5851:             return &allowed($qualifier,$rest);
                   5852: # ------------------------------------------ user.preferences, user.environment
                   5853:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5854: 	    if (($uname eq $env{'user.name'}) &&
                   5855: 		($udom eq $env{'user.domain'})) {
                   5856: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5857: 	    } else {
1.359     albertel 5858: 		my %returnhash;
                   5859: 		if (!$publicuser) {
                   5860: 		    %returnhash=&userenvironment($udom,$uname,
                   5861: 						 $qualifierrest);
                   5862: 		}
1.218     albertel 5863: 		return $returnhash{$qualifierrest};
                   5864: 	    }
1.48      www      5865: # ----------------------------------------------------------------- user.course
                   5866:         } elsif ($space eq 'course') {
1.218     albertel 5867: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5868:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5869: # ------------------------------------------------------------------- user.role
                   5870:         } elsif ($space eq 'role') {
1.218     albertel 5871: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5872:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5873:             if ($qualifier eq 'value') {
                   5874: 		return $role;
                   5875:             } elsif ($qualifier eq 'extent') {
                   5876:                 return $where;
                   5877:             }
                   5878: # ----------------------------------------------------------------- user.domain
                   5879:         } elsif ($space eq 'domain') {
1.218     albertel 5880:             return $udom;
1.48      www      5881: # ------------------------------------------------------------------- user.name
                   5882:         } elsif ($space eq 'name') {
1.218     albertel 5883:             return $uname;
1.48      www      5884: # ---------------------------------------------------- Any other user namespace
1.29      www      5885:         } else {
1.359     albertel 5886: 	    my %reply;
                   5887: 	    if (!$publicuser) {
                   5888: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5889: 	    }
                   5890: 	    return $reply{$qualifierrest};
1.48      www      5891:         }
1.236     www      5892:     } elsif ($realm eq 'query') {
                   5893: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5894:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5895: 						[$spacequalifierrest]);
1.620     albertel 5896: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5897:    } elsif ($realm eq 'request') {
1.48      www      5898: # ------------------------------------------------------------- request.browser
                   5899:         if ($space eq 'browser') {
1.430     www      5900: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5901: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5902: 		    return 1;
                   5903: 		} else {
                   5904: 		    return 0;
                   5905: 		}
                   5906: 	    } else {
1.620     albertel 5907: 		return $env{'browser.'.$qualifier};
1.430     www      5908: 	    }
1.57      www      5909: # ------------------------------------------------------------ request.filename
                   5910:         } else {
1.620     albertel 5911:             return $env{'request.'.$spacequalifierrest};
1.29      www      5912:         }
1.28      www      5913:     } elsif ($realm eq 'course') {
1.48      www      5914: # ---------------------------------------------------------- course.description
1.620     albertel 5915:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5916:     } elsif ($realm eq 'resource') {
1.165     www      5917: 
1.620     albertel 5918: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5919: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5920: 	}
1.693     albertel 5921: 
                   5922: 	if ($space eq 'title') {
                   5923: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5924: 	    return &gettitle($symbparm);
                   5925: 	}
                   5926: 	
                   5927: 	if ($space eq 'map') {
                   5928: 	    my ($map) = &decode_symb($symbparm);
                   5929: 	    return &symbread($map);
                   5930: 	}
                   5931: 
                   5932: 	my ($section, $group, @groups);
1.593     albertel 5933: 	my ($courselevelm,$courselevel);
1.539     albertel 5934: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5935: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5936: 
1.218     albertel 5937: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5938: 
1.60      www      5939: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5940: 	    my $symbp=$symbparm;
1.735     albertel 5941: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5942: 
                   5943: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5944: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5945: 
1.620     albertel 5946: 	    if (($env{'user.name'} eq $uname) &&
                   5947: 		($env{'user.domain'} eq $udom)) {
                   5948: 		$section=$env{'request.course.sec'};
1.733     raeburn  5949:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5950:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5951: 	    } else {
1.539     albertel 5952: 		if (! defined($usection)) {
1.551     albertel 5953: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5954: 		} else {
                   5955: 		    $section = $usection;
                   5956: 		}
1.733     raeburn  5957:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5958: 	    }
                   5959: 
                   5960: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5961: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5962: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5963: 
1.593     albertel 5964: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5965: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5966: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5967: 
1.60      www      5968: # ----------------------------------------------------------- first, check user
1.624     albertel 5969: 
                   5970: 	    my $userreply=&resdata($uname,$udom,'user',
                   5971: 				       ($courselevelr,$courselevelm,
                   5972: 					$courselevel));
                   5973: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5974: 
1.594     albertel 5975: # ------------------------------------------------ second, check some of course
1.684     raeburn  5976:             my $coursereply;
1.691     raeburn  5977:             if (@groups > 0) {
                   5978:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5979:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5980:                 if (defined($coursereply)) { return $coursereply; }
                   5981:             }
1.96      www      5982: 
1.684     raeburn  5983: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5984: 				     $env{'course.'.$courseid.'.domain'},
                   5985: 				     'course',
                   5986: 				     ($seclevelr,$seclevelm,$seclevel,
                   5987: 				      $courselevelr));
1.287     albertel 5988: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5989: 
1.60      www      5990: # ------------------------------------------------------ third, check map parms
1.218     albertel 5991: 	    my %parmhash=();
                   5992: 	    my $thisparm='';
                   5993: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5994: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5995: 		    &GDBM_READER(),0640)) {
1.218     albertel 5996: 		$thisparm=$parmhash{$symbparm};
                   5997: 		untie(%parmhash);
                   5998: 	    }
                   5999: 	    if ($thisparm) { return $thisparm; }
                   6000: 	}
1.594     albertel 6001: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6002: 
1.218     albertel 6003: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6004: 	my $filename;
                   6005: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6006: 	if ($symbparm) {
1.409     www      6007: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6008: 	} else {
1.620     albertel 6009: 	    $filename=$env{'request.filename'};
1.282     albertel 6010: 	}
                   6011: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6012: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6013: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6014: 	if (defined($metadata)) { return $metadata; }
1.142     www      6015: 
1.594     albertel 6016: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6017: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6018: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6019: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6020: 				     $env{'course.'.$courseid.'.domain'},
                   6021: 				     'course',
                   6022: 				     ($courselevelm,$courselevel));
1.593     albertel 6023: 	    if (defined($coursereply)) { return $coursereply; }
                   6024: 	}
1.145     www      6025: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6026: 	unless ($space eq '0') {
1.336     albertel 6027: 	    my @parts=split(/_/,$space);
                   6028: 	    my $id=pop(@parts);
                   6029: 	    my $part=join('_',@parts);
                   6030: 	    if ($part eq '') { $part='0'; }
                   6031: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6032: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6033: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6034: 	}
1.395     albertel 6035: 	if ($recurse) { return undef; }
                   6036: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6037: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6038: 
1.48      www      6039: # ---------------------------------------------------- Any other user namespace
                   6040:     } elsif ($realm eq 'environment') {
                   6041: # ----------------------------------------------------------------- environment
1.620     albertel 6042: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6043: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6044: 	} else {
1.770     albertel 6045: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6046: 		return '';
                   6047: 	    }
1.219     albertel 6048: 	    my %returnhash=&userenvironment($udom,$uname,
                   6049: 					    $spacequalifierrest);
                   6050: 	    return $returnhash{$spacequalifierrest};
                   6051: 	}
1.28      www      6052:     } elsif ($realm eq 'system') {
1.48      www      6053: # ----------------------------------------------------------------- system.time
                   6054: 	if ($space eq 'time') {
                   6055: 	    return time;
                   6056:         }
1.696     albertel 6057:     } elsif ($realm eq 'server') {
                   6058: # ----------------------------------------------------------------- system.time
                   6059: 	if ($space eq 'name') {
                   6060: 	    return $ENV{'SERVER_NAME'};
                   6061:         }
1.28      www      6062:     }
1.48      www      6063:     return '';
1.61      www      6064: }
                   6065: 
1.691     raeburn  6066: sub check_group_parms {
                   6067:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6068:     my @groupitems = ();
                   6069:     my $resultitem;
                   6070:     my @levels = ($symbparm,$mapparm,$what);
                   6071:     foreach my $group (@{$groups}) {
                   6072:         foreach my $level (@levels) {
                   6073:              my $item = $courseid.'.['.$group.'].'.$level;
                   6074:              push(@groupitems,$item);
                   6075:         }
                   6076:     }
                   6077:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6078:                             $env{'course.'.$courseid.'.domain'},
                   6079:                                      'course',@groupitems);
                   6080:     return $coursereply;
                   6081: }
                   6082: 
                   6083: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6084:     my ($courseid,@groups) = @_;
                   6085:     @groups = sort(@groups);
1.691     raeburn  6086:     return @groups;
                   6087: }
                   6088: 
1.395     albertel 6089: sub packages_tab_default {
                   6090:     my ($uri,$varname)=@_;
                   6091:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6092: 
                   6093:     my (@extension,@specifics,$do_default);
                   6094:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6095: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6096: 	if ($pack_type eq 'default') {
                   6097: 	    $do_default=1;
                   6098: 	} elsif ($pack_type eq 'extension') {
                   6099: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6100: 	} else {
                   6101: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6102: 	}
                   6103:     }
                   6104:     # first look for a package that matches the requested part id
                   6105:     foreach my $package (@specifics) {
                   6106: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6107: 	next if ($pack_part ne $part);
                   6108: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6109: 	    return $packagetab{"$pack_type&$name&default"};
                   6110: 	}
                   6111:     }
                   6112:     # look for any possible matching non extension_ package
                   6113:     foreach my $package (@specifics) {
                   6114: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6115: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6116: 	    return $packagetab{"$pack_type&$name&default"};
                   6117: 	}
1.585     albertel 6118: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6119: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6120: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6121: 	}
                   6122:     }
1.738     albertel 6123:     # look for any posible extension_ match
                   6124:     foreach my $package (@extension) {
                   6125: 	my ($package,$pack_type)=@{$package};
                   6126: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6127: 	    return $packagetab{"$pack_type&$name&default"};
                   6128: 	}
                   6129: 	if (defined($packagetab{$package."&$name&default"})) {
                   6130: 	    return $packagetab{$package."&$name&default"};
                   6131: 	}
                   6132:     }
                   6133:     # look for a global default setting
                   6134:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6135: 	return $packagetab{"default&$name&default"};
                   6136:     }
1.395     albertel 6137:     return undef;
                   6138: }
                   6139: 
1.334     albertel 6140: sub add_prefix_and_part {
                   6141:     my ($prefix,$part)=@_;
                   6142:     my $keyroot;
                   6143:     if (defined($prefix) && $prefix !~ /^__/) {
                   6144: 	# prefix that has a part already
                   6145: 	$keyroot=$prefix;
                   6146:     } elsif (defined($prefix)) {
                   6147: 	# prefix that is missing a part
                   6148: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6149:     } else {
                   6150: 	# no prefix at all
                   6151: 	if (defined($part)) { $keyroot='_'.$part; }
                   6152:     }
                   6153:     return $keyroot;
                   6154: }
                   6155: 
1.71      www      6156: # ---------------------------------------------------------------- Get metadata
                   6157: 
1.599     albertel 6158: my %metaentry;
1.71      www      6159: sub metadata {
1.176     www      6160:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6161:     $uri=&declutter($uri);
1.288     albertel 6162:     # if it is a non metadata possible uri return quickly
1.529     albertel 6163:     if (($uri eq '') || 
                   6164: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6165: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6166:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6167: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6168: 	return undef;
1.288     albertel 6169:     }
1.73      www      6170:     my $filename=$uri;
                   6171:     $uri=~s/\.meta$//;
1.172     www      6172: #
                   6173: # Is the metadata already cached?
1.177     www      6174: # Look at timestamp of caching
1.172     www      6175: # Everything is cached by the main uri, libraries are never directly cached
                   6176: #
1.428     albertel 6177:     if (!defined($liburi)) {
1.599     albertel 6178: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6179: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6180:     }
                   6181:     {
1.172     www      6182: #
                   6183: # Is this a recursive call for a library?
                   6184: #
1.599     albertel 6185: #	if (! exists($metacache{$uri})) {
                   6186: #	    $metacache{$uri}={};
                   6187: #	}
1.171     www      6188:         if ($liburi) {
                   6189: 	    $liburi=&declutter($liburi);
                   6190:             $filename=$liburi;
1.401     bowersj2 6191:         } else {
1.599     albertel 6192: 	    &devalidate_cache_new('meta',$uri);
                   6193: 	    undef(%metaentry);
1.401     bowersj2 6194: 	}
1.140     www      6195:         my %metathesekeys=();
1.73      www      6196:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6197: 	my $metastring;
1.768     albertel 6198: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6199: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6200: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6201: 	    $metastring=&getfile($file);
1.489     albertel 6202: 	}
1.208     albertel 6203:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6204:         my $token;
1.140     www      6205:         undef %metathesekeys;
1.71      www      6206:         while ($token=$parser->get_token) {
1.339     albertel 6207: 	    if ($token->[0] eq 'S') {
                   6208: 		if (defined($token->[2]->{'package'})) {
1.172     www      6209: #
                   6210: # This is a package - get package info
                   6211: #
1.339     albertel 6212: 		    my $package=$token->[2]->{'package'};
                   6213: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6214: 		    if (defined($token->[2]->{'id'})) { 
                   6215: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6216: 		    }
1.599     albertel 6217: 		    if ($metaentry{':packages'}) {
                   6218: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6219: 		    } else {
1.599     albertel 6220: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6221: 		    }
1.736     albertel 6222: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6223: 			my $part=$keyroot;
                   6224: 			$part=~s/^\_//;
1.736     albertel 6225: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6226: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6227: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6228: 			    # ignore package.tab specified default values
                   6229:                             # here &package_tab_default() will fetch those
                   6230: 			    if ($subp eq 'default') { next; }
1.736     albertel 6231: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6232: 			    my $unikey;
                   6233: 			    if ($pack =~ /_0$/) {
                   6234: 				$unikey='parameter_0_'.$name;
                   6235: 				$part=0;
                   6236: 			    } else {
                   6237: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6238: 			    }
1.339     albertel 6239: 			    if ($subp eq 'display') {
                   6240: 				$value.=' [Part: '.$part.']';
                   6241: 			    }
1.599     albertel 6242: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6243: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6244: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6245: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6246: 			    }
1.599     albertel 6247: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6248: 				$metaentry{':'.$unikey}=
                   6249: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6250: 			    }
1.339     albertel 6251: 			}
                   6252: 		    }
                   6253: 		} else {
1.172     www      6254: #
                   6255: # This is not a package - some other kind of start tag
1.339     albertel 6256: #
                   6257: 		    my $entry=$token->[1];
                   6258: 		    my $unikey;
                   6259: 		    if ($entry eq 'import') {
                   6260: 			$unikey='';
                   6261: 		    } else {
                   6262: 			$unikey=$entry;
                   6263: 		    }
                   6264: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6265: 
                   6266: 		    if (defined($token->[2]->{'id'})) { 
                   6267: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6268: 		    }
1.175     www      6269: 
1.339     albertel 6270: 		    if ($entry eq 'import') {
1.175     www      6271: #
                   6272: # Importing a library here
1.339     albertel 6273: #
                   6274: 			if ($depthcount<20) {
                   6275: 			    my $location=$parser->get_text('/import');
                   6276: 			    my $dir=$filename;
                   6277: 			    $dir=~s|[^/]*$||;
                   6278: 			    $location=&filelocation($dir,$location);
1.736     albertel 6279: 			    my $metadata = 
                   6280: 				&metadata($uri,'keys', $location,$unikey,
                   6281: 					  $depthcount+1);
                   6282: 			    foreach my $meta (split(',',$metadata)) {
                   6283: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6284: 				$metathesekeys{$meta}=1;
1.339     albertel 6285: 			    }
                   6286: 			}
                   6287: 		    } else { 
                   6288: 			
                   6289: 			if (defined($token->[2]->{'name'})) { 
                   6290: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6291: 			}
                   6292: 			$metathesekeys{$unikey}=1;
1.736     albertel 6293: 			foreach my $param (@{$token->[3]}) {
                   6294: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6295: 				$token->[2]->{$param};
1.339     albertel 6296: 			}
                   6297: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6298: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6299: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6300: 		 # only ws inside the tag, and not in default, so use default
                   6301: 		 # as value
1.599     albertel 6302: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6303: 			} else {
1.321     albertel 6304: 		  # either something interesting inside the tag or default
                   6305:                   # uninteresting
1.599     albertel 6306: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6307: 			}
1.172     www      6308: # end of not-a-package not-a-library import
1.339     albertel 6309: 		    }
1.172     www      6310: # end of not-a-package start tag
1.339     albertel 6311: 		}
1.172     www      6312: # the next is the end of "start tag"
1.339     albertel 6313: 	    }
                   6314: 	}
1.483     albertel 6315: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6316: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6317: 	    #no specific packages #how's our extension
                   6318: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6319: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6320: 					 \%metathesekeys);
                   6321: 	}
1.599     albertel 6322: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6323: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6324: 		#no specific packages well let's get default then
                   6325: 		if ($key!~/^default&/) { next; }
1.488     albertel 6326: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6327: 					     \%metathesekeys);
                   6328: 	    }
                   6329: 	}
1.338     www      6330: # are there custom rights to evaluate
1.599     albertel 6331: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6332: 
1.338     www      6333:     #
                   6334:     # Importing a rights file here
1.339     albertel 6335:     #
                   6336: 	    unless ($depthcount) {
1.599     albertel 6337: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6338: 		my $dir=$filename;
                   6339: 		$dir=~s|[^/]*$||;
                   6340: 		$location=&filelocation($dir,$location);
1.736     albertel 6341: 		my $rights_metadata =
                   6342: 		    &metadata($uri,'keys',$location,'_rights',
                   6343: 			      $depthcount+1);
                   6344: 		foreach my $rights (split(',',$rights_metadata)) {
                   6345: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6346: 		    $metathesekeys{$rights}=1;
1.339     albertel 6347: 		}
                   6348: 	    }
                   6349: 	}
1.737     albertel 6350: 	# uniqifiy package listing
                   6351: 	my %seen;
                   6352: 	my @uniq_packages =
                   6353: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6354: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6355: 
                   6356: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6357: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6358: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6359: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6360: # this is the end of "was not already recently cached
1.71      www      6361:     }
1.599     albertel 6362:     return $metaentry{':'.$what};
1.261     albertel 6363: }
                   6364: 
1.488     albertel 6365: sub metadata_create_package_def {
1.483     albertel 6366:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6367:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6368:     if ($subp eq 'default') { next; }
                   6369:     
1.599     albertel 6370:     if (defined($metaentry{':packages'})) {
                   6371: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6372:     } else {
1.599     albertel 6373: 	$metaentry{':packages'}=$package;
1.483     albertel 6374:     }
                   6375:     my $value=$packagetab{$key};
                   6376:     my $unikey;
                   6377:     $unikey='parameter_0_'.$name;
1.599     albertel 6378:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6379:     $$metathesekeys{$unikey}=1;
1.599     albertel 6380:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6381: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6382:     }
1.599     albertel 6383:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6384: 	$metaentry{':'.$unikey}=
                   6385: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6386:     }
                   6387: }
                   6388: 
1.261     albertel 6389: sub metadata_generate_part0 {
                   6390:     my ($metadata,$metacache,$uri) = @_;
                   6391:     my %allnames;
1.737     albertel 6392:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6393: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6394: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6395: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6396: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6397: 	    $allnames{$name}=$part;
                   6398: 	  }
                   6399: 	}
                   6400:     }
                   6401:     foreach my $name (keys(%allnames)) {
                   6402:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6403:       my $key=":parameter_0_$name";
1.261     albertel 6404:       $$metacache{"$key.part"}='0';
                   6405:       $$metacache{"$key.name"}=$name;
1.428     albertel 6406:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6407: 					   $allnames{$name}.'_'.$name.
                   6408: 					   '.type'};
1.428     albertel 6409:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6410: 			     '.display'};
1.644     www      6411:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6412:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6413:       $$metacache{"$key.display"}=$olddis;
                   6414:     }
1.71      www      6415: }
                   6416: 
1.764     albertel 6417: # ------------------------------------------------------ Devalidate title cache
                   6418: 
                   6419: sub devalidate_title_cache {
                   6420:     my ($url)=@_;
                   6421:     if (!$env{'request.course.id'}) { return; }
                   6422:     my $symb=&symbread($url);
                   6423:     if (!$symb) { return; }
                   6424:     my $key=$env{'request.course.id'}."\0".$symb;
                   6425:     &devalidate_cache_new('title',$key);
                   6426: }
                   6427: 
1.301     www      6428: # ------------------------------------------------- Get the title of a resource
                   6429: 
                   6430: sub gettitle {
                   6431:     my $urlsymb=shift;
                   6432:     my $symb=&symbread($urlsymb);
1.534     albertel 6433:     if ($symb) {
1.620     albertel 6434: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6435: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6436: 	if (defined($cached)) { 
                   6437: 	    return $result;
                   6438: 	}
1.534     albertel 6439: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6440: 	my $title='';
                   6441: 	my %bighash;
1.620     albertel 6442: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6443: 		&GDBM_READER(),0640)) {
                   6444: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6445: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6446: 	    untie %bighash;
                   6447: 	}
                   6448: 	$title=~s/\&colon\;/\:/gs;
                   6449: 	if ($title) {
1.599     albertel 6450: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6451: 	}
                   6452: 	$urlsymb=$url;
                   6453:     }
                   6454:     my $title=&metadata($urlsymb,'title');
                   6455:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6456:     return $title;
1.301     www      6457: }
1.613     albertel 6458: 
1.614     albertel 6459: sub get_slot {
                   6460:     my ($which,$cnum,$cdom)=@_;
                   6461:     if (!$cnum || !$cdom) {
1.790     albertel 6462: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6463: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6464: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6465:     }
1.703     albertel 6466:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6467:     my %slotinfo;
                   6468:     if (exists($remembered{$key})) {
                   6469: 	$slotinfo{$which} = $remembered{$key};
                   6470:     } else {
                   6471: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6472: 	&Apache::lonhomework::showhash(%slotinfo);
                   6473: 	my ($tmp)=keys(%slotinfo);
                   6474: 	if ($tmp=~/^error:/) { return (); }
                   6475: 	$remembered{$key} = $slotinfo{$which};
                   6476:     }
1.616     albertel 6477:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6478: 	return %{$slotinfo{$which}};
                   6479:     }
                   6480:     return $slotinfo{$which};
1.614     albertel 6481: }
1.31      www      6482: # ------------------------------------------------- Update symbolic store links
                   6483: 
                   6484: sub symblist {
                   6485:     my ($mapname,%newhash)=@_;
1.438     www      6486:     $mapname=&deversion(&declutter($mapname));
1.31      www      6487:     my %hash;
1.620     albertel 6488:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6489:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6490:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6491: 	    foreach my $url (keys %newhash) {
                   6492: 		next if ($url eq 'last_known'
                   6493: 			 && $env{'form.no_update_last_known'});
                   6494: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6495: 						    $newhash{$url}->[1],
                   6496: 						    $newhash{$url}->[0]);
1.191     harris41 6497:             }
1.31      www      6498:             if (untie(%hash)) {
                   6499: 		return 'ok';
                   6500:             }
                   6501:         }
                   6502:     }
                   6503:     return 'error';
1.212     www      6504: }
                   6505: 
                   6506: # --------------------------------------------------------------- Verify a symb
                   6507: 
                   6508: sub symbverify {
1.510     www      6509:     my ($symb,$thisurl)=@_;
                   6510:     my $thisfn=$thisurl;
1.439     www      6511:     $thisfn=&declutter($thisfn);
1.215     www      6512: # direct jump to resource in page or to a sequence - will construct own symbs
                   6513:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6514: # check URL part
1.409     www      6515:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6516: 
1.431     www      6517:     unless ($url eq $thisfn) { return 0; }
1.213     www      6518: 
1.216     www      6519:     $symb=&symbclean($symb);
1.510     www      6520:     $thisurl=&deversion($thisurl);
1.439     www      6521:     $thisfn=&deversion($thisfn);
1.213     www      6522: 
                   6523:     my %bighash;
                   6524:     my $okay=0;
1.431     www      6525: 
1.620     albertel 6526:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6527:                             &GDBM_READER(),0640)) {
1.510     www      6528:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6529:         unless ($ids) { 
1.510     www      6530:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6531:         }
                   6532:         if ($ids) {
                   6533: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6534: 	    foreach my $id (split(/\,/,$ids)) {
                   6535: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6536:                if (
                   6537:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6538:    eq $symb) { 
1.620     albertel 6539: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6540: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6541: 		       $okay=1; 
                   6542: 		   }
                   6543: 	       }
1.216     www      6544: 	   }
                   6545:         }
1.213     www      6546: 	untie(%bighash);
                   6547:     }
                   6548:     return $okay;
1.31      www      6549: }
                   6550: 
1.210     www      6551: # --------------------------------------------------------------- Clean-up symb
                   6552: 
                   6553: sub symbclean {
                   6554:     my $symb=shift;
1.568     albertel 6555:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6556: # remove version from map
                   6557:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6558: 
1.210     www      6559: # remove version from URL
                   6560:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6561: 
1.507     www      6562: # remove wrapper
                   6563: 
1.510     www      6564:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6565:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6566:     return $symb;
1.409     www      6567: }
                   6568: 
                   6569: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6570: 
                   6571: sub encode_symb {
                   6572:     my ($map,$resid,$url)=@_;
                   6573:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6574: }
1.409     www      6575: 
                   6576: sub decode_symb {
1.568     albertel 6577:     my $symb=shift;
                   6578:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6579:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6580:     return (&fixversion($map),$resid,&fixversion($url));
                   6581: }
                   6582: 
                   6583: sub fixversion {
                   6584:     my $fn=shift;
1.609     banghart 6585:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6586:     my %bighash;
                   6587:     my $uri=&clutter($fn);
1.620     albertel 6588:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6589: # is this cached?
1.599     albertel 6590:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6591:     if (defined($cached)) { return $result; }
                   6592: # unfortunately not cached, or expired
1.620     albertel 6593:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6594: 	    &GDBM_READER(),0640)) {
                   6595:  	if ($bighash{'version_'.$uri}) {
                   6596:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6597:  	    unless (($version eq 'mostrecent') || 
                   6598: 		    ($version==&getversion($uri))) {
1.440     www      6599:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6600:  	    }
                   6601:  	}
                   6602:  	untie %bighash;
1.413     www      6603:     }
1.599     albertel 6604:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6605: }
                   6606: 
                   6607: sub deversion {
                   6608:     my $url=shift;
                   6609:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6610:     return $url;
1.210     www      6611: }
                   6612: 
1.31      www      6613: # ------------------------------------------------------ Return symb list entry
                   6614: 
                   6615: sub symbread {
1.249     www      6616:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6617:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6618:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6619: # no filename provided? try from environment
1.44      www      6620:     unless ($thisfn) {
1.620     albertel 6621:         if ($env{'request.symb'}) {
                   6622: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6623: 	}
1.620     albertel 6624: 	$thisfn=$env{'request.filename'};
1.44      www      6625:     }
1.569     albertel 6626:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6627: # is that filename actually a symb? Verify, clean, and return
                   6628:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6629: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6630: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6631: 	}
1.242     www      6632:     }
1.44      www      6633:     $thisfn=declutter($thisfn);
1.31      www      6634:     my %hash;
1.37      www      6635:     my %bighash;
                   6636:     my $syval='';
1.620     albertel 6637:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6638:         my $targetfn = $thisfn;
1.609     banghart 6639:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6640:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6641:         }
1.687     albertel 6642: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6643: 	    $targetfn=$1;
                   6644: 	}
1.620     albertel 6645:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6646:                       &GDBM_READER(),0640)) {
1.481     raeburn  6647: 	    $syval=$hash{$targetfn};
1.37      www      6648:             untie(%hash);
                   6649:         }
                   6650: # ---------------------------------------------------------- There was an entry
                   6651:         if ($syval) {
1.601     albertel 6652: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6653: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6654: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6655: 		    #return $env{$cache_str}='';
1.601     albertel 6656: 		#}    
                   6657: 		#$syval.=$1;
                   6658: 	    #}
1.37      www      6659:         } else {
                   6660: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6661:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6662:                             &GDBM_READER(),0640)) {
1.37      www      6663: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6664:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6665:               unless ($ids) { 
                   6666:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6667:               }
                   6668:               unless ($ids) {
                   6669: # alias?
                   6670: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6671:               }
1.37      www      6672:               if ($ids) {
                   6673: # ------------------------------------------------------------------- Has ID(s)
                   6674:                  my @possibilities=split(/\,/,$ids);
1.39      www      6675:                  if ($#possibilities==0) {
                   6676: # ----------------------------------------------- There is only one possibility
1.37      www      6677: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6678: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6679: 						    $resid,$thisfn);
1.249     www      6680:                  } elsif (!$donotrecurse) {
1.39      www      6681: # ------------------------------------------ There is more than one possibility
                   6682:                      my $realpossible=0;
1.800     albertel 6683:                      foreach my $id (@possibilities) {
                   6684: 			 my $file=$bighash{'src_'.$id};
1.39      www      6685:                          if (&allowed('bre',$file)) {
1.800     albertel 6686:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6687:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6688: 				$realpossible++;
1.626     albertel 6689:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6690: 						    $resid,$thisfn);
1.39      www      6691:                             }
                   6692: 			 }
1.191     harris41 6693:                      }
1.39      www      6694: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6695:                  } else {
                   6696:                      $syval='';
1.37      www      6697:                  }
                   6698: 	      }
                   6699:               untie(%bighash)
1.481     raeburn  6700:            }
1.31      www      6701:         }
1.62      www      6702:         if ($syval) {
1.620     albertel 6703: 	    return $env{$cache_str}=$syval;
1.62      www      6704:         }
1.31      www      6705:     }
1.44      www      6706:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6707:     return $env{$cache_str}='';
1.31      www      6708: }
                   6709: 
                   6710: # ---------------------------------------------------------- Return random seed
                   6711: 
1.32      www      6712: sub numval {
                   6713:     my $txt=shift;
                   6714:     $txt=~tr/A-J/0-9/;
                   6715:     $txt=~tr/a-j/0-9/;
                   6716:     $txt=~tr/K-T/0-9/;
                   6717:     $txt=~tr/k-t/0-9/;
                   6718:     $txt=~tr/U-Z/0-5/;
                   6719:     $txt=~tr/u-z/0-5/;
                   6720:     $txt=~s/\D//g;
1.564     albertel 6721:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6722:     return int($txt);
1.368     albertel 6723: }
                   6724: 
1.484     albertel 6725: sub numval2 {
                   6726:     my $txt=shift;
                   6727:     $txt=~tr/A-J/0-9/;
                   6728:     $txt=~tr/a-j/0-9/;
                   6729:     $txt=~tr/K-T/0-9/;
                   6730:     $txt=~tr/k-t/0-9/;
                   6731:     $txt=~tr/U-Z/0-5/;
                   6732:     $txt=~tr/u-z/0-5/;
                   6733:     $txt=~s/\D//g;
                   6734:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6735:     my $total;
                   6736:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6737:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6738:     return int($total);
                   6739: }
                   6740: 
1.575     albertel 6741: sub numval3 {
                   6742:     use integer;
                   6743:     my $txt=shift;
                   6744:     $txt=~tr/A-J/0-9/;
                   6745:     $txt=~tr/a-j/0-9/;
                   6746:     $txt=~tr/K-T/0-9/;
                   6747:     $txt=~tr/k-t/0-9/;
                   6748:     $txt=~tr/U-Z/0-5/;
                   6749:     $txt=~tr/u-z/0-5/;
                   6750:     $txt=~s/\D//g;
                   6751:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6752:     my $total;
                   6753:     foreach my $val (@txts) { $total+=$val; }
                   6754:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6755:     return $total;
                   6756: }
                   6757: 
1.675     albertel 6758: sub digest {
                   6759:     my ($data)=@_;
                   6760:     my $digest=&Digest::MD5::md5($data);
                   6761:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6762:     my ($e,$f);
                   6763:     {
                   6764:         use integer;
                   6765:         $e=($a+$b);
                   6766:         $f=($c+$d);
                   6767:         if ($_64bit) {
                   6768:             $e=(($e<<32)>>32);
                   6769:             $f=(($f<<32)>>32);
                   6770:         }
                   6771:     }
                   6772:     if (wantarray) {
                   6773: 	return ($e,$f);
                   6774:     } else {
                   6775: 	my $g;
                   6776: 	{
                   6777: 	    use integer;
                   6778: 	    $g=($e+$f);
                   6779: 	    if ($_64bit) {
                   6780: 		$g=(($g<<32)>>32);
                   6781: 	    }
                   6782: 	}
                   6783: 	return $g;
                   6784:     }
                   6785: }
                   6786: 
1.368     albertel 6787: sub latest_rnd_algorithm_id {
1.675     albertel 6788:     return '64bit5';
1.366     albertel 6789: }
1.32      www      6790: 
1.503     albertel 6791: sub get_rand_alg {
                   6792:     my ($courseid)=@_;
1.790     albertel 6793:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6794:     if ($courseid) {
1.620     albertel 6795: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6796:     }
                   6797:     return &latest_rnd_algorithm_id();
                   6798: }
                   6799: 
1.562     albertel 6800: sub validCODE {
                   6801:     my ($CODE)=@_;
                   6802:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6803:     return 0;
                   6804: }
                   6805: 
1.491     albertel 6806: sub getCODE {
1.620     albertel 6807:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6808:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6809: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6810: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6811: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6812:     }
                   6813:     return undef;
                   6814: }
                   6815: 
1.31      www      6816: sub rndseed {
1.155     albertel 6817:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6818: 
1.790     albertel 6819:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6820:     if (!$symb) {
1.366     albertel 6821: 	unless ($symb=$wsymb) { return time; }
                   6822:     }
                   6823:     if (!$courseid) { $courseid=$wcourseid; }
                   6824:     if (!$domain) { $domain=$wdomain; }
                   6825:     if (!$username) { $username=$wusername }
1.503     albertel 6826:     my $which=&get_rand_alg();
1.803     albertel 6827: 
1.491     albertel 6828:     if (defined(&getCODE())) {
1.675     albertel 6829: 	if ($which eq '64bit5') {
                   6830: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6831: 	} elsif ($which eq '64bit4') {
1.575     albertel 6832: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6833: 	} else {
                   6834: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6835: 	}
1.675     albertel 6836:     } elsif ($which eq '64bit5') {
                   6837: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6838:     } elsif ($which eq '64bit4') {
                   6839: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6840:     } elsif ($which eq '64bit3') {
                   6841: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6842:     } elsif ($which eq '64bit2') {
                   6843: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6844:     } elsif ($which eq '64bit') {
                   6845: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6846:     }
                   6847:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6848: }
                   6849: 
                   6850: sub rndseed_32bit {
                   6851:     my ($symb,$courseid,$domain,$username)=@_;
                   6852:     {
                   6853: 	use integer;
                   6854: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6855: 	my $symbseed=numval($symb) << 22;
                   6856: 	my $namechck=unpack("%32C*",$username) << 17;
                   6857: 	my $nameseed=numval($username) << 12;
                   6858: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6859: 	my $courseseed=unpack("%32C*",$courseid);
                   6860: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6861: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6862: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6863: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6864: 	return $num;
                   6865:     }
                   6866: }
                   6867: 
                   6868: sub rndseed_64bit {
                   6869:     my ($symb,$courseid,$domain,$username)=@_;
                   6870:     {
                   6871: 	use integer;
                   6872: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6873: 	my $symbseed=numval($symb) << 10;
                   6874: 	my $namechck=unpack("%32S*",$username);
                   6875: 	
                   6876: 	my $nameseed=numval($username) << 21;
                   6877: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6878: 	my $courseseed=unpack("%32S*",$courseid);
                   6879: 	
                   6880: 	my $num1=$symbchck+$symbseed+$namechck;
                   6881: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6882: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6883: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6884: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6885: 	return "$num1,$num2";
1.155     albertel 6886:     }
1.366     albertel 6887: }
                   6888: 
1.443     albertel 6889: sub rndseed_64bit2 {
                   6890:     my ($symb,$courseid,$domain,$username)=@_;
                   6891:     {
                   6892: 	use integer;
                   6893: 	# strings need to be an even # of cahracters long, it it is odd the
                   6894:         # last characters gets thrown away
                   6895: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6896: 	my $symbseed=numval($symb) << 10;
                   6897: 	my $namechck=unpack("%32S*",$username.' ');
                   6898: 	
                   6899: 	my $nameseed=numval($username) << 21;
1.501     albertel 6900: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6901: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6902: 	
                   6903: 	my $num1=$symbchck+$symbseed+$namechck;
                   6904: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6905: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6906: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6907: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6908: 	return "$num1,$num2";
                   6909:     }
                   6910: }
                   6911: 
                   6912: sub rndseed_64bit3 {
                   6913:     my ($symb,$courseid,$domain,$username)=@_;
                   6914:     {
                   6915: 	use integer;
                   6916: 	# strings need to be an even # of cahracters long, it it is odd the
                   6917:         # last characters gets thrown away
                   6918: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6919: 	my $symbseed=numval2($symb) << 10;
                   6920: 	my $namechck=unpack("%32S*",$username.' ');
                   6921: 	
                   6922: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6923: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6924: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6925: 	
                   6926: 	my $num1=$symbchck+$symbseed+$namechck;
                   6927: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6928: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6929: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6930: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6931: 	
1.503     albertel 6932: 	return "$num1:$num2";
1.443     albertel 6933:     }
                   6934: }
                   6935: 
1.575     albertel 6936: sub rndseed_64bit4 {
                   6937:     my ($symb,$courseid,$domain,$username)=@_;
                   6938:     {
                   6939: 	use integer;
                   6940: 	# strings need to be an even # of cahracters long, it it is odd the
                   6941:         # last characters gets thrown away
                   6942: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6943: 	my $symbseed=numval3($symb) << 10;
                   6944: 	my $namechck=unpack("%32S*",$username.' ');
                   6945: 	
                   6946: 	my $nameseed=numval3($username) << 21;
                   6947: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6948: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6949: 	
                   6950: 	my $num1=$symbchck+$symbseed+$namechck;
                   6951: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6952: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6953: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6954: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6955: 	
                   6956: 	return "$num1:$num2";
                   6957:     }
                   6958: }
                   6959: 
1.675     albertel 6960: sub rndseed_64bit5 {
                   6961:     my ($symb,$courseid,$domain,$username)=@_;
                   6962:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6963:     return "$num1:$num2";
                   6964: }
                   6965: 
1.366     albertel 6966: sub rndseed_CODE_64bit {
                   6967:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6968:     {
1.366     albertel 6969: 	use integer;
1.443     albertel 6970: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6971: 	my $symbseed=numval2($symb);
1.491     albertel 6972: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6973: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6974: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6975: 	my $num1=$symbseed+$CODEchck;
                   6976: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6977: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6978: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6979: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6980: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6981: 	return "$num1:$num2";
1.366     albertel 6982:     }
                   6983: }
                   6984: 
1.575     albertel 6985: sub rndseed_CODE_64bit4 {
                   6986:     my ($symb,$courseid,$domain,$username)=@_;
                   6987:     {
                   6988: 	use integer;
                   6989: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6990: 	my $symbseed=numval3($symb);
                   6991: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6992: 	my $CODEseed=numval3(&getCODE());
                   6993: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6994: 	my $num1=$symbseed+$CODEchck;
                   6995: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6996: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6997: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6998: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6999: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7000: 	return "$num1:$num2";
                   7001:     }
                   7002: }
                   7003: 
1.675     albertel 7004: sub rndseed_CODE_64bit5 {
                   7005:     my ($symb,$courseid,$domain,$username)=@_;
                   7006:     my $code = &getCODE();
                   7007:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7008:     return "$num1:$num2";
                   7009: }
                   7010: 
1.366     albertel 7011: sub setup_random_from_rndseed {
                   7012:     my ($rndseed)=@_;
1.503     albertel 7013:     if ($rndseed =~/([,:])/) {
                   7014: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7015: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7016:     } else {
                   7017: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7018:     }
1.36      albertel 7019: }
                   7020: 
1.474     albertel 7021: sub latest_receipt_algorithm_id {
                   7022:     return 'receipt2';
                   7023: }
                   7024: 
1.480     www      7025: sub recunique {
                   7026:     my $fucourseid=shift;
                   7027:     my $unique;
1.620     albertel 7028:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7029: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7030:     } else {
                   7031: 	$unique=$perlvar{'lonReceipt'};
                   7032:     }
                   7033:     return unpack("%32C*",$unique);
                   7034: }
                   7035: 
                   7036: sub recprefix {
                   7037:     my $fucourseid=shift;
                   7038:     my $prefix;
1.620     albertel 7039:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7040: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7041:     } else {
                   7042: 	$prefix=$perlvar{'lonHostID'};
                   7043:     }
                   7044:     return unpack("%32C*",$prefix);
                   7045: }
                   7046: 
1.76      www      7047: sub ireceipt {
1.474     albertel 7048:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      7049:     my $cuname=unpack("%32C*",$funame);
                   7050:     my $cudom=unpack("%32C*",$fudom);
                   7051:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7052:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7053:     my $cunique=&recunique($fucourseid);
1.474     albertel 7054:     my $cpart=unpack("%32S*",$part);
1.480     www      7055:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 7056:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7057: 	$env{'request.state'} eq 'construct') {
1.790     albertel 7058: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7059: 			       
                   7060: 	$return.= ($cunique%$cuname+
                   7061: 		   $cunique%$cudom+
                   7062: 		   $cusymb%$cuname+
                   7063: 		   $cusymb%$cudom+
                   7064: 		   $cucourseid%$cuname+
                   7065: 		   $cucourseid%$cudom+
                   7066: 		   $cpart%$cuname+
                   7067: 		   $cpart%$cudom);
                   7068:     } else {
                   7069: 	$return.= ($cunique%$cuname+
                   7070: 		   $cunique%$cudom+
                   7071: 		   $cusymb%$cuname+
                   7072: 		   $cusymb%$cudom+
                   7073: 		   $cucourseid%$cuname+
                   7074: 		   $cucourseid%$cudom);
                   7075:     }
                   7076:     return $return;
1.76      www      7077: }
                   7078: 
                   7079: sub receipt {
1.474     albertel 7080:     my ($part)=@_;
1.790     albertel 7081:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7082:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7083: }
1.260     ng       7084: 
1.790     albertel 7085: sub whichuser {
                   7086:     my ($passedsymb)=@_;
                   7087:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7088:     if (defined($env{'form.grade_symb'})) {
                   7089: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7090: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7091: 	if (!$allowed &&
                   7092: 	    exists($env{'request.course.sec'}) &&
                   7093: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7094: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7095: 			      '/'.$env{'request.course.sec'});
                   7096: 	}
                   7097: 	if ($allowed) {
                   7098: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7099: 	    $courseid=$tmp_courseid;
                   7100: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7101: 	    ($name)=&get_env_multiple('form.grade_username');
                   7102: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7103: 	}
                   7104:     }
                   7105:     if (!$passedsymb) {
                   7106: 	$symb=&symbread();
                   7107:     } else {
                   7108: 	$symb=$passedsymb;
                   7109:     }
                   7110:     $courseid=$env{'request.course.id'};
                   7111:     $domain=$env{'user.domain'};
                   7112:     $name=$env{'user.name'};
                   7113:     if ($name eq 'public' && $domain eq 'public') {
                   7114: 	if (!defined($env{'form.username'})) {
                   7115: 	    $env{'form.username'}.=time.rand(10000000);
                   7116: 	}
                   7117: 	$name.=$env{'form.username'};
                   7118:     }
                   7119:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7120: 
                   7121: }
                   7122: 
1.36      albertel 7123: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7124: # returns either the contents of the file or 
                   7125: # -1 if the file doesn't exist
1.481     raeburn  7126: #
                   7127: # if the target is a file that was uploaded via DOCS, 
                   7128: # a check will be made to see if a current copy exists on the local server,
                   7129: # if it does this will be served, otherwise a copy will be retrieved from
                   7130: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7131: # the local server.   
1.472     albertel 7132: 
1.36      albertel 7133: sub getfile {
1.538     albertel 7134:     my ($file) = @_;
1.609     banghart 7135:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7136:     &repcopy($file);
                   7137:     return &readfile($file);
                   7138: }
                   7139: 
                   7140: sub repcopy_userfile {
                   7141:     my ($file)=@_;
1.609     banghart 7142:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7143:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7144:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7145: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7146:     my ($info,$rtncode);
                   7147:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7148:     if (-e "$file") {
                   7149: 	my @fileinfo = stat($file);
                   7150: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7151: 	if ($lwpresp ne 'ok') {
                   7152: 	    if ($rtncode eq '404') {
1.538     albertel 7153: 		unlink($file);
1.482     albertel 7154: 	    }
1.517     albertel 7155: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7156: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7157: 	    #my $response=$ua->request($request);
                   7158: 	    #if ($response->is_success()) {
                   7159: 	#	return $response->content;
                   7160: 	#    } else {
                   7161: 	#	return -1;
                   7162: 	#    }
1.482     albertel 7163: 	    return -1;
                   7164: 	}
                   7165: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7166: 	    return 'ok';
1.482     albertel 7167: 	}
                   7168: 	$info = '';
1.538     albertel 7169: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7170: 	if ($lwpresp ne 'ok') {
                   7171: 	    return -1;
                   7172: 	}
                   7173:     } else {
1.538     albertel 7174: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7175: 	if ($lwpresp ne 'ok') {
1.824.2.2  albertel 7176: 	    return -1;
1.482     albertel 7177: 	}
                   7178: 	my @parts = ($cdom,$cnum); 
                   7179: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7180: 	    push @parts, split(/\//,$1);
1.518     albertel 7181: 	}
1.538     albertel 7182: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7183: 	foreach my $part (@parts) {
                   7184: 	    $path .= '/'.$part;
                   7185: 	    if (!-e $path) {
                   7186: 		mkdir($path,0770);
                   7187: 	    }
                   7188: 	}
                   7189:     }
1.538     albertel 7190:     open(FILE,">$file");
1.482     albertel 7191:     print FILE $info;
                   7192:     close(FILE);
1.607     raeburn  7193:     return 'ok';
1.481     raeburn  7194: }
                   7195: 
1.517     albertel 7196: sub tokenwrapper {
                   7197:     my $uri=shift;
1.552     albertel 7198:     $uri=~s|^http\://([^/]+)||;
                   7199:     $uri=~s|^/||;
1.620     albertel 7200:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7201:     my $token=$1;
1.552     albertel 7202:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7203:     if ($udom && $uname && $file) {
                   7204: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7205:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7206:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7207:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7208:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7209:     } else {
                   7210:         return '/adm/notfound.html';
                   7211:     }
                   7212: }
                   7213: 
1.481     raeburn  7214: sub getuploaded {
                   7215:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7216:     $uri=~s/^\///;
                   7217:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7218:     my $ua=new LWP::UserAgent;
                   7219:     my $request=new HTTP::Request($reqtype,$uri);
                   7220:     my $response=$ua->request($request);
                   7221:     $$rtncode = $response->code;
1.482     albertel 7222:     if (! $response->is_success()) {
                   7223: 	return 'failed';
                   7224:     }      
                   7225:     if ($reqtype eq 'HEAD') {
1.486     www      7226: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7227:     } elsif ($reqtype eq 'GET') {
                   7228: 	$$info = $response->content;
1.472     albertel 7229:     }
1.482     albertel 7230:     return 'ok';
1.36      albertel 7231: }
                   7232: 
1.481     raeburn  7233: sub readfile {
                   7234:     my $file = shift;
                   7235:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7236:     my $fh;
                   7237:     open($fh,"<$file");
                   7238:     my $a='';
1.800     albertel 7239:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7240:     return $a;
                   7241: }
                   7242: 
1.36      albertel 7243: sub filelocation {
1.590     banghart 7244:     my ($dir,$file) = @_;
                   7245:     my $location;
                   7246:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7247: 
                   7248:     if ($file =~ m-^/adm/-) {
                   7249: 	$file=~s-^/adm/wrapper/-/-;
                   7250: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7251:     }
1.590     banghart 7252:     if ($file=~m:^/~:) { # is a contruction space reference
                   7253:         $location = $file;
                   7254:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7255:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7256: 	# is a correct contruction space reference
                   7257:         $location = $file;
1.609     banghart 7258:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7259:         my ($udom,$uname,$filename)=
1.811     albertel 7260:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7261:         my $home=&homeserver($uname,$udom);
                   7262:         my $is_me=0;
                   7263:         my @ids=&current_machine_ids();
                   7264:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7265:         if ($is_me) {
1.740     www      7266:   	    $location=&propath($udom,$uname).
1.590     banghart 7267:   	      '/userfiles/'.$filename;
                   7268:         } else {
                   7269:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7270:   	      $udom.'/'.$uname.'/'.$filename;
                   7271:         }
                   7272:     } else {
                   7273:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7274:         $file=~s:^/res/:/:;
                   7275:         if ( !( $file =~ m:^/:) ) {
                   7276:             $location = $dir. '/'.$file;
                   7277:         } else {
                   7278:             $location = '/home/httpd/html/res'.$file;
                   7279:         }
1.59      albertel 7280:     }
1.590     banghart 7281:     $location=~s://+:/:g; # remove duplicate /
                   7282:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7283:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7284:     return $location;
1.46      www      7285: }
1.36      albertel 7286: 
1.46      www      7287: sub hreflocation {
                   7288:     my ($dir,$file)=@_;
1.460     albertel 7289:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7290: 	$file=filelocation($dir,$file);
1.700     albertel 7291:     } elsif ($file=~m-^/adm/-) {
                   7292: 	$file=~s-^/adm/wrapper/-/-;
                   7293: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7294:     }
                   7295:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7296: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7297:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7298: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7299:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7300: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7301: 	    -/uploaded/$1/$2/-x;
1.46      www      7302:     }
1.462     albertel 7303:     return $file;
1.465     albertel 7304: }
                   7305: 
                   7306: sub current_machine_domains {
                   7307:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7308:     my @domains;
                   7309:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7310: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7311: 	if ($hostname eq $name) {
                   7312: 	    push(@domains,$hostdom{$id});
                   7313: 	}
                   7314:     }
                   7315:     return @domains;
                   7316: }
                   7317: 
                   7318: sub current_machine_ids {
                   7319:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7320:     my @ids;
                   7321:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7322: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7323: 	if ($hostname eq $name) {
                   7324: 	    push(@ids,$id);
                   7325: 	}
                   7326:     }
                   7327:     return @ids;
1.31      www      7328: }
                   7329: 
1.824     raeburn  7330: sub additional_machine_domains {
                   7331:     my @domains;
                   7332:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7333:     while( my $line = <$fh>) {
                   7334:         $line =~ s/\s//g;
                   7335:         push(@domains,$line);
                   7336:     }
                   7337:     return @domains;
                   7338: }
                   7339: 
                   7340: sub default_login_domain {
                   7341:     my $domain = $perlvar{'lonDefDomain'};
                   7342:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7343:     foreach my $posdom (&current_machine_domains(),
                   7344:                         &additional_machine_domains()) {
                   7345:         if (lc($posdom) eq lc($testdomain)) {
                   7346:             $domain=$posdom;
                   7347:             last;
                   7348:         }
                   7349:     }
                   7350:     return $domain;
                   7351: }
                   7352: 
1.31      www      7353: # ------------------------------------------------------------- Declutters URLs
                   7354: 
                   7355: sub declutter {
                   7356:     my $thisfn=shift;
1.569     albertel 7357:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7358:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7359:     $thisfn=~s/^\///;
1.697     albertel 7360:     $thisfn=~s|^adm/wrapper/||;
                   7361:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7362:     $thisfn=~s/^res\///;
1.235     www      7363:     $thisfn=~s/\?.+$//;
1.268     www      7364:     return $thisfn;
                   7365: }
                   7366: 
                   7367: # ------------------------------------------------------------- Clutter up URLs
                   7368: 
                   7369: sub clutter {
                   7370:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7371:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7372:        $thisfn='/res'.$thisfn; 
                   7373:     }
1.694     albertel 7374:     if ($thisfn !~m|/adm|) {
1.695     albertel 7375: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7376: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7377: 	} else {
                   7378: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7379: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7380: 	    if ($embstyle eq 'ssi'
                   7381: 		|| ($embstyle eq 'hdn')
                   7382: 		|| ($embstyle eq 'rat')
                   7383: 		|| ($embstyle eq 'prv')
                   7384: 		|| ($embstyle eq 'ign')) {
                   7385: 		#do nothing with these
                   7386: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7387: 		|| ($embstyle eq 'emb')
                   7388: 		|| ($embstyle eq 'wrp')) {
                   7389: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7390: 	    } elsif ($embstyle eq 'unk'
                   7391: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7392: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7393: 	    } else {
1.718     www      7394: #		&logthis("Got a blank emb style");
1.695     albertel 7395: 	    }
1.694     albertel 7396: 	}
                   7397:     }
1.31      www      7398:     return $thisfn;
1.12      www      7399: }
                   7400: 
1.787     albertel 7401: sub clutter_with_no_wrapper {
                   7402:     my $uri = &clutter(shift);
                   7403:     if ($uri =~ m-^/adm/-) {
                   7404: 	$uri =~ s-^/adm/wrapper/-/-;
                   7405: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7406:     }
                   7407:     return $uri;
                   7408: }
                   7409: 
1.557     albertel 7410: sub freeze_escape {
                   7411:     my ($value)=@_;
                   7412:     if (ref($value)) {
                   7413: 	$value=&nfreeze($value);
                   7414: 	return '__FROZEN__'.&escape($value);
                   7415:     }
                   7416:     return &escape($value);
                   7417: }
                   7418: 
1.11      www      7419: 
1.557     albertel 7420: sub thaw_unescape {
                   7421:     my ($value)=@_;
                   7422:     if ($value =~ /^__FROZEN__/) {
                   7423: 	substr($value,0,10,undef);
                   7424: 	$value=&unescape($value);
                   7425: 	return &thaw($value);
                   7426:     }
                   7427:     return &unescape($value);
                   7428: }
                   7429: 
1.436     albertel 7430: sub correct_line_ends {
                   7431:     my ($result)=@_;
                   7432:     $$result =~s/\r\n/\n/mg;
                   7433:     $$result =~s/\r/\n/mg;
1.415     albertel 7434: }
1.1       albertel 7435: # ================================================================ Main Program
                   7436: 
1.184     www      7437: sub goodbye {
1.204     albertel 7438:    &logthis("Starting Shut down");
1.443     albertel 7439: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7440:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7441: #converted
1.599     albertel 7442: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7443:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7444: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7445: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7446: #1.1 only
1.599     albertel 7447: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7448: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7449: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7450: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7451:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7452:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7453:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7454:    &flushcourselogs();
                   7455:    &logthis("Shutting down");
                   7456: }
                   7457: 
1.179     www      7458: BEGIN {
1.228     harris41 7459: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7460:     unless ($readit) {
1.217     harris41 7461: {
1.781     raeburn  7462:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7463:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7464: }
1.1       albertel 7465: 
1.327     albertel 7466: # ------------------------------------------------------------ Read domain file
                   7467: {
                   7468:     %domaindescription = ();
                   7469:     %domain_auth_def = ();
                   7470:     %domain_auth_arg_def = ();
1.448     albertel 7471:     my $fh;
                   7472:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7473: 	while (my $line = <$fh>) {
                   7474:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7475: #           next if /^\#/;
1.801     foxr     7476:            chomp $line;
1.403     www      7477:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7478: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7479: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7480:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7481: 	   $domaindescription{$domain}=$domain_description;
                   7482: 	   $domain_lang_def{$domain}=$def_lang;
                   7483: 	   $domain_city{$domain}=$city;
                   7484: 	   $domain_longi{$domain}=$longi;
                   7485: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7486:            $domain_primary{$domain}=$primary;
1.403     www      7487: 
1.448     albertel 7488:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7489: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7490: 	}
1.327     albertel 7491:     }
1.448     albertel 7492:     close ($fh);
1.327     albertel 7493: }
                   7494: 
                   7495: 
1.1       albertel 7496: # ------------------------------------------------------------- Read hosts file
                   7497: {
1.448     albertel 7498:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7499: 
                   7500:     while (my $configline=<$config>) {
1.303     matthew  7501:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7502:        chomp($configline);
1.595     albertel 7503:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7504:        $name=~s/\s//g;
1.595     albertel 7505:        if ($id && $domain && $role && $name) {
1.252     albertel 7506: 	 $hostname{$id}=$name;
                   7507: 	 $hostdom{$id}=$domain;
                   7508: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7509:        }
1.1       albertel 7510:     }
1.448     albertel 7511:     close($config);
1.619     albertel 7512:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7513:     #&get_iphost();
1.1       albertel 7514: }
                   7515: 
1.598     albertel 7516: sub get_iphost {
                   7517:     if (%iphost) { return %iphost; }
1.653     albertel 7518:     my %name_to_ip;
1.598     albertel 7519:     foreach my $id (keys(%hostname)) {
                   7520: 	my $name=$hostname{$id};
1.653     albertel 7521: 	my $ip;
                   7522: 	if (!exists($name_to_ip{$name})) {
                   7523: 	    $ip = gethostbyname($name);
                   7524: 	    if (!$ip || length($ip) ne 4) {
                   7525: 		&logthis("Skipping host $id name $name no IP found\n");
                   7526: 		next;
                   7527: 	    }
                   7528: 	    $ip=inet_ntoa($ip);
                   7529: 	    $name_to_ip{$name} = $ip;
                   7530: 	} else {
                   7531: 	    $ip = $name_to_ip{$name};
1.598     albertel 7532: 	}
                   7533: 	push(@{$iphost{$ip}},$id);
                   7534:     }
                   7535:     return %iphost;
                   7536: }
                   7537: 
1.1       albertel 7538: # ------------------------------------------------------ Read spare server file
                   7539: {
1.448     albertel 7540:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7541: 
                   7542:     while (my $configline=<$config>) {
                   7543:        chomp($configline);
1.284     matthew  7544:        if ($configline) {
1.784     albertel 7545: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7546: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7547: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7548:        }
                   7549:     }
1.448     albertel 7550:     close($config);
1.1       albertel 7551: }
1.11      www      7552: # ------------------------------------------------------------ Read permissions
                   7553: {
1.448     albertel 7554:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7555: 
                   7556:     while (my $configline=<$config>) {
1.448     albertel 7557: 	chomp($configline);
                   7558: 	if ($configline) {
                   7559: 	    my ($role,$perm)=split(/ /,$configline);
                   7560: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7561: 	}
1.11      www      7562:     }
1.448     albertel 7563:     close($config);
1.11      www      7564: }
                   7565: 
                   7566: # -------------------------------------------- Read plain texts for permissions
                   7567: {
1.448     albertel 7568:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7569: 
                   7570:     while (my $configline=<$config>) {
1.448     albertel 7571: 	chomp($configline);
                   7572: 	if ($configline) {
1.742     raeburn  7573: 	    my ($short,@plain)=split(/:/,$configline);
                   7574:             %{$prp{$short}} = ();
                   7575: 	    if (@plain > 0) {
                   7576:                 $prp{$short}{'std'} = $plain[0];
                   7577:                 for (my $i=1; $i<@plain; $i++) {
                   7578:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7579:                 }
                   7580:             }
1.448     albertel 7581: 	}
1.135     www      7582:     }
1.448     albertel 7583:     close($config);
1.135     www      7584: }
                   7585: 
                   7586: # ---------------------------------------------------------- Read package table
                   7587: {
1.448     albertel 7588:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7589: 
                   7590:     while (my $configline=<$config>) {
1.483     albertel 7591: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7592: 	chomp($configline);
                   7593: 	my ($short,$plain)=split(/:/,$configline);
                   7594: 	my ($pack,$name)=split(/\&/,$short);
                   7595: 	if ($plain ne '') {
                   7596: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7597: 	    $packagetab{$short}=$plain; 
                   7598: 	}
1.11      www      7599:     }
1.448     albertel 7600:     close($config);
1.329     matthew  7601: }
                   7602: 
                   7603: # ------------- set up temporary directory
                   7604: {
                   7605:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7606: 
1.11      www      7607: }
                   7608: 
1.794     albertel 7609: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7610: 				'compress_threshold'=> 20_000,
                   7611:  			        });
1.185     www      7612: 
1.281     www      7613: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7614: $dumpcount=0;
1.22      www      7615: 
1.163     harris41 7616: &logtouch();
1.672     albertel 7617: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7618: $readit=1;
1.564     albertel 7619:     {
                   7620: 	use integer;
                   7621: 	my $test=(2**32)+1;
1.568     albertel 7622: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7623: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7624:     }
1.195     www      7625: }
1.1       albertel 7626: }
1.179     www      7627: 
1.1       albertel 7628: 1;
1.191     harris41 7629: __END__
                   7630: 
1.243     albertel 7631: =pod
                   7632: 
1.191     harris41 7633: =head1 NAME
                   7634: 
1.243     albertel 7635: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7636: 
                   7637: =head1 SYNOPSIS
                   7638: 
1.243     albertel 7639: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7640: 
                   7641:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7642: 
1.243     albertel 7643: Common parameters:
                   7644: 
                   7645: =over 4
                   7646: 
                   7647: =item *
                   7648: 
                   7649: $uname : an internal username (if $cname expecting a course Id specifically)
                   7650: 
                   7651: =item *
                   7652: 
                   7653: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7654: 
                   7655: =item *
                   7656: 
                   7657: $symb : a resource instance identifier
                   7658: 
                   7659: =item *
                   7660: 
                   7661: $namespace : the name of a .db file that contains the data needed or
                   7662: being set.
                   7663: 
                   7664: =back
                   7665: 
1.394     bowersj2 7666: =head1 OVERVIEW
1.191     harris41 7667: 
1.394     bowersj2 7668: lonnet provides subroutines which interact with the
                   7669: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7670: about classes, users, and resources.
1.243     albertel 7671: 
                   7672: For many of these objects you can also use this to store data about
                   7673: them or modify them in various ways.
1.191     harris41 7674: 
1.394     bowersj2 7675: =head2 Symbs
1.191     harris41 7676: 
1.394     bowersj2 7677: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7678: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7679: map, the resource number of the resource in the map, and the URL of
                   7680: the resource itself. The latter is somewhat redundant, but might help
                   7681: if maps change.
                   7682: 
                   7683: An example is
                   7684: 
                   7685:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7686: 
                   7687: The respective map entry is
                   7688: 
                   7689:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7690:   title="Problem 2">
                   7691:  </resource>
                   7692: 
                   7693: Symbs are used by the random number generator, as well as to store and
                   7694: restore data specific to a certain instance of for example a problem.
                   7695: 
                   7696: =head2 Storing And Retrieving Data
                   7697: 
                   7698: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7699: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7700: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7701: is is the non-critical message twin of cstore. These functions are for
                   7702: handlers to store a perl hash to a user's permanent data space in an
                   7703: easy manner, and to retrieve it again on another call. It is expected
                   7704: that a handler would use this once at the beginning to retrieve data,
                   7705: and then again once at the end to send only the new data back.
                   7706: 
                   7707: The data is stored in the user's data directory on the user's
                   7708: homeserver under the ID of the course.
                   7709: 
                   7710: The hash that is returned by restore will have all of the previous
                   7711: value for all of the elements of the hash.
                   7712: 
                   7713: Example:
                   7714: 
                   7715:  #creating a hash
                   7716:  my %hash;
                   7717:  $hash{'foo'}='bar';
                   7718: 
                   7719:  #storing it
                   7720:  &Apache::lonnet::cstore(\%hash);
                   7721: 
                   7722:  #changing a value
                   7723:  $hash{'foo'}='notbar';
                   7724: 
                   7725:  #adding a new value
                   7726:  $hash{'bar'}='foo';
                   7727:  &Apache::lonnet::cstore(\%hash);
                   7728: 
                   7729:  #retrieving the hash
                   7730:  my %history=&Apache::lonnet::restore();
                   7731: 
                   7732:  #print the hash
                   7733:  foreach my $key (sort(keys(%history))) {
                   7734:    print("\%history{$key} = $history{$key}");
                   7735:  }
                   7736: 
                   7737: Will print out:
1.191     harris41 7738: 
1.394     bowersj2 7739:  %history{1:foo} = bar
                   7740:  %history{1:keys} = foo:timestamp
                   7741:  %history{1:timestamp} = 990455579
                   7742:  %history{2:bar} = foo
                   7743:  %history{2:foo} = notbar
                   7744:  %history{2:keys} = foo:bar:timestamp
                   7745:  %history{2:timestamp} = 990455580
                   7746:  %history{bar} = foo
                   7747:  %history{foo} = notbar
                   7748:  %history{timestamp} = 990455580
                   7749:  %history{version} = 2
                   7750: 
                   7751: Note that the special hash entries C<keys>, C<version> and
                   7752: C<timestamp> were added to the hash. C<version> will be equal to the
                   7753: total number of versions of the data that have been stored. The
                   7754: C<timestamp> attribute will be the UNIX time the hash was
                   7755: stored. C<keys> is available in every historical section to list which
                   7756: keys were added or changed at a specific historical revision of a
                   7757: hash.
                   7758: 
                   7759: B<Warning>: do not store the hash that restore returns directly. This
                   7760: will cause a mess since it will restore the historical keys as if the
                   7761: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7762: 
1.394     bowersj2 7763: Calling convention:
1.191     harris41 7764: 
1.394     bowersj2 7765:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7766:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7767: 
1.394     bowersj2 7768: For more detailed information, see lonnet specific documentation.
1.191     harris41 7769: 
1.394     bowersj2 7770: =head1 RETURN MESSAGES
1.191     harris41 7771: 
1.394     bowersj2 7772: =over 4
1.191     harris41 7773: 
1.394     bowersj2 7774: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7775: 
1.394     bowersj2 7776: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7777: when the connection is brought back up
1.191     harris41 7778: 
1.394     bowersj2 7779: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7780: for later delivery
1.191     harris41 7781: 
1.394     bowersj2 7782: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7783: 
1.394     bowersj2 7784: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7785: that was requested
1.191     harris41 7786: 
1.243     albertel 7787: =back
1.191     harris41 7788: 
1.243     albertel 7789: =head1 PUBLIC SUBROUTINES
1.191     harris41 7790: 
1.243     albertel 7791: =head2 Session Environment Functions
1.191     harris41 7792: 
1.243     albertel 7793: =over 4
1.191     harris41 7794: 
1.394     bowersj2 7795: =item * 
                   7796: X<appenv()>
                   7797: B<appenv(%hash)>: the value of %hash is written to
                   7798: the user envirnoment file, and will be restored for each access this
1.620     albertel 7799: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7800: process
1.191     harris41 7801: 
                   7802: =item *
1.394     bowersj2 7803: X<delenv()>
                   7804: B<delenv($regexp)>: removes all items from the session
                   7805: environment file that matches the regular expression in $regexp. The
1.620     albertel 7806: values are also delted from the current processes %env.
1.191     harris41 7807: 
1.795     albertel 7808: =item * get_env_multiple($name) 
                   7809: 
                   7810: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7811: values may be defined and end up as an array ref.
                   7812: 
                   7813: returns an array of values
                   7814: 
1.243     albertel 7815: =back
                   7816: 
                   7817: =head2 User Information
1.191     harris41 7818: 
1.243     albertel 7819: =over 4
1.191     harris41 7820: 
                   7821: =item *
1.394     bowersj2 7822: X<queryauthenticate()>
                   7823: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7824: authentication scheme
                   7825: 
                   7826: =item *
1.394     bowersj2 7827: X<authenticate()>
                   7828: B<authenticate($uname,$upass,$udom)>: try to
                   7829: authenticate user from domain's lib servers (first use the current
                   7830: one). C<$upass> should be the users password.
1.191     harris41 7831: 
                   7832: =item *
1.394     bowersj2 7833: X<homeserver()>
                   7834: B<homeserver($uname,$udom)>: find the server which has
                   7835: the user's directory and files (there must be only one), this caches
                   7836: the answer, and also caches if there is a borken connection.
1.191     harris41 7837: 
                   7838: =item *
1.394     bowersj2 7839: X<idget()>
                   7840: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7841: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7842: username, and only 1 username per ID in a specific domain) (returns
                   7843: hash: id=>name,id=>name)
1.191     harris41 7844: 
                   7845: =item *
1.394     bowersj2 7846: X<idrget()>
                   7847: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7848: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7849: 
                   7850: =item *
1.394     bowersj2 7851: X<idput()>
                   7852: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7853: 
                   7854: =item *
1.394     bowersj2 7855: X<rolesinit()>
                   7856: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7857: 
                   7858: =item *
1.551     albertel 7859: X<getsection()>
                   7860: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7861: course $cname, return section name/number or '' for "not in course"
                   7862: and '-1' for "no section"
                   7863: 
                   7864: =item *
1.394     bowersj2 7865: X<userenvironment()>
                   7866: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7867: passed in @what from the requested user's environment, returns a hash
                   7868: 
                   7869: =back
                   7870: 
                   7871: =head2 User Roles
                   7872: 
                   7873: =over 4
                   7874: 
                   7875: =item *
                   7876: 
1.810     raeburn  7877: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7878:  F: full access
                   7879:  U,I,K: authentication modes (cxx only)
                   7880:  '': forbidden
                   7881:  1: user needs to choose course
                   7882:  2: browse allowed
1.766     albertel 7883:  A: passphrase authentication needed
1.243     albertel 7884: 
                   7885: =item *
                   7886: 
                   7887: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7888: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7889: and course level
                   7890: 
                   7891: =item *
                   7892: 
                   7893: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7894: explanation of a user role term
                   7895: 
                   7896: =back
                   7897: 
                   7898: =head2 User Modification
                   7899: 
                   7900: =over 4
                   7901: 
                   7902: =item *
                   7903: 
                   7904: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7905: user for the level given by URL.  Optional start and end dates (leave empty
                   7906: string or zero for "no date")
1.191     harris41 7907: 
                   7908: =item *
                   7909: 
1.243     albertel 7910: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7911: change a users, password, possible return values are: ok,
                   7912: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7913: refused
1.191     harris41 7914: 
                   7915: =item *
                   7916: 
1.243     albertel 7917: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7918: 
                   7919: =item *
                   7920: 
1.243     albertel 7921: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7922: modify user
1.191     harris41 7923: 
                   7924: =item *
                   7925: 
1.286     matthew  7926: modifystudent
                   7927: 
                   7928: modify a students enrollment and identification information.
                   7929: The course id is resolved based on the current users environment.  
                   7930: This means the envoking user must be a course coordinator or otherwise
                   7931: associated with a course.
                   7932: 
1.297     matthew  7933: This call is essentially a wrapper for lonnet::modifyuser and
                   7934: lonnet::modify_student_enrollment
1.286     matthew  7935: 
                   7936: Inputs: 
                   7937: 
                   7938: =over 4
                   7939: 
                   7940: =item B<$udom> Students loncapa domain
                   7941: 
                   7942: =item B<$uname> Students loncapa login name
                   7943: 
                   7944: =item B<$uid> Students id/student number
                   7945: 
                   7946: =item B<$umode> Students authentication mode
                   7947: 
                   7948: =item B<$upass> Students password
                   7949: 
                   7950: =item B<$first> Students first name
                   7951: 
                   7952: =item B<$middle> Students middle name
                   7953: 
                   7954: =item B<$last> Students last name
                   7955: 
                   7956: =item B<$gene> Students generation
                   7957: 
                   7958: =item B<$usec> Students section in course
                   7959: 
                   7960: =item B<$end> Unix time of the roles expiration
                   7961: 
                   7962: =item B<$start> Unix time of the roles start date
                   7963: 
                   7964: =item B<$forceid> If defined, allow $uid to be changed
                   7965: 
                   7966: =item B<$desiredhome> server to use as home server for student
                   7967: 
                   7968: =back
1.297     matthew  7969: 
                   7970: =item *
                   7971: 
                   7972: modify_student_enrollment
                   7973: 
                   7974: Change a students enrollment status in a class.  The environment variable
                   7975: 'role.request.course' must be defined for this function to proceed.
                   7976: 
                   7977: Inputs:
                   7978: 
                   7979: =over 4
                   7980: 
                   7981: =item $udom, students domain
                   7982: 
                   7983: =item $uname, students name
                   7984: 
                   7985: =item $uid, students user id
                   7986: 
                   7987: =item $first, students first name
                   7988: 
                   7989: =item $middle
                   7990: 
                   7991: =item $last
                   7992: 
                   7993: =item $gene
                   7994: 
                   7995: =item $usec
                   7996: 
                   7997: =item $end
                   7998: 
                   7999: =item $start
                   8000: 
                   8001: =back
                   8002: 
1.191     harris41 8003: 
                   8004: =item *
                   8005: 
1.243     albertel 8006: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8007: custom role; give a custom role to a user for the level given by URL.  Specify
                   8008: name and domain of role author, and role name
1.191     harris41 8009: 
                   8010: =item *
                   8011: 
1.243     albertel 8012: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8013: 
                   8014: =item *
                   8015: 
1.243     albertel 8016: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8017: 
                   8018: =back
                   8019: 
                   8020: =head2 Course Infomation
                   8021: 
                   8022: =over 4
1.191     harris41 8023: 
                   8024: =item *
                   8025: 
1.631     albertel 8026: coursedescription($courseid) : returns a hash of information about the
                   8027: specified course id, including all environment settings for the
                   8028: course, the description of the course will be in the hash under the
                   8029: key 'description'
1.191     harris41 8030: 
                   8031: =item *
                   8032: 
1.624     albertel 8033: resdata($name,$domain,$type,@which) : request for current parameter
                   8034: setting for a specific $type, where $type is either 'course' or 'user',
                   8035: @what should be a list of parameters to ask about. This routine caches
                   8036: answers for 5 minutes.
1.243     albertel 8037: 
                   8038: =back
                   8039: 
                   8040: =head2 Course Modification
                   8041: 
                   8042: =over 4
1.191     harris41 8043: 
                   8044: =item *
                   8045: 
1.243     albertel 8046: writecoursepref($courseid,%prefs) : write preferences (environment
                   8047: database) for a course
1.191     harris41 8048: 
                   8049: =item *
                   8050: 
1.243     albertel 8051: createcourse($udom,$description,$url) : make/modify course
                   8052: 
                   8053: =back
                   8054: 
                   8055: =head2 Resource Subroutines
                   8056: 
                   8057: =over 4
1.191     harris41 8058: 
                   8059: =item *
                   8060: 
1.243     albertel 8061: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8062: 
                   8063: =item *
                   8064: 
1.243     albertel 8065: repcopy($filename) : subscribes to the requested file, and attempts to
                   8066: replicate from the owning library server, Might return
1.607     raeburn  8067: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8068: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8069: resource. Expects the local filesystem pathname
                   8070: (/home/httpd/html/res/....)
                   8071: 
                   8072: =back
                   8073: 
                   8074: =head2 Resource Information
                   8075: 
                   8076: =over 4
1.191     harris41 8077: 
                   8078: =item *
                   8079: 
1.243     albertel 8080: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8081: a vairety of different possible values, $varname should be a request
                   8082: string, and the other parameters can be used to specify who and what
                   8083: one is asking about.
                   8084: 
                   8085: Possible values for $varname are environment.lastname (or other item
                   8086: from the envirnment hash), user.name (or someother aspect about the
                   8087: user), resource.0.maxtries (or some other part and parameter of a
                   8088: resource)
1.204     albertel 8089: 
                   8090: =item *
                   8091: 
1.243     albertel 8092: directcondval($number) : get current value of a condition; reads from a state
                   8093: string
1.204     albertel 8094: 
                   8095: =item *
                   8096: 
1.243     albertel 8097: condval($condidx) : value of condition index based on state
1.204     albertel 8098: 
                   8099: =item *
                   8100: 
1.243     albertel 8101: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8102: resource's metadata, $what should be either a specific key, or either
                   8103: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8104: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8105: 
                   8106: this function automatically caches all requests
1.191     harris41 8107: 
                   8108: =item *
                   8109: 
1.243     albertel 8110: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8111: network of library servers; returns file handle of where SQL and regex results
                   8112: will be stored for query
1.191     harris41 8113: 
                   8114: =item *
                   8115: 
1.243     albertel 8116: symbread($filename) : return symbolic list entry (filename argument optional);
                   8117: returns the data handle
1.191     harris41 8118: 
                   8119: =item *
                   8120: 
1.243     albertel 8121: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8122: a possible symb for the URL in $thisfn, and if is an encryypted
                   8123: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8124: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8125: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8126: 
1.191     harris41 8127: 
                   8128: =item *
                   8129: 
1.243     albertel 8130: symbclean($symb) : removes versions numbers from a symb, returns the
                   8131: cleaned symb
1.191     harris41 8132: 
                   8133: =item *
                   8134: 
1.243     albertel 8135: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8136: course map, user must be in a course for it to work.
1.191     harris41 8137: 
                   8138: =item *
                   8139: 
1.243     albertel 8140: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8141: 
                   8142: =item *
                   8143: 
1.243     albertel 8144: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8145: a random seed, all arguments are optional, if they aren't sent it uses the
                   8146: environment to derive them. Note: if symb isn't sent and it can't get one
                   8147: from &symbread it will use the current time as its return value
1.191     harris41 8148: 
                   8149: =item *
                   8150: 
1.243     albertel 8151: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8152: unfakeable, receipt
1.191     harris41 8153: 
                   8154: =item *
                   8155: 
1.620     albertel 8156: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8157: 
                   8158: =item *
                   8159: 
1.243     albertel 8160: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8161: 
                   8162: =item *
                   8163: 
1.243     albertel 8164: 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 8165: 
                   8166: =item *
                   8167: 
1.243     albertel 8168: 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 8169: 
                   8170: =item *
                   8171: 
1.243     albertel 8172: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8173: 
                   8174: =item *
                   8175: 
1.243     albertel 8176: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8177: forcing spreadsheet to reevaluate the resource scores next time.
                   8178: 
                   8179: =back
                   8180: 
                   8181: =head2 Storing/Retreiving Data
                   8182: 
                   8183: =over 4
1.191     harris41 8184: 
                   8185: =item *
                   8186: 
1.243     albertel 8187: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8188: for this url; hashref needs to be given and should be a \%hashname; the
                   8189: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8190: be derived from the env
1.191     harris41 8191: 
                   8192: =item *
                   8193: 
1.243     albertel 8194: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8195: uses critical subroutine
1.191     harris41 8196: 
                   8197: =item *
                   8198: 
1.243     albertel 8199: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8200: all args are optional
1.191     harris41 8201: 
                   8202: =item *
                   8203: 
1.717     albertel 8204: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8205: dumps the complete (or key matching regexp) namespace into a hash
                   8206: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8207: normally &store()ed into
                   8208: 
                   8209: $range should be either an integer '100' (give me the first 100
                   8210:                                            matching records)
                   8211:               or be  two integers sperated by a - with no spaces
                   8212:                  '30-50' (give me the 30th through the 50th matching
                   8213:                           records)
                   8214: 
                   8215: 
                   8216: =item *
                   8217: 
                   8218: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8219: replaces a &store() version of data with a replacement set of data
                   8220: for a particular resource in a namespace passed in the $storehash hash 
                   8221: reference
                   8222: 
                   8223: =item *
                   8224: 
1.243     albertel 8225: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8226: works very similar to store/cstore, but all data is stored in a
                   8227: temporary location and can be reset using tmpreset, $storehash should
                   8228: be a hash reference, returns nothing on success
1.191     harris41 8229: 
                   8230: =item *
                   8231: 
1.243     albertel 8232: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8233: similar to restore, but all data is stored in a temporary location and
                   8234: can be reset using tmpreset. Returns a hash of values on success,
                   8235: error string otherwise.
1.191     harris41 8236: 
                   8237: =item *
                   8238: 
1.243     albertel 8239: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8240: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8241: 
                   8242: =item *
                   8243: 
1.243     albertel 8244: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8245: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8246: 
                   8247: =item *
                   8248: 
1.243     albertel 8249: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8250: namesp ($udom and $uname are optional)
1.191     harris41 8251: 
                   8252: =item *
                   8253: 
1.702     albertel 8254: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8255: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8256: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8257: 
1.702     albertel 8258: $range should be either an integer '100' (give me the first 100
                   8259:                                            matching records)
                   8260:               or be  two integers sperated by a - with no spaces
                   8261:                  '30-50' (give me the 30th through the 50th matching
                   8262:                           records)
1.449     matthew  8263: =item *
                   8264: 
                   8265: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8266: $store can be a scalar, an array reference, or if the amount to be 
                   8267: incremented is > 1, a hash reference.
                   8268: 
                   8269: ($udom and $uname are optional)
1.191     harris41 8270: 
                   8271: =item *
                   8272: 
1.243     albertel 8273: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8274: ($udom and $uname are optional)
1.191     harris41 8275: 
                   8276: =item *
                   8277: 
1.243     albertel 8278: cput($namespace,$storehash,$udom,$uname) : critical put
                   8279: ($udom and $uname are optional)
1.191     harris41 8280: 
                   8281: =item *
                   8282: 
1.748     albertel 8283: newput($namespace,$storehash,$udom,$uname) :
                   8284: 
                   8285: Attempts to store the items in the $storehash, but only if they don't
                   8286: currently exist, if this succeeds you can be certain that you have 
                   8287: successfully created a new key value pair in the $namespace db.
                   8288: 
                   8289: 
                   8290: Args:
                   8291:  $namespace: name of database to store values to
                   8292:  $storehash: hashref to store to the db
                   8293:  $udom: (optional) domain of user containing the db
                   8294:  $uname: (optional) name of user caontaining the db
                   8295: 
                   8296: Returns:
                   8297:  'ok' -> succeeded in storing all keys of $storehash
                   8298:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8299:                         least <key> already existed in the db (other
                   8300:                         requested keys may also already exist)
                   8301:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8302:  'con_lost' -> unable to contact request server
                   8303:  'refused' -> action was not allowed by remote machine
                   8304: 
                   8305: 
                   8306: =item *
                   8307: 
1.243     albertel 8308: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8309: reference filled in from namesp (encrypts the return communication)
                   8310: ($udom and $uname are optional)
1.191     harris41 8311: 
                   8312: =item *
                   8313: 
1.243     albertel 8314: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8315: critical subroutine
                   8316: 
1.806     raeburn  8317: =item *
                   8318: 
                   8319: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8320: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8321: 
                   8322: =item *
                   8323: 
                   8324: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8325: 
1.243     albertel 8326: =back
                   8327: 
                   8328: =head2 Network Status Functions
                   8329: 
                   8330: =over 4
1.191     harris41 8331: 
                   8332: =item *
                   8333: 
                   8334: dirlist($uri) : return directory list based on URI
                   8335: 
                   8336: =item *
                   8337: 
1.243     albertel 8338: spareserver() : find server with least workload from spare.tab
                   8339: 
                   8340: =back
                   8341: 
                   8342: =head2 Apache Request
                   8343: 
                   8344: =over 4
1.191     harris41 8345: 
                   8346: =item *
                   8347: 
1.243     albertel 8348: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8349: localhost, posts hash
                   8350: 
                   8351: =back
                   8352: 
                   8353: =head2 Data to String to Data
                   8354: 
                   8355: =over 4
1.191     harris41 8356: 
                   8357: =item *
                   8358: 
1.243     albertel 8359: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8360: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8361: 
                   8362: =item *
                   8363: 
1.243     albertel 8364: hashref2str($hashref) : convert a hashref into a string complete with
                   8365: escaping and '=' and '&' separators, supports elements that are
                   8366: arrayrefs and hashrefs
1.191     harris41 8367: 
                   8368: =item *
                   8369: 
1.243     albertel 8370: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8371: with escaping and '&' separators, supports elements that are arrayrefs
                   8372: and hashrefs
1.191     harris41 8373: 
                   8374: =item *
                   8375: 
1.243     albertel 8376: str2hash($string) : convert string to hash using unescaping and
                   8377: splitting on '=' and '&', supports elements that are arrayrefs and
                   8378: hashrefs
1.191     harris41 8379: 
                   8380: =item *
                   8381: 
1.243     albertel 8382: str2array($string) : convert string to hash using unescaping and
                   8383: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8384: 
                   8385: =back
                   8386: 
                   8387: =head2 Logging Routines
                   8388: 
                   8389: =over 4
                   8390: 
                   8391: These routines allow one to make log messages in the lonnet.log and
                   8392: lonnet.perm logfiles.
1.191     harris41 8393: 
                   8394: =item *
                   8395: 
1.243     albertel 8396: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8397: 
                   8398: =item *
                   8399: 
1.243     albertel 8400: logthis() : append message to the normal lonnet.log file, it gets
                   8401: preiodically rolled over and deleted.
1.191     harris41 8402: 
                   8403: =item *
                   8404: 
1.243     albertel 8405: logperm() : append a permanent message to lonnet.perm.log, this log
                   8406: file never gets deleted by any automated portion of the system, only
                   8407: messages of critical importance should go in here.
                   8408: 
                   8409: =back
                   8410: 
                   8411: =head2 General File Helper Routines
                   8412: 
                   8413: =over 4
1.191     harris41 8414: 
                   8415: =item *
                   8416: 
1.481     raeburn  8417: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8418: (a) files in /uploaded
                   8419:   (i) If a local copy of the file exists - 
                   8420:       compares modification date of local copy with last-modified date for 
                   8421:       definitive version stored on home server for course. If local copy is 
                   8422:       stale, requests a new version from the home server and stores it. 
                   8423:       If the original has been removed from the home server, then local copy 
                   8424:       is unlinked.
                   8425:   (ii) If local copy does not exist -
                   8426:       requests the file from the home server and stores it. 
                   8427:   
                   8428:   If $caller is 'uploadrep':  
                   8429:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8430:     for request for files originally uploaded via DOCS. 
                   8431:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8432:   
                   8433:   Otherwise:
                   8434:      This indicates a call from the content generation phase of the request.
                   8435:      -  returns the entire contents of the file or -1.
                   8436:      
                   8437: (b) files in /res
                   8438:    - returns the entire contents of a file or -1; 
                   8439:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8440: 
1.712     albertel 8441: 
                   8442: =item *
                   8443: 
                   8444: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8445:                   reference
                   8446: 
                   8447: returns either a stat() list of data about the file or an empty list
                   8448: if the file doesn't exist or couldn't find out about it (connection
                   8449: problems or user unknown)
                   8450: 
1.191     harris41 8451: =item *
                   8452: 
1.243     albertel 8453: filelocation($dir,$file) : returns file system location of a file
                   8454: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8455: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8456: and a file of ../bob will become /a/bob)
1.191     harris41 8457: 
                   8458: =item *
                   8459: 
                   8460: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8461: filelocation except for hrefs
                   8462: 
                   8463: =item *
                   8464: 
                   8465: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8466: 
1.243     albertel 8467: =back
                   8468: 
1.608     albertel 8469: =head2 Usererfile file routines (/uploaded*)
                   8470: 
                   8471: =over 4
                   8472: 
                   8473: =item *
                   8474: 
                   8475: userfileupload(): main rotine for putting a file in a user or course's
                   8476:                   filespace, arguments are,
                   8477: 
1.620     albertel 8478:  formname - required - this is the name of the element in $env where the
1.608     albertel 8479:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8480:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8481:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8482:  coursedoc - if true, store the file in the course of the active role
                   8483:              of the current user
                   8484:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8485:          if undefined, it will be placed in "unknown"
                   8486: 
                   8487:  (This routine calls clean_filename() to remove any dangerous
                   8488:  characters from the filename, and then calls finuserfileupload() to
                   8489:  complete the transaction)
                   8490: 
                   8491:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8492:  and /adm/notfound.html if unsuccessful
                   8493: 
                   8494: =item *
                   8495: 
                   8496: clean_filename(): routine for cleaing a filename up for storage in
                   8497:                  userfile space, argument is:
                   8498: 
                   8499:  filename - proposed filename
                   8500: 
                   8501: returns: the new clean filename
                   8502: 
                   8503: =item *
                   8504: 
                   8505: finishuserfileupload(): routine that creaes and sends the file to
                   8506: userspace, probably shouldn't be called directly
                   8507: 
                   8508:   docuname: username or courseid of destination for the file
                   8509:   docudom: domain of user/course of destination for the file
                   8510:   formname: same as for userfileupload()
                   8511:   fname: filename (inculding subdirectories) for the file
                   8512: 
                   8513:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8514:  and /adm/notfound.html if unsuccessful
                   8515: 
                   8516: =item *
                   8517: 
                   8518: renameuserfile(): renames an existing userfile to a new name
                   8519: 
                   8520:   Args:
                   8521:    docuname: username or courseid of destination for the file
                   8522:    docudom: domain of user/course of destination for the file
                   8523:    old: current file name (including any subdirs under userfiles)
                   8524:    new: desired file name (including any subdirs under userfiles)
                   8525: 
                   8526: =item *
                   8527: 
                   8528: mkdiruserfile(): creates a directory is a userfiles dir
                   8529: 
                   8530:   Args:
                   8531:    docuname: username or courseid of destination for the file
                   8532:    docudom: domain of user/course of destination for the file
                   8533:    dir: dir to create (including any subdirs under userfiles)
                   8534: 
                   8535: =item *
                   8536: 
                   8537: removeuserfile(): removes a file that exists in userfiles
                   8538: 
                   8539:   Args:
                   8540:    docuname: username or courseid of destination for the file
                   8541:    docudom: domain of user/course of destination for the file
                   8542:    fname: filname to delete (including any subdirs under userfiles)
                   8543: 
                   8544: =item *
                   8545: 
                   8546: removeuploadedurl(): convience function for removeuserfile()
                   8547: 
                   8548:   Args:
                   8549:    url:  a full /uploaded/... url to delete
                   8550: 
1.747     albertel 8551: =item * 
                   8552: 
                   8553: get_portfile_permissions():
                   8554:   Args:
                   8555:     domain: domain of user or course contain the portfolio files
                   8556:     user: name of user or num of course contain the portfolio files
                   8557:   Returns:
                   8558:     hashref of a dump of the proper file_permissions.db
                   8559:    
                   8560: 
                   8561: =item * 
                   8562: 
                   8563: get_access_controls():
                   8564: 
                   8565: Args:
                   8566:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8567:   group: (optional) the group you want the files associated with
                   8568:   file: (optional) the file you want access info on
                   8569: 
                   8570: Returns:
1.749     raeburn  8571:     a hash (keys are file names) of hashes containing
                   8572:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8573:         values are XML containing access control settings (see below) 
1.747     albertel 8574: 
                   8575: Internal notes:
                   8576: 
1.749     raeburn  8577:  access controls are stored in file_permissions.db as key=value pairs.
                   8578:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8579:         where scope -> public,guest,course,group,domains or users.
                   8580:               end -> UNIX time for end of access (0 -> no end date)
                   8581:               start -> UNIX time for start of access
                   8582: 
                   8583:     value -> XML description of access control
                   8584:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8585:             <start></start>
                   8586:             <end></end>
                   8587: 
                   8588:             <password></password>  for scope type = guest
                   8589: 
                   8590:             <domain></domain>     for scope type = course or group
                   8591:             <number></number>
                   8592:             <roles id="">
                   8593:              <role></role>
                   8594:              <access></access>
                   8595:              <section></section>
                   8596:              <group></group>
                   8597:             </roles>
                   8598: 
                   8599:             <dom></dom>         for scope type = domains
                   8600: 
                   8601:             <users>             for scope type = users
                   8602:              <user>
                   8603:               <uname></uname>
                   8604:               <udom></udom>
                   8605:              </user>
                   8606:             </users>
                   8607:            </scope> 
                   8608:               
                   8609:  Access data is also aggregated for each file in an additional key=value pair:
                   8610:  key -> path to file/file_name\0accesscontrol 
                   8611:  value -> reference to hash
                   8612:           hash contains key = value pairs
                   8613:           where key = uniqueID:scope_end_start
                   8614:                 value = UNIX time record was last updated
                   8615: 
                   8616:           Used to improve speed of look-ups of access controls for each file.  
                   8617:  
                   8618:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8619: 
                   8620: modify_access_controls():
                   8621: 
                   8622: Modifies access controls for a portfolio file
                   8623: Args
                   8624: 1. file name
                   8625: 2. reference to hash of required changes,
                   8626: 3. domain
                   8627: 4. username
                   8628:   where domain,username are the domain of the portfolio owner 
                   8629:   (either a user or a course) 
                   8630: 
                   8631: Returns:
                   8632: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8633: 2. result of deletions ('ok' or 'error', with error message).
                   8634: 3. reference to hash of any new or updated access controls.
                   8635: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8636:    key = integer (inbound ID)
                   8637:    value = uniqueID  
1.747     albertel 8638: 
1.608     albertel 8639: =back
                   8640: 
1.243     albertel 8641: =head2 HTTP Helper Routines
                   8642: 
                   8643: =over 4
                   8644: 
1.191     harris41 8645: =item *
                   8646: 
                   8647: escape() : unpack non-word characters into CGI-compatible hex codes
                   8648: 
                   8649: =item *
                   8650: 
                   8651: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8652: 
1.243     albertel 8653: =back
                   8654: 
                   8655: =head1 PRIVATE SUBROUTINES
                   8656: 
                   8657: =head2 Underlying communication routines (Shouldn't call)
                   8658: 
                   8659: =over 4
                   8660: 
                   8661: =item *
                   8662: 
                   8663: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8664: 
                   8665: =item *
                   8666: 
                   8667: reply() : uses subreply to send a message to remote machine, logs all failures
                   8668: 
                   8669: =item *
                   8670: 
                   8671: critical() : passes a critical message to another server; if cannot
                   8672: get through then place message in connection buffer directory and
                   8673: returns con_delayed, if incapable of saving message, returns
                   8674: con_failed
                   8675: 
                   8676: =item *
                   8677: 
                   8678: reconlonc() : tries to reconnect lonc client processes.
                   8679: 
                   8680: =back
                   8681: 
                   8682: =head2 Resource Access Logging
                   8683: 
                   8684: =over 4
                   8685: 
                   8686: =item *
                   8687: 
                   8688: flushcourselogs() : flush (save) buffer logs and access logs
                   8689: 
                   8690: =item *
                   8691: 
                   8692: courselog($what) : save message for course in hash
                   8693: 
                   8694: =item *
                   8695: 
                   8696: courseacclog($what) : save message for course using &courselog().  Perform
                   8697: special processing for specific resource types (problems, exams, quizzes, etc).
                   8698: 
1.191     harris41 8699: =item *
                   8700: 
                   8701: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8702: as a PerlChildExitHandler
1.243     albertel 8703: 
                   8704: =back
                   8705: 
                   8706: =head2 Other
                   8707: 
                   8708: =over 4
                   8709: 
                   8710: =item *
                   8711: 
                   8712: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8713: 
                   8714: =back
                   8715: 
                   8716: =cut

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