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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.788   ! albertel    4: # $Id: lonnet.pm,v 1.787 2006/09/29 18:23:25 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.740     www        55: use lib '/home/httpd/lib/perl';
                     56: use LONCAPA;
                     57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.783     albertel  295: sub convert_and_load_session_env {
                    296:     my ($lonidsdir,$handle)=@_;
                    297:     my @profile;
                    298:     {
                    299: 	open(my $idf,"$lonidsdir/$handle.id");
                    300: 	flock($idf,LOCK_SH);
                    301: 	@profile=<$idf>;
                    302: 	close($idf);
                    303:     }
                    304:     my %temp_env;
                    305:     foreach my $line (@profile) {
1.786     albertel  306: 	if ($line !~ m/=/) {
                    307: 	    return 0;
                    308: 	}
1.783     albertel  309: 	chomp($line);
                    310: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    311: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    312:     }
                    313:     unlink("$lonidsdir/$handle.id");
                    314:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    315: 	    0640)) {
                    316: 	%disk_env = %temp_env;
                    317: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    318: 	untie(%disk_env);
                    319:     }
1.786     albertel  320:     return 1;
1.783     albertel  321: }
                    322: 
1.374     www       323: # ------------------------------------------- Transfer profile into environment
1.780     albertel  324: my $env_loaded;
                    325: sub transfer_profile_to_env {
1.788   ! albertel  326:     my ($lonidsdir,$handle,$force_transfer) = @_;
        !           327:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       328: 
1.720     albertel  329:     if (!defined($lonidsdir)) {
                    330: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    331:     }
                    332:     if (!defined($handle)) {
                    333:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    334:     }
                    335: 
1.786     albertel  336:     my $convert;
                    337:     {
                    338:     	open(my $idf,"$lonidsdir/$handle.id");
                    339: 	flock($idf,LOCK_SH);
                    340: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    341: 		&GDBM_READER(),0640)) {
                    342: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    343: 	    untie(%disk_env);
                    344: 	} else {
                    345: 	    $convert = 1;
                    346: 	}
                    347:     }
                    348:     if ($convert) {
                    349: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    350: 	    &logthis("Failed to load session, or convert session.");
                    351: 	}
1.374     www       352:     }
1.783     albertel  353: 
1.786     albertel  354:     my %remove;
1.783     albertel  355:     while ( my $envname = each(%env) ) {
1.433     matthew   356:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    357:             if ($time < time-300) {
1.783     albertel  358:                 $remove{$key}++;
1.433     matthew   359:             }
                    360:         }
                    361:     }
1.783     albertel  362: 
1.619     albertel  363:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  364:     $env_loaded=1;
1.783     albertel  365:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   366:         &delenv($expired_key);
1.374     www       367:     }
1.1       albertel  368: }
                    369: 
1.5       www       370: # ---------------------------------------------------------- Append Environment
                    371: 
                    372: sub appenv {
1.6       www       373:     my %newenv=@_;
1.692     albertel  374:     foreach my $key (keys(%newenv)) {
                    375: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  376:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  377:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       378:                 .'</font>');
1.692     albertel  379: 	    delete($newenv{$key});
1.35      www       380:         } else {
1.692     albertel  381:             $env{$key}=$newenv{$key};
1.35      www       382:         }
1.191     harris41  383:     }
1.783     albertel  384:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    385: 	    0640)) {
                    386: 	while (my ($key,$value) = each(%newenv)) {
                    387: 	    $disk_env{$key} = $value;
1.448     albertel  388: 	}
1.783     albertel  389: 	untie(%disk_env);
1.56      www       390:     }
                    391:     return 'ok';
                    392: }
                    393: # ----------------------------------------------------- Delete from Environment
                    394: 
                    395: sub delenv {
                    396:     my $delthis=shift;
                    397:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  398:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       399:                 "Attempt to delete from environment ".$delthis);
                    400:         return 'error';
                    401:     }
1.783     albertel  402:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    403: 	    0640)) {
                    404: 	foreach my $key (keys(%disk_env)) {
                    405: 	    if ($key=~/^$delthis/) { 
1.619     albertel  406:                 delete($env{$key});
1.783     albertel  407:                 delete($disk_env{$key});
1.473     matthew   408:             }
1.448     albertel  409: 	}
1.783     albertel  410: 	untie(%disk_env);
1.5       www       411:     }
                    412:     return 'ok';
1.369     albertel  413: }
                    414: 
                    415: # ------------------------------------------ Find out current server userload
                    416: # there is a copy in lond
                    417: sub userload {
                    418:     my $numusers=0;
                    419:     {
                    420: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    421: 	my $filename;
                    422: 	my $curtime=time;
                    423: 	while ($filename=readdir(LONIDS)) {
                    424: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  425: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  426: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  427: 	}
                    428: 	closedir(LONIDS);
                    429:     }
                    430:     my $userloadpercent=0;
                    431:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    432:     if ($maxuserload) {
1.371     albertel  433: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  434:     }
1.372     albertel  435:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  436:     return $userloadpercent;
1.283     www       437: }
                    438: 
                    439: # ------------------------------------------ Fight off request when overloaded
                    440: 
                    441: sub overloaderror {
                    442:     my ($r,$checkserver)=@_;
                    443:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    444:     my $loadavg;
                    445:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  446:        open(my $loadfile,'/proc/loadavg');
1.283     www       447:        $loadavg=<$loadfile>;
                    448:        $loadavg =~ s/\s.*//g;
1.285     matthew   449:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  450:        close($loadfile);
1.283     www       451:     } else {
                    452:        $loadavg=&reply('load',$checkserver);
                    453:     }
1.285     matthew   454:     my $overload=$loadavg-100;
1.283     www       455:     if ($overload>0) {
1.285     matthew   456: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       457:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       458:         return 413;
1.283     www       459:     }    
                    460:     return '';
1.5       www       461: }
1.1       albertel  462: 
                    463: # ------------------------------ Find server with least workload from spare.tab
1.11      www       464: 
1.1       albertel  465: sub spareserver {
1.670     albertel  466:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  467:     my $spare_server;
1.370     albertel  468:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  469:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    470:                                                      :  $userloadpercent;
                    471:     
                    472:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    473: 	($spare_server, $lowest_load) =
                    474: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    475:     }
                    476: 
                    477:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    478: 
                    479:     if (!$found_server) {
                    480: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    481: 	    ($spare_server, $lowest_load) =
                    482: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    483: 	}
                    484:     }
                    485: 
                    486:     if (!$want_server_name) {
                    487: 	$spare_server="http://$hostname{$spare_server}";
                    488:     }
                    489:     return $spare_server;
                    490: }
                    491: 
                    492: sub compare_server_load {
                    493:     my ($try_server, $spare_server, $lowest_load) = @_;
                    494: 
                    495:     my $loadans     = &reply('load',    $try_server);
                    496:     my $userloadans = &reply('userload',$try_server);
                    497: 
                    498:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    499: 	next; #didn't get a number from the server
                    500:     }
                    501: 
                    502:     my $load;
                    503:     if ($loadans =~ /\d/) {
                    504: 	if ($userloadans =~ /\d/) {
                    505: 	    #both are numbers, pick the bigger one
                    506: 	    $load = ($loadans > $userloadans) ? $loadans 
                    507: 		                              : $userloadans;
1.411     albertel  508: 	} else {
1.784     albertel  509: 	    $load = $loadans;
1.411     albertel  510: 	}
1.784     albertel  511:     } else {
                    512: 	$load = $userloadans;
                    513:     }
                    514: 
                    515:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    516: 	$spare_server = $try_server;
                    517: 	$lowest_load  = $load;
1.370     albertel  518:     }
1.784     albertel  519:     return ($spare_server,$lowest_load);
1.202     matthew   520: }
                    521: # --------------------------------------------- Try to change a user's password
                    522: 
                    523: sub changepass {
                    524:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    525:     $currentpass = &escape($currentpass);
                    526:     $newpass     = &escape($newpass);
                    527:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    528: 		       $server);
                    529:     if (! $answer) {
                    530: 	&logthis("No reply on password change request to $server ".
                    531: 		 "by $uname in domain $udom.");
                    532:     } elsif ($answer =~ "^ok") {
                    533:         &logthis("$uname in $udom successfully changed their password ".
                    534: 		 "on $server.");
                    535:     } elsif ($answer =~ "^pwchange_failure") {
                    536: 	&logthis("$uname in $udom was unable to change their password ".
                    537: 		 "on $server.  The action was blocked by either lcpasswd ".
                    538: 		 "or pwchange");
                    539:     } elsif ($answer =~ "^non_authorized") {
                    540:         &logthis("$uname in $udom did not get their password correct when ".
                    541: 		 "attempting to change it on $server.");
                    542:     } elsif ($answer =~ "^auth_mode_error") {
                    543:         &logthis("$uname in $udom attempted to change their password despite ".
                    544: 		 "not being locally or internally authenticated on $server.");
                    545:     } elsif ($answer =~ "^unknown_user") {
                    546:         &logthis("$uname in $udom attempted to change their password ".
                    547: 		 "on $server but were unable to because $server is not ".
                    548: 		 "their home server.");
                    549:     } elsif ($answer =~ "^refused") {
                    550: 	&logthis("$server refused to change $uname in $udom password because ".
                    551: 		 "it was sent an unencrypted request to change the password.");
                    552:     }
                    553:     return $answer;
1.1       albertel  554: }
                    555: 
1.169     harris41  556: # ----------------------- Try to determine user's current authentication scheme
                    557: 
                    558: sub queryauthenticate {
                    559:     my ($uname,$udom)=@_;
1.456     albertel  560:     my $uhome=&homeserver($uname,$udom);
                    561:     if (!$uhome) {
                    562: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    563: 	return 'no_host';
                    564:     }
                    565:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    566:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    567: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  568:     }
1.456     albertel  569:     return $answer;
1.169     harris41  570: }
                    571: 
1.1       albertel  572: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       573: 
1.1       albertel  574: sub authenticate {
                    575:     my ($uname,$upass,$udom)=@_;
1.12      www       576:     $upass=escape($upass);
1.199     www       577:     $uname=~s/\W//g;
1.471     albertel  578:     my $uhome=&homeserver($uname,$udom);
                    579:     if (!$uhome) {
                    580: 	&logthis("User $uname at $udom is unknown in authenticate");
                    581: 	return 'no_host';
1.1       albertel  582:     }
1.471     albertel  583:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    584:     if ($answer eq 'authorized') {
                    585: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    586: 	return $uhome; 
                    587:     }
                    588:     if ($answer eq 'non_authorized') {
                    589: 	&logthis("User $uname at $udom rejected by $uhome");
                    590: 	return 'no_host'; 
1.9       www       591:     }
1.471     albertel  592:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  593:     return 'no_host';
                    594: }
                    595: 
                    596: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       597: 
1.599     albertel  598: my %homecache;
1.1       albertel  599: sub homeserver {
1.230     stredwic  600:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  601:     my $index="$uname:$udom";
1.426     albertel  602: 
1.599     albertel  603:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  604:     my $tryserver;
                    605:     foreach $tryserver (keys %libserv) {
1.230     stredwic  606:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  607: 		 exists($badServerCache{$tryserver}));
1.1       albertel  608: 	if ($hostdom{$tryserver} eq $udom) {
                    609:            my $answer=reply("home:$udom:$uname",$tryserver);
                    610:            if ($answer eq 'found') { 
1.599     albertel  611: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  612:            } elsif ($answer eq 'no_host') {
                    613: 	       $badServerCache{$tryserver}=1;
1.221     matthew   614:            }
1.1       albertel  615:        }
                    616:     }    
                    617:     return 'no_host';
1.70      www       618: }
                    619: 
                    620: # ------------------------------------- Find the usernames behind a list of IDs
                    621: 
                    622: sub idget {
                    623:     my ($udom,@ids)=@_;
                    624:     my %returnhash=();
                    625:     
                    626:     my $tryserver;
                    627:     foreach $tryserver (keys %libserv) {
                    628:        if ($hostdom{$tryserver} eq $udom) {
                    629: 	  my $idlist=join('&',@ids);
                    630:           $idlist=~tr/A-Z/a-z/; 
                    631: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    632:           my @answer=();
1.76      www       633:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       634: 	      @answer=split(/\&/,$reply);
                    635:           }                    ;
                    636:           my $i;
                    637:           for ($i=0;$i<=$#ids;$i++) {
                    638:               if ($answer[$i]) {
                    639: 		  $returnhash{$ids[$i]}=$answer[$i];
                    640:               } 
                    641:           }
                    642:        }
                    643:     }    
                    644:     return %returnhash;
                    645: }
                    646: 
                    647: # ------------------------------------- Find the IDs behind a list of usernames
                    648: 
                    649: sub idrget {
                    650:     my ($udom,@unames)=@_;
                    651:     my %returnhash=();
1.191     harris41  652:     foreach (@unames) {
1.70      www       653:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  654:     }
1.70      www       655:     return %returnhash;
                    656: }
                    657: 
                    658: # ------------------------------- Store away a list of names and associated IDs
                    659: 
                    660: sub idput {
                    661:     my ($udom,%ids)=@_;
                    662:     my %servers=();
1.191     harris41  663:     foreach (keys %ids) {
1.487     albertel  664: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       665:         my $uhom=&homeserver($_,$udom);
                    666:         if ($uhom ne 'no_host') {
                    667:             my $id=&escape($ids{$_});
                    668:             $id=~tr/A-Z/a-z/;
                    669:             my $unam=&escape($_);
                    670: 	    if ($servers{$uhom}) {
                    671: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    672:             } else {
                    673:                 $servers{$uhom}=$id.'='.$unam;
                    674:             }
                    675:         }
1.191     harris41  676:     }
                    677:     foreach (keys %servers) {
1.70      www       678:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  679:     }
1.344     www       680: }
                    681: 
                    682: # --------------------------------------------------- Assign a key to a student
                    683: 
                    684: sub assign_access_key {
1.364     www       685: #
                    686: # a valid key looks like uname:udom#comments
                    687: # comments are being appended
                    688: #
1.498     www       689:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    690:     $kdom=
1.620     albertel  691:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       692:     $knum=
1.620     albertel  693:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       694:     $cdom=
1.620     albertel  695:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       696:     $cnum=
1.620     albertel  697:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    698:     $udom=$env{'user.name'} unless (defined($udom));
                    699:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       700:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       701:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  702:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       703:                                                   # assigned to this person
                    704:                                                   # - this should not happen,
1.345     www       705:                                                   # unless something went wrong
                    706:                                                   # the first time around
                    707: # ready to assign
1.364     www       708:         $logentry=$1.'; '.$logentry;
1.496     www       709:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       710:                                                  $kdom,$knum) eq 'ok') {
1.345     www       711: # key now belongs to user
1.346     www       712: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       713:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    714:                 &appenv('environment.'.$envkey => $ckey);
                    715:                 return 'ok';
                    716:             } else {
                    717:                 return 
                    718:   'error: Count not permanently assign key, will need to be re-entered later.';
                    719: 	    }
                    720:         } else {
                    721:             return 'error: Could not assign key, try again later.';
                    722:         }
1.364     www       723:     } elsif (!$existing{$ckey}) {
1.345     www       724: # the key does not exist
                    725: 	return 'error: The key does not exist';
                    726:     } else {
                    727: # the key is somebody else's
                    728: 	return 'error: The key is already in use';
                    729:     }
1.344     www       730: }
                    731: 
1.364     www       732: # ------------------------------------------ put an additional comment on a key
                    733: 
                    734: sub comment_access_key {
                    735: #
                    736: # a valid key looks like uname:udom#comments
                    737: # comments are being appended
                    738: #
                    739:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    740:     $cdom=
1.620     albertel  741:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       742:     $cnum=
1.620     albertel  743:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       744:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    745:     if ($existing{$ckey}) {
                    746:         $existing{$ckey}.='; '.$logentry;
                    747: # ready to assign
1.367     www       748:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       749:                                                  $cdom,$cnum) eq 'ok') {
                    750: 	    return 'ok';
                    751:         } else {
                    752: 	    return 'error: Count not store comment.';
                    753:         }
                    754:     } else {
                    755: # the key does not exist
                    756: 	return 'error: The key does not exist';
                    757:     }
                    758: }
                    759: 
1.344     www       760: # ------------------------------------------------------ Generate a set of keys
                    761: 
                    762: sub generate_access_keys {
1.364     www       763:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       764:     $cdom=
1.620     albertel  765:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       766:     $cnum=
1.620     albertel  767:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       768:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       769:     unless (($cdom) && ($cnum)) { return 0; }
                    770:     if ($number>10000) { return 0; }
                    771:     sleep(2); # make sure don't get same seed twice
                    772:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    773:     my $total=0;
                    774:     for (my $i=1;$i<=$number;$i++) {
                    775:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    776:                   sprintf("%lx",int(100000*rand)).'-'.
                    777:                   sprintf("%lx",int(100000*rand));
                    778:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    779:        $newkey=~s/0/h/g; # and also 0 and O
                    780:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    781:        if ($existing{$newkey}) {
                    782:            $i--;
                    783:        } else {
1.364     www       784: 	  if (&put('accesskeys',
                    785:               { $newkey => '# generated '.localtime().
1.620     albertel  786:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       787:                            '; '.$logentry },
                    788: 		   $cdom,$cnum) eq 'ok') {
1.344     www       789:               $total++;
                    790: 	  }
                    791:        }
                    792:     }
1.620     albertel  793:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       794:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    795:     return $total;
                    796: }
                    797: 
                    798: # ------------------------------------------------------- Validate an accesskey
                    799: 
                    800: sub validate_access_key {
                    801:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    802:     $cdom=
1.620     albertel  803:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       804:     $cnum=
1.620     albertel  805:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    806:     $udom=$env{'user.domain'} unless (defined($udom));
                    807:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       808:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  809:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       810: }
                    811: 
                    812: # ------------------------------------- Find the section of student in a course
1.652     albertel  813: sub devalidate_getsection_cache {
                    814:     my ($udom,$unam,$courseid)=@_;
                    815:     $courseid=~s/\_/\//g;
                    816:     $courseid=~s/^(\w)/\/$1/;
                    817:     my $hashid="$udom:$unam:$courseid";
                    818:     &devalidate_cache_new('getsection',$hashid);
                    819: }
1.298     matthew   820: 
                    821: sub getsection {
                    822:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  823:     my $cachetime=1800;
1.298     matthew   824:     $courseid=~s/\_/\//g;
                    825:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  826: 
                    827:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  828:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  829:     if (defined($cached)) { return $result; }
                    830: 
1.298     matthew   831:     my %Pending; 
                    832:     my %Expired;
                    833:     #
                    834:     # Each role can either have not started yet (pending), be active, 
                    835:     #    or have expired.
                    836:     #
                    837:     # If there is an active role, we are done.
                    838:     #
                    839:     # If there is more than one role which has not started yet, 
                    840:     #     choose the one which will start sooner
                    841:     # If there is one role which has not started yet, return it.
                    842:     #
                    843:     # If there is more than one expired role, choose the one which ended last.
                    844:     # If there is a role which has expired, return it.
                    845:     #
                    846:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    847:                         &homeserver($unam,$udom)))) {
                    848:         my ($key,$value)=split(/\=/,$_);
                    849:         $key=&unescape($key);
1.479     albertel  850:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   851:         my $section=$1;
                    852:         if ($key eq $courseid.'_st') { $section=''; }
                    853:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    854:         my $now=time;
1.548     albertel  855:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   856:             $Expired{$end}=$section;
                    857:             next;
                    858:         }
1.548     albertel  859:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   860:             $Pending{$start}=$section;
                    861:             next;
                    862:         }
1.599     albertel  863:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   864:     }
                    865:     #
                    866:     # Presumedly there will be few matching roles from the above
                    867:     # loop and the sorting time will be negligible.
                    868:     if (scalar(keys(%Pending))) {
                    869:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  870:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   871:     } 
                    872:     if (scalar(keys(%Expired))) {
                    873:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    874:         my $time = pop(@sorted);
1.599     albertel  875:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   876:     }
1.599     albertel  877:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   878: }
1.70      www       879: 
1.599     albertel  880: sub save_cache {
                    881:     &purge_remembered();
1.722     albertel  882:     #&Apache::loncommon::validate_page();
1.620     albertel  883:     undef(%env);
1.780     albertel  884:     undef($env_loaded);
1.599     albertel  885: }
1.452     albertel  886: 
1.599     albertel  887: my $to_remember=-1;
                    888: my %remembered;
                    889: my %accessed;
                    890: my $kicks=0;
                    891: my $hits=0;
                    892: sub devalidate_cache_new {
                    893:     my ($name,$id,$debug) = @_;
                    894:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    895:     $id=&escape($name.':'.$id);
                    896:     $memcache->delete($id);
                    897:     delete($remembered{$id});
                    898:     delete($accessed{$id});
                    899: }
                    900: 
                    901: sub is_cached_new {
                    902:     my ($name,$id,$debug) = @_;
                    903:     $id=&escape($name.':'.$id);
                    904:     if (exists($remembered{$id})) {
                    905: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    906: 	$accessed{$id}=[&gettimeofday()];
                    907: 	$hits++;
                    908: 	return ($remembered{$id},1);
                    909:     }
                    910:     my $value = $memcache->get($id);
                    911:     if (!(defined($value))) {
                    912: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  913: 	return (undef,undef);
1.416     albertel  914:     }
1.599     albertel  915:     if ($value eq '__undef__') {
                    916: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    917: 	$value=undef;
                    918:     }
                    919:     &make_room($id,$value,$debug);
                    920:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    921:     return ($value,1);
                    922: }
                    923: 
                    924: sub do_cache_new {
                    925:     my ($name,$id,$value,$time,$debug) = @_;
                    926:     $id=&escape($name.':'.$id);
                    927:     my $setvalue=$value;
                    928:     if (!defined($setvalue)) {
                    929: 	$setvalue='__undef__';
                    930:     }
1.623     albertel  931:     if (!defined($time) ) {
                    932: 	$time=600;
                    933:     }
1.599     albertel  934:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  935:     $memcache->set($id,$setvalue,$time);
                    936:     # need to make a copy of $value
                    937:     #&make_room($id,$value,$debug);
1.599     albertel  938:     return $value;
                    939: }
                    940: 
                    941: sub make_room {
                    942:     my ($id,$value,$debug)=@_;
                    943:     $remembered{$id}=$value;
                    944:     if ($to_remember<0) { return; }
                    945:     $accessed{$id}=[&gettimeofday()];
                    946:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    947:     my $to_kick;
                    948:     my $max_time=0;
                    949:     foreach my $other (keys(%accessed)) {
                    950: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    951: 	    $to_kick=$other;
                    952: 	    $max_time=&tv_interval($accessed{$other});
                    953: 	}
                    954:     }
                    955:     delete($remembered{$to_kick});
                    956:     delete($accessed{$to_kick});
                    957:     $kicks++;
                    958:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  959:     return;
                    960: }
                    961: 
1.599     albertel  962: sub purge_remembered {
1.604     albertel  963:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    964:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  965:     undef(%remembered);
                    966:     undef(%accessed);
1.428     albertel  967: }
1.70      www       968: # ------------------------------------- Read an entry from a user's environment
                    969: 
                    970: sub userenvironment {
                    971:     my ($udom,$unam,@what)=@_;
                    972:     my %returnhash=();
                    973:     my @answer=split(/\&/,
                    974:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    975:                       &homeserver($unam,$udom)));
                    976:     my $i;
                    977:     for ($i=0;$i<=$#what;$i++) {
                    978: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    979:     }
                    980:     return %returnhash;
1.1       albertel  981: }
                    982: 
1.617     albertel  983: # ---------------------------------------------------------- Get a studentphoto
                    984: sub studentphoto {
                    985:     my ($udom,$unam,$ext) = @_;
                    986:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   987:     if (defined($env{'request.course.id'})) {
1.708     raeburn   988:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   989:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    990:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    991:             } else {
                    992:                 my ($result,$perm_reqd)=
1.707     albertel  993: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   994:                 if ($result eq 'ok') {
                    995:                     if (!($perm_reqd eq 'yes')) {
                    996:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    997:                     }
                    998:                 }
                    999:             }
                   1000:         }
                   1001:     } else {
                   1002:         my ($result,$perm_reqd) = 
1.707     albertel 1003: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1004:         if ($result eq 'ok') {
                   1005:             if (!($perm_reqd eq 'yes')) {
                   1006:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1007:             }
                   1008:         }
                   1009:     }
                   1010:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1011: }
                   1012: 
                   1013: sub retrievestudentphoto {
                   1014:     my ($udom,$unam,$ext,$type) = @_;
                   1015:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1016:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1017:     if ($ret eq 'ok') {
                   1018:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1019:         if ($type eq 'thumbnail') {
                   1020:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1021:         }
                   1022:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1023:         return $tokenurl;
                   1024:     } else {
                   1025:         if ($type eq 'thumbnail') {
                   1026:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1027:         } else { 
                   1028:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1029:         }
1.617     albertel 1030:     }
                   1031: }
                   1032: 
1.263     www      1033: # -------------------------------------------------------------------- New chat
                   1034: 
                   1035: sub chatsend {
1.724     raeburn  1036:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1037:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1038:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1039:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1040:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1041: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1042: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1043: }
                   1044: 
                   1045: # ------------------------------------------ Find current version of a resource
                   1046: 
                   1047: sub getversion {
                   1048:     my $fname=&clutter(shift);
                   1049:     unless ($fname=~/^\/res\//) { return -1; }
                   1050:     return &currentversion(&filelocation('',$fname));
                   1051: }
                   1052: 
                   1053: sub currentversion {
                   1054:     my $fname=shift;
1.599     albertel 1055:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1056:     if (defined($cached)) { return $result; }
1.292     www      1057:     my $author=$fname;
                   1058:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1059:     my ($udom,$uname)=split(/\//,$author);
                   1060:     my $home=homeserver($uname,$udom);
                   1061:     if ($home eq 'no_host') { 
                   1062:         return -1; 
                   1063:     }
                   1064:     my $answer=reply("currentversion:$fname",$home);
                   1065:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1066: 	return -1;
                   1067:     }
1.599     albertel 1068:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1069: }
                   1070: 
1.1       albertel 1071: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1072: 
1.1       albertel 1073: sub subscribe {
                   1074:     my $fname=shift;
1.761     raeburn  1075:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1076:     $fname=~s/[\n\r]//g;
1.1       albertel 1077:     my $author=$fname;
                   1078:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1079:     my ($udom,$uname)=split(/\//,$author);
                   1080:     my $home=homeserver($uname,$udom);
1.335     albertel 1081:     if ($home eq 'no_host') {
                   1082:         return 'not_found';
1.1       albertel 1083:     }
                   1084:     my $answer=reply("sub:$fname",$home);
1.64      www      1085:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1086: 	$answer.=' by '.$home;
                   1087:     }
1.1       albertel 1088:     return $answer;
                   1089: }
                   1090:     
1.8       www      1091: # -------------------------------------------------------------- Replicate file
                   1092: 
                   1093: sub repcopy {
                   1094:     my $filename=shift;
1.23      www      1095:     $filename=~s/\/+/\//g;
1.607     raeburn  1096:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1097:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1098:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1099: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1100: 	return &repcopy_userfile($filename);
                   1101:     }
1.532     albertel 1102:     $filename=~s/[\n\r]//g;
1.8       www      1103:     my $transname="$filename.in.transfer";
1.607     raeburn  1104:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1105:     my $remoteurl=subscribe($filename);
1.64      www      1106:     if ($remoteurl =~ /^con_lost by/) {
                   1107: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1108:            return 'unavailable';
1.8       www      1109:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1110: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1111: 	   return 'not_found';
1.64      www      1112:     } elsif ($remoteurl =~ /^rejected by/) {
                   1113: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1114:            return 'forbidden';
1.20      www      1115:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1116:            return 'ok';
1.8       www      1117:     } else {
1.290     www      1118:         my $author=$filename;
                   1119:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1120:         my ($udom,$uname)=split(/\//,$author);
                   1121:         my $home=homeserver($uname,$udom);
                   1122:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1123:            my @parts=split(/\//,$filename);
                   1124:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1125:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1126:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1127: 	       return 'bad_request';
1.8       www      1128:            }
                   1129:            my $count;
                   1130:            for ($count=5;$count<$#parts;$count++) {
                   1131:                $path.="/$parts[$count]";
                   1132:                if ((-e $path)!=1) {
                   1133: 		   mkdir($path,0777);
                   1134:                }
                   1135:            }
                   1136:            my $ua=new LWP::UserAgent;
                   1137:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1138:            my $response=$ua->request($request,$transname);
                   1139:            if ($response->is_error()) {
                   1140: 	       unlink($transname);
                   1141:                my $message=$response->status_line;
1.672     albertel 1142:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1143:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1144:                return 'unavailable';
1.8       www      1145:            } else {
1.16      www      1146: 	       if ($remoteurl!~/\.meta$/) {
                   1147:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1148:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1149:                   if ($mresponse->is_error()) {
                   1150: 		      unlink($filename.'.meta');
                   1151:                       &logthis(
1.672     albertel 1152:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1153:                   }
                   1154: 	       }
1.8       www      1155:                rename($transname,$filename);
1.607     raeburn  1156:                return 'ok';
1.8       www      1157:            }
1.290     www      1158:        }
1.8       www      1159:     }
1.330     www      1160: }
                   1161: 
                   1162: # ------------------------------------------------ Get server side include body
                   1163: sub ssi_body {
1.381     albertel 1164:     my ($filelink,%form)=@_;
1.606     matthew  1165:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1166:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1167:     }
1.330     www      1168:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1169:                                      &ssi($filelink,%form));
1.778     albertel 1170:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1171:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1172:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1173:     return $output;
1.8       www      1174: }
                   1175: 
1.15      www      1176: # --------------------------------------------------------- Server Side Include
                   1177: 
1.782     albertel 1178: sub absolute_url {
                   1179:     my ($host_name) = @_;
                   1180:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1181:     if ($host_name eq '') {
                   1182: 	$host_name = $ENV{'SERVER_NAME'};
                   1183:     }
                   1184:     return $protocol.$host_name;
                   1185: }
                   1186: 
1.783     albertel 1187: sub absolute_url {
                   1188:     my ($host_name) = @_;
                   1189:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1190:     if ($host_name eq '') {
                   1191: 	$host_name = $ENV{'SERVER_NAME'};
                   1192:     }
                   1193:     return $protocol.$host_name;
                   1194: }
                   1195: 
1.15      www      1196: sub ssi {
                   1197: 
1.23      www      1198:     my ($fn,%form)=@_;
1.15      www      1199: 
                   1200:     my $ua=new LWP::UserAgent;
1.23      www      1201:     
                   1202:     my $request;
1.711     albertel 1203: 
                   1204:     $form{'no_update_last_known'}=1;
                   1205: 
1.23      www      1206:     if (%form) {
1.782     albertel 1207:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1208:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1209:     } else {
1.782     albertel 1210:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1211:     }
                   1212: 
1.15      www      1213:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1214:     my $response=$ua->request($request);
                   1215: 
1.324     www      1216:     return $response->content;
                   1217: }
                   1218: 
                   1219: sub externalssi {
                   1220:     my ($url)=@_;
                   1221:     my $ua=new LWP::UserAgent;
                   1222:     my $request=new HTTP::Request('GET',$url);
                   1223:     my $response=$ua->request($request);
1.15      www      1224:     return $response->content;
                   1225: }
1.254     www      1226: 
1.492     albertel 1227: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1228: 
                   1229: sub allowuploaded {
                   1230:     my ($srcurl,$url)=@_;
                   1231:     $url=&clutter(&declutter($url));
                   1232:     my $dir=$url;
                   1233:     $dir=~s/\/[^\/]+$//;
                   1234:     my %httpref=();
                   1235:     my $httpurl=&hreflocation('',$url);
                   1236:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1237:     &Apache::lonnet::appenv(%httpref);
1.254     www      1238: }
1.477     raeburn  1239: 
1.478     albertel 1240: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1241: # input: action, courseID, current domain, intended
1.637     raeburn  1242: #        path to file, source of file, instruction to parse file for objects,
                   1243: #        ref to hash for embedded objects,
                   1244: #        ref to hash for codebase of java objects.
                   1245: #
1.485     raeburn  1246: # output: url to file (if action was uploaddoc), 
                   1247: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1248: #
1.478     albertel 1249: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1250: # course.
1.477     raeburn  1251: #
1.478     albertel 1252: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1253: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1254: #          course's home server.
1.477     raeburn  1255: #
1.478     albertel 1256: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1257: #          be copied from $source (current location) to 
                   1258: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1259: #         and will then be copied to
                   1260: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1261: #         course's home server.
1.485     raeburn  1262: #
1.481     raeburn  1263: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1264: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1265: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1266: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1267: #         in course's home server.
1.637     raeburn  1268: #
1.477     raeburn  1269: 
                   1270: sub process_coursefile {
1.638     albertel 1271:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1272:     my $fetchresult;
1.638     albertel 1273:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1274:     if ($action eq 'propagate') {
1.638     albertel 1275:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1276: 			     $home);
1.481     raeburn  1277:     } else {
1.477     raeburn  1278:         my $fpath = '';
                   1279:         my $fname = $file;
1.478     albertel 1280:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1281:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1282:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1283:         if ($action eq 'copy') {
                   1284:             if ($source eq '') {
                   1285:                 $fetchresult = 'no source file';
                   1286:                 return $fetchresult;
                   1287:             } else {
                   1288:                 my $destination = $filepath.'/'.$fname;
                   1289:                 rename($source,$destination);
                   1290:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1291:                                  $home);
1.481     raeburn  1292:             }
                   1293:         } elsif ($action eq 'uploaddoc') {
                   1294:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1295:             print $fh $env{'form.'.$source};
1.481     raeburn  1296:             close($fh);
1.637     raeburn  1297:             if ($parser eq 'parse') {
                   1298:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1299:                 unless ($parse_result eq 'ok') {
                   1300:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1301:                 }
                   1302:             }
1.477     raeburn  1303:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1304:                                  $home);
1.481     raeburn  1305:             if ($fetchresult eq 'ok') {
                   1306:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1307:             } else {
                   1308:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1309:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1310:                 return '/adm/notfound.html';
                   1311:             }
1.477     raeburn  1312:         }
                   1313:     }
1.485     raeburn  1314:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1315:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1316:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1317:     }
                   1318:     return $fetchresult;
                   1319: }
                   1320: 
1.637     raeburn  1321: sub build_filepath {
                   1322:     my ($fpath) = @_;
                   1323:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1324:     unless ($fpath eq '') {
                   1325:         my @parts=split('/',$fpath);
                   1326:         foreach my $part (@parts) {
                   1327:             $filepath.= '/'.$part;
                   1328:             if ((-e $filepath)!=1) {
                   1329:                 mkdir($filepath,0777);
                   1330:             }
                   1331:         }
                   1332:     }
                   1333:     return $filepath;
                   1334: }
                   1335: 
                   1336: sub store_edited_file {
1.638     albertel 1337:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1338:     my $file = $primary_url;
                   1339:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1340:     my $fpath = '';
                   1341:     my $fname = $file;
                   1342:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1343:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1344:     my $filepath = &build_filepath($fpath);
                   1345:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1346:     print $fh $content;
                   1347:     close($fh);
1.638     albertel 1348:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1349:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1350: 			  $home);
1.637     raeburn  1351:     if ($$fetchresult eq 'ok') {
                   1352:         return '/uploaded/'.$fpath.'/'.$fname;
                   1353:     } else {
1.638     albertel 1354:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1355: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1356:         return '/adm/notfound.html';
                   1357:     }
                   1358: }
                   1359: 
1.531     albertel 1360: sub clean_filename {
                   1361:     my ($fname)=@_;
1.315     www      1362: # Replace Windows backslashes by forward slashes
1.257     www      1363:     $fname=~s/\\/\//g;
1.315     www      1364: # Get rid of everything but the actual filename
1.257     www      1365:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1366: # Replace spaces by underscores
                   1367:     $fname=~s/\s+/\_/g;
                   1368: # Replace all other weird characters by nothing
1.317     www      1369:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1370: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1371: # numbers
                   1372:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1373:     return $fname;
                   1374: }
                   1375: 
1.608     albertel 1376: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1377: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1378: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1379: #        $coursedoc - if true up to the current course
                   1380: #                     if false
                   1381: #        $subdir - directory in userfile to store the file into
                   1382: #        $parser, $allfiles, $codebase - unknown
                   1383: #
                   1384: # output: url of file in userspace, or error: <message> 
                   1385: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1386: 
                   1387: 
1.531     albertel 1388: sub userfileupload {
1.719     banghart 1389:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1390:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1391:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1392:     $fname=&clean_filename($fname);
1.315     www      1393: # See if there is anything left
1.257     www      1394:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1395:     chop($env{'form.'.$formname});
1.523     raeburn  1396:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1397:         my $now = time;
                   1398:         my $filepath = 'tmp/helprequests/'.$now;
                   1399:         my @parts=split(/\//,$filepath);
                   1400:         my $fullpath = $perlvar{'lonDaemons'};
                   1401:         for (my $i=0;$i<@parts;$i++) {
                   1402:             $fullpath .= '/'.$parts[$i];
                   1403:             if ((-e $fullpath)!=1) {
                   1404:                 mkdir($fullpath,0777);
                   1405:             }
                   1406:         }
                   1407:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1408:         print $fh $env{'form.'.$formname};
1.523     raeburn  1409:         close($fh);
1.741     raeburn  1410:         return $fullpath.'/'.$fname;
                   1411:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1412:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1413:                        '_'.$env{'user.domain'}.'/pending';
                   1414:         my @parts=split(/\//,$filepath);
                   1415:         my $fullpath = $perlvar{'lonDaemons'};
                   1416:         for (my $i=0;$i<@parts;$i++) {
                   1417:             $fullpath .= '/'.$parts[$i];
                   1418:             if ((-e $fullpath)!=1) {
                   1419:                 mkdir($fullpath,0777);
                   1420:             }
                   1421:         }
                   1422:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1423:         print $fh $env{'form.'.$formname};
                   1424:         close($fh);
                   1425:         return $fullpath.'/'.$fname;
1.523     raeburn  1426:     }
1.719     banghart 1427:     
1.258     www      1428: # Create the directory if not present
1.493     albertel 1429:     $fname="$subdir/$fname";
1.259     www      1430:     if ($coursedoc) {
1.638     albertel 1431: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1432: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1433:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1434:             return &finishuserfileupload($docuname,$docudom,
                   1435: 					 $formname,$fname,$parser,$allfiles,
                   1436: 					 $codebase);
1.481     raeburn  1437:         } else {
1.620     albertel 1438:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1439:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1440: 				       $fname,$formname,$parser,
                   1441: 				       $allfiles,$codebase);
1.481     raeburn  1442:         }
1.719     banghart 1443:     } elsif (defined($destuname)) {
                   1444:         my $docuname=$destuname;
                   1445:         my $docudom=$destudom;
                   1446: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1447: 				     $fname,$parser,$allfiles,$codebase);
                   1448:         
1.259     www      1449:     } else {
1.638     albertel 1450:         my $docuname=$env{'user.name'};
                   1451:         my $docudom=$env{'user.domain'};
1.714     raeburn  1452:         if (exists($env{'form.group'})) {
                   1453:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1454:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1455:         }
1.638     albertel 1456: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1457: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1458:     }
1.271     www      1459: }
                   1460: 
                   1461: sub finishuserfileupload {
1.638     albertel 1462:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1463:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1464:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1465:     my ($fnamepath,$file);
                   1466:     $file=$fname;
                   1467:     if ($fname=~m|/|) {
                   1468:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1469: 	$path.=$fnamepath.'/';
                   1470:     }
1.259     www      1471:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1472:     my $count;
                   1473:     for ($count=4;$count<=$#parts;$count++) {
                   1474:         $filepath.="/$parts[$count]";
                   1475:         if ((-e $filepath)!=1) {
                   1476: 	    mkdir($filepath,0777);
                   1477:         }
                   1478:     }
                   1479: # Save the file
                   1480:     {
1.701     albertel 1481: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1482: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1483: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1484: 	    return '/adm/notfound.html';
                   1485: 	}
                   1486: 	if (!print FH ($env{'form.'.$formname})) {
                   1487: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1488: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1489: 	    return '/adm/notfound.html';
                   1490: 	}
1.570     albertel 1491: 	close(FH);
1.258     www      1492:     }
1.637     raeburn  1493:     if ($parser eq 'parse') {
1.638     albertel 1494:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1495: 						   $codebase);
1.637     raeburn  1496:         unless ($parse_result eq 'ok') {
1.638     albertel 1497:             &logthis('Failed to parse '.$filepath.$file.
                   1498: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1499:         }
                   1500:     }
1.259     www      1501: # Notify homeserver to grep it
                   1502: #
1.638     albertel 1503:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1504:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1505:     if ($fetchresult eq 'ok') {
1.259     www      1506: #
1.258     www      1507: # Return the URL to it
1.494     albertel 1508:         return '/uploaded/'.$path.$file;
1.263     www      1509:     } else {
1.494     albertel 1510:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1511: 		 ': '.$fetchresult);
1.263     www      1512:         return '/adm/notfound.html';
                   1513:     }    
1.493     albertel 1514: }
                   1515: 
1.637     raeburn  1516: sub extract_embedded_items {
1.648     raeburn  1517:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1518:     my @state = ();
                   1519:     my %javafiles = (
                   1520:                       codebase => '',
                   1521:                       code => '',
                   1522:                       archive => ''
                   1523:                     );
                   1524:     my %mediafiles = (
                   1525:                       src => '',
                   1526:                       movie => '',
                   1527:                      );
1.648     raeburn  1528:     my $p;
                   1529:     if ($content) {
                   1530:         $p = HTML::LCParser->new($content);
                   1531:     } else {
                   1532:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1533:     }
1.641     albertel 1534:     while (my $t=$p->get_token()) {
1.640     albertel 1535: 	if ($t->[0] eq 'S') {
                   1536: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1537: 	    push (@state, $tagname);
1.648     raeburn  1538:             if (lc($tagname) eq 'allow') {
                   1539:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1540:             }
1.640     albertel 1541: 	    if (lc($tagname) eq 'img') {
                   1542: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1543: 	    }
1.645     raeburn  1544:             if (lc($tagname) eq 'script') {
                   1545:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1546:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1547:                 } else {
                   1548:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1549:                 }
                   1550:             }
                   1551:             if (lc($tagname) eq 'link') {
                   1552:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1553:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1554:                 }
                   1555:             }
1.640     albertel 1556: 	    if (lc($tagname) eq 'object' ||
                   1557: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1558: 		foreach my $item (keys(%javafiles)) {
                   1559: 		    $javafiles{$item} = '';
                   1560: 		}
                   1561: 	    }
                   1562: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1563: 		my $name = lc($attr->{'name'});
                   1564: 		foreach my $item (keys(%javafiles)) {
                   1565: 		    if ($name eq $item) {
                   1566: 			$javafiles{$item} = $attr->{'value'};
                   1567: 			last;
                   1568: 		    }
                   1569: 		}
                   1570: 		foreach my $item (keys(%mediafiles)) {
                   1571: 		    if ($name eq $item) {
                   1572: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1573: 			last;
                   1574: 		    }
                   1575: 		}
                   1576: 	    }
                   1577: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1578: 		foreach my $item (keys(%javafiles)) {
                   1579: 		    if ($attr->{$item}) {
                   1580: 			$javafiles{$item} = $attr->{$item};
                   1581: 			last;
                   1582: 		    }
                   1583: 		}
                   1584: 		foreach my $item (keys(%mediafiles)) {
                   1585: 		    if ($attr->{$item}) {
                   1586: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1587: 			last;
                   1588: 		    }
                   1589: 		}
                   1590: 	    }
                   1591: 	} elsif ($t->[0] eq 'E') {
                   1592: 	    my ($tagname) = ($t->[1]);
                   1593: 	    if ($javafiles{'codebase'} ne '') {
                   1594: 		$javafiles{'codebase'} .= '/';
                   1595: 	    }  
                   1596: 	    if (lc($tagname) eq 'applet' ||
                   1597: 		lc($tagname) eq 'object' ||
                   1598: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1599: 		) {
                   1600: 		foreach my $item (keys(%javafiles)) {
                   1601: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1602: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1603: 			&add_filetype($allfiles,$file,$item);
                   1604: 		    }
                   1605: 		}
                   1606: 	    } 
                   1607: 	    pop @state;
                   1608: 	}
                   1609:     }
1.637     raeburn  1610:     return 'ok';
                   1611: }
                   1612: 
1.639     albertel 1613: sub add_filetype {
                   1614:     my ($allfiles,$file,$type)=@_;
                   1615:     if (exists($allfiles->{$file})) {
                   1616: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1617: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1618: 	}
                   1619:     } else {
                   1620: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1621:     }
                   1622: }
                   1623: 
1.493     albertel 1624: sub removeuploadedurl {
                   1625:     my ($url)=@_;
                   1626:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1627:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1628: }
                   1629: 
                   1630: sub removeuserfile {
                   1631:     my ($docuname,$docudom,$fname)=@_;
                   1632:     my $home=&homeserver($docuname,$docudom);
                   1633:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1634: }
1.15      www      1635: 
1.530     albertel 1636: sub mkdiruserfile {
                   1637:     my ($docuname,$docudom,$dir)=@_;
                   1638:     my $home=&homeserver($docuname,$docudom);
                   1639:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1640: }
                   1641: 
1.531     albertel 1642: sub renameuserfile {
                   1643:     my ($docuname,$docudom,$old,$new)=@_;
                   1644:     my $home=&homeserver($docuname,$docudom);
                   1645:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1646: 		  &escape("$new"),$home);
                   1647: }
                   1648: 
1.14      www      1649: # ------------------------------------------------------------------------- Log
                   1650: 
                   1651: sub log {
                   1652:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1653:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1654: }
                   1655: 
                   1656: # ------------------------------------------------------------------ Course Log
1.352     www      1657: #
                   1658: # This routine flushes several buffers of non-mission-critical nature
                   1659: #
1.157     www      1660: 
                   1661: sub flushcourselogs {
1.352     www      1662:     &logthis('Flushing log buffers');
                   1663: #
                   1664: # course logs
                   1665: # This is a log of all transactions in a course, which can be used
                   1666: # for data mining purposes
                   1667: #
                   1668: # It also collects the courseid database, which lists last transaction
                   1669: # times and course titles for all courseids
                   1670: #
                   1671:     my %courseidbuffer=();
1.191     harris41 1672:     foreach (keys %courselogs) {
1.157     www      1673:         my $crsid=$_;
1.352     www      1674:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1675: 		          &escape($courselogs{$crsid}),
                   1676: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1677: 	    delete $courselogs{$crsid};
                   1678:         } else {
                   1679:             &logthis('Failed to flush log buffer for '.$crsid);
                   1680:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1681:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1682:                         " exceeded maximum size, deleting.</font>");
                   1683:                delete $courselogs{$crsid};
                   1684:             }
1.352     www      1685:         }
                   1686:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1687:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1688: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1689:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1690:         } else {
                   1691:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1692: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1693:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1694:         }
1.191     harris41 1695:     }
1.352     www      1696: #
                   1697: # Write course id database (reverse lookup) to homeserver of courses 
                   1698: # Is used in pickcourse
                   1699: #
                   1700:     foreach (keys %courseidbuffer) {
1.353     www      1701:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1702:     }
                   1703: #
                   1704: # File accesses
                   1705: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1706: #
1.449     matthew  1707:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1708:         if ($entry =~ /___count$/) {
                   1709:             my ($dom,$name);
                   1710:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1711:             if (! defined($dom) || $dom eq '' || 
                   1712:                 ! defined($name) || $name eq '') {
1.620     albertel 1713:                 my $cid = $env{'request.course.id'};
                   1714:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1715:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1716:             }
1.450     matthew  1717:             my $value = $accesshash{$entry};
                   1718:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1719:             my %temphash=($url => $value);
1.449     matthew  1720:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1721:             if ($result eq 'ok') {
                   1722:                 delete $accesshash{$entry};
                   1723:             } elsif ($result eq 'unknown_cmd') {
                   1724:                 # Target server has old code running on it.
1.450     matthew  1725:                 my %temphash=($entry => $value);
1.449     matthew  1726:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1727:                     delete $accesshash{$entry};
                   1728:                 }
                   1729:             }
                   1730:         } else {
1.458     matthew  1731:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1732:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1733:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1734:                 delete $accesshash{$entry};
                   1735:             }
1.185     www      1736:         }
1.191     harris41 1737:     }
1.352     www      1738: #
                   1739: # Roles
                   1740: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1741: #
1.349     www      1742:     foreach (keys %userrolehash) {
                   1743:         my $entry=$_;
1.351     www      1744:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1745: 	    split(/\:/,$entry);
                   1746:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1747:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1748:                 $rudom,$runame) eq 'ok') {
                   1749: 	    delete $userrolehash{$entry};
                   1750:         }
                   1751:     }
1.662     raeburn  1752: #
                   1753: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1754: #
                   1755:     my %domrolebuffer = ();
                   1756:     foreach my $entry (keys %domainrolehash) {
                   1757:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1758:         if ($domrolebuffer{$rudom}) {
                   1759:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1760:                       '='.&escape($domainrolehash{$entry});
                   1761:         } else {
                   1762:             $domrolebuffer{$rudom}.=&escape($entry).
                   1763:                       '='.&escape($domainrolehash{$entry});
                   1764:         }
                   1765:         delete $domainrolehash{$entry};
                   1766:     }
                   1767:     foreach my $dom (keys(%domrolebuffer)) {
                   1768:         foreach my $tryserver (keys %libserv) {
                   1769:             if ($hostdom{$tryserver} eq $dom) {
                   1770:                 unless (&reply('domroleput:'.$dom.':'.
                   1771:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1772:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1773:                 }
                   1774:             }
                   1775:         }
                   1776:     }
1.186     www      1777:     $dumpcount++;
1.157     www      1778: }
                   1779: 
                   1780: sub courselog {
                   1781:     my $what=shift;
1.158     www      1782:     $what=time.':'.$what;
1.620     albertel 1783:     unless ($env{'request.course.id'}) { return ''; }
                   1784:     $coursedombuf{$env{'request.course.id'}}=
                   1785:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1786:     $coursenumbuf{$env{'request.course.id'}}=
                   1787:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1788:     $coursehombuf{$env{'request.course.id'}}=
                   1789:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1790:     $coursedescrbuf{$env{'request.course.id'}}=
                   1791:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1792:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1793:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1794:     $courseownerbuf{$env{'request.course.id'}}=
                   1795:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1796:     $coursetypebuf{$env{'request.course.id'}}=
                   1797:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1798:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1799: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1800:     } else {
1.620     albertel 1801: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1802:     }
1.620     albertel 1803:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1804: 	&flushcourselogs();
                   1805:     }
1.158     www      1806: }
                   1807: 
                   1808: sub courseacclog {
                   1809:     my $fnsymb=shift;
1.620     albertel 1810:     unless ($env{'request.course.id'}) { return ''; }
                   1811:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1812:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1813:         $what.=':POST';
1.583     matthew  1814:         # FIXME: Probably ought to escape things....
1.620     albertel 1815: 	foreach (keys %env) {
1.158     www      1816:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1817: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1818:             }
1.191     harris41 1819:         }
1.583     matthew  1820:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1821:         # FIXME: We should not be depending on a form parameter that someone
                   1822:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1823:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1824:             $what.= ':POST';
                   1825:             # FIXME: Probably ought to escape things....
                   1826:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1827:                                  'crsdiscuss') {
1.620     albertel 1828:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1829:             }
                   1830:         }
1.158     www      1831:     }
                   1832:     &courselog($what);
1.149     www      1833: }
                   1834: 
1.185     www      1835: sub countacc {
                   1836:     my $url=&declutter(shift);
1.458     matthew  1837:     return if (! defined($url) || $url eq '');
1.620     albertel 1838:     unless ($env{'request.course.id'}) { return ''; }
                   1839:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1840:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1841:     $accesshash{$key}++;
1.185     www      1842: }
1.349     www      1843: 
1.361     www      1844: sub linklog {
                   1845:     my ($from,$to)=@_;
                   1846:     $from=&declutter($from);
                   1847:     $to=&declutter($to);
                   1848:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1849:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1850: }
                   1851:   
1.349     www      1852: sub userrolelog {
                   1853:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1854:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1855:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1856:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1857:         ($trole=~/^ta/)) {
1.350     www      1858:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1859:        $userrolehash
                   1860:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1861:                     =$tend.':'.$tstart;
1.662     raeburn  1862:     }
                   1863:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1864:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1865:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1866:         ($trole=~/^sc/)) {
                   1867:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1868:        $domainrolehash
                   1869:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1870:                     = $tend.':'.$tstart;
                   1871:     }
1.351     www      1872: }
                   1873: 
                   1874: sub get_course_adv_roles {
                   1875:     my $cid=shift;
1.620     albertel 1876:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1877:     my %coursehash=&coursedescription($cid);
1.470     www      1878:     my %nothide=();
                   1879:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1880: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1881:     }
1.351     www      1882:     my %returnhash=();
                   1883:     my %dumphash=
                   1884:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1885:     my $now=time;
                   1886:     foreach (keys %dumphash) {
                   1887: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1888:         if (($tstart) && ($tstart<0)) { next; }
                   1889:         if (($tend) && ($tend<$now)) { next; }
                   1890:         if (($tstart) && ($now<$tstart)) { next; }
                   1891:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1892: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1893: 	if ((&privileged($username,$domain)) && 
                   1894: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1895: 	if ($role eq 'cr') { next; }
1.351     www      1896:         my $key=&plaintext($role);
                   1897:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1898:         if ($returnhash{$key}) {
                   1899: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1900:         } else {
                   1901:             $returnhash{$key}=$username.':'.$domain;
                   1902:         }
1.400     www      1903:      }
                   1904:     return %returnhash;
                   1905: }
                   1906: 
                   1907: sub get_my_roles {
                   1908:     my ($uname,$udom)=@_;
1.620     albertel 1909:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1910:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1911:     my %dumphash=
                   1912:             &dump('nohist_userroles',$udom,$uname);
                   1913:     my %returnhash=();
                   1914:     my $now=time;
                   1915:     foreach (keys %dumphash) {
                   1916: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1917:         if (($tstart) && ($tstart<0)) { next; }
                   1918:         if (($tend) && ($tend<$now)) { next; }
                   1919:         if (($tstart) && ($now<$tstart)) { next; }
                   1920:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1921: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1922:      }
                   1923:     return %returnhash;
1.399     www      1924: }
                   1925: 
                   1926: # ----------------------------------------------------- Frontpage Announcements
                   1927: #
                   1928: #
                   1929: 
                   1930: sub postannounce {
                   1931:     my ($server,$text)=@_;
                   1932:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1933:     unless ($text=~/\w/) { $text=''; }
                   1934:     return &reply('setannounce:'.&escape($text),$server);
                   1935: }
                   1936: 
                   1937: sub getannounce {
1.448     albertel 1938: 
                   1939:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1940: 	my $announcement='';
                   1941: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1942: 	close($fh);
1.399     www      1943: 	if ($announcement=~/\w/) { 
                   1944: 	    return 
                   1945:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1946:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1947: 	} else {
                   1948: 	    return '';
                   1949: 	}
                   1950:     } else {
                   1951: 	return '';
                   1952:     }
1.351     www      1953: }
1.353     www      1954: 
                   1955: # ---------------------------------------------------------- Course ID routines
                   1956: # Deal with domain's nohist_courseid.db files
                   1957: #
                   1958: 
                   1959: sub courseidput {
                   1960:     my ($domain,$what,$coursehome)=@_;
                   1961:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1962: }
                   1963: 
                   1964: sub courseiddump {
1.741     raeburn  1965:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1966:     my %returnhash=();
1.355     www      1967:     unless ($domfilter) { $domfilter=''; }
1.353     www      1968:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1969:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1970: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1971: 	        foreach (
                   1972:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1973: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1974:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1975:                                $tryserver))) {
1.506     raeburn  1976: 		    my ($key,$value)=split(/\=/,$_);
                   1977:                     if (($key) && ($value)) {
1.516     raeburn  1978: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1979:                     }
1.353     www      1980:                 }
                   1981:             }
                   1982:         }
                   1983:     }
                   1984:     return %returnhash;
                   1985: }
                   1986: 
1.658     raeburn  1987: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1988: 
                   1989: sub dcmailput {
1.685     raeburn  1990:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1991:     my $status = &Apache::lonnet::critical(
1.740     www      1992:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1993:        &escape($message),$server);
1.662     raeburn  1994:     return $status;
                   1995: }
                   1996: 
1.658     raeburn  1997: sub dcmaildump {
                   1998:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1999:     my %returnhash=();
                   2000:     if (exists($domain_primary{$dom})) {
                   2001:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2002:                                                          &escape($enddate).':';
                   2003: 	my @esc_senders=map { &escape($_)} @$senders;
                   2004: 	$cmd.=&escape(join('&',@esc_senders));
                   2005: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2006:             my ($key,$value) = split(/\=/,$_);
                   2007:             if (($key) && ($value)) {
                   2008:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2009:             }
                   2010:         }
                   2011:     }
                   2012:     return %returnhash;
                   2013: }
1.662     raeburn  2014: # ---------------------------------------------------------- Domain roles
                   2015: 
                   2016: sub get_domain_roles {
                   2017:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2018:     if (undef($startdate) || $startdate eq '') {
                   2019:         $startdate = '.';
                   2020:     }
                   2021:     if (undef($enddate) || $enddate eq '') {
                   2022:         $enddate = '.';
                   2023:     }
                   2024:     my $rolelist = join(':',@{$roles});
                   2025:     my %personnel = ();
                   2026:     foreach my $tryserver (keys(%libserv)) {
                   2027:         if ($hostdom{$tryserver} eq $dom) {
                   2028:             %{$personnel{$tryserver}}=();
                   2029:             foreach (
                   2030:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2031:                    &escape($startdate).':'.&escape($enddate).':'.
                   2032:                    &escape($rolelist), $tryserver))) {
                   2033:                 my($key,$value) = split(/\=/,$_);
                   2034:                 if (($key) && ($value)) {
                   2035:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2036:                 }
                   2037:             }
                   2038:         }
                   2039:     }
                   2040:     return %personnel;
                   2041: }
1.658     raeburn  2042: 
1.149     www      2043: # ----------------------------------------------------------- Check out an item
                   2044: 
1.504     albertel 2045: sub get_first_access {
                   2046:     my ($type,$argsymb)=@_;
                   2047:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2048:     if ($argsymb) { $symb=$argsymb; }
                   2049:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2050:     if ($type eq 'map') {
                   2051: 	$res=&symbread($map);
                   2052:     } else {
                   2053: 	$res=$symb;
                   2054:     }
                   2055:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2056:     return $times{"$courseid\0$res"};
1.504     albertel 2057: }
                   2058: 
                   2059: sub set_first_access {
                   2060:     my ($type)=@_;
                   2061:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2062:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2063:     if ($type eq 'map') {
                   2064: 	$res=&symbread($map);
                   2065:     } else {
                   2066: 	$res=$symb;
                   2067:     }
                   2068:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2069:     if (!$firstaccess) {
1.588     albertel 2070: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2071:     }
                   2072:     return 'already_set';
1.504     albertel 2073: }
                   2074: 
1.149     www      2075: sub checkout {
                   2076:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2077:     my $now=time;
                   2078:     my $lonhost=$perlvar{'lonHostID'};
                   2079:     my $infostr=&escape(
1.234     www      2080:                  'CHECKOUTTOKEN&'.
1.149     www      2081:                  $tuname.'&'.
                   2082:                  $tudom.'&'.
                   2083:                  $tcrsid.'&'.
                   2084:                  $symb.'&'.
                   2085: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2086:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2087:     if ($token=~/^error\:/) { 
1.672     albertel 2088:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2089:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2090:                  "</font>");
                   2091:         return ''; 
                   2092:     }
                   2093: 
1.149     www      2094:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2095:     $token=~tr/a-z/A-Z/;
                   2096: 
1.153     www      2097:     my %infohash=('resource.0.outtoken' => $token,
                   2098:                   'resource.0.checkouttime' => $now,
                   2099:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2100: 
                   2101:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2102:        return '';
1.151     www      2103:     } else {
1.672     albertel 2104:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2105:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2106:                  "</font>");
1.149     www      2107:     }    
                   2108: 
                   2109:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2110:                          &escape('Checkout '.$infostr.' - '.
                   2111:                                                  $token)) ne 'ok') {
                   2112: 	return '';
1.151     www      2113:     } else {
1.672     albertel 2114:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2115:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2116:                  "</font>");
1.149     www      2117:     }
1.151     www      2118:     return $token;
1.149     www      2119: }
                   2120: 
                   2121: # ------------------------------------------------------------ Check in an item
                   2122: 
                   2123: sub checkin {
                   2124:     my $token=shift;
1.150     www      2125:     my $now=time;
                   2126:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2127:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2128:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2129:     $dtoken=~s/\W/\_/g;
1.234     www      2130:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2131:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2132: 
1.154     www      2133:     unless (($tuname) && ($tudom)) {
                   2134:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2135:         return '';
                   2136:     }
                   2137:     
                   2138:     unless (&allowed('mgr',$tcrsid)) {
                   2139:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2140:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2141:         return '';
                   2142:     }
                   2143: 
1.153     www      2144:     my %infohash=('resource.0.intoken' => $token,
                   2145:                   'resource.0.checkintime' => $now,
                   2146:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2147: 
                   2148:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2149:        return '';
                   2150:     }    
                   2151: 
                   2152:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2153:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2154: 	return '';
                   2155:     }
                   2156: 
                   2157:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2158: }
                   2159: 
                   2160: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2161: 
                   2162: sub expirespread {
                   2163:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2164:     my $cid=$env{'request.course.id'}; 
1.110     www      2165:     if ($cid) {
                   2166:        my $now=time;
                   2167:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2168:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2169:                             $env{'course.'.$cid.'.num'}.
1.110     www      2170: 	        	    ':nohist_expirationdates:'.
                   2171:                             &escape($key).'='.$now,
1.620     albertel 2172:                             $env{'course.'.$cid.'.home'})
1.110     www      2173:     }
                   2174:     return 'ok';
1.14      www      2175: }
                   2176: 
1.109     www      2177: # ----------------------------------------------------- Devalidate Spreadsheets
                   2178: 
                   2179: sub devalidate {
1.325     www      2180:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2181:     my $cid=$env{'request.course.id'}; 
1.109     www      2182:     if ($cid) {
1.391     matthew  2183:         # delete the stored spreadsheets for
                   2184:         # - the student level sheet of this user in course's homespace
                   2185:         # - the assessment level sheet for this resource 
                   2186:         #   for this user in user's homespace
1.553     albertel 2187: 	# - current conditional state info
1.325     www      2188: 	my $key=$uname.':'.$udom.':';
1.109     www      2189:         my $status=
1.299     matthew  2190: 	    &del('nohist_calculatedsheets',
1.391     matthew  2191: 		 [$key.'studentcalc:'],
1.620     albertel 2192: 		 $env{'course.'.$cid.'.domain'},
                   2193: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2194: 		.' '.
                   2195: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2196: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2197:         unless ($status eq 'ok ok') {
                   2198:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2199:                     $uname.' at '.$udom.' for '.
1.109     www      2200: 		    $symb.': '.$status);
1.133     albertel 2201:         }
1.553     albertel 2202: 	&delenv('user.state.'.$cid);
1.109     www      2203:     }
                   2204: }
                   2205: 
1.265     albertel 2206: sub get_scalar {
                   2207:     my ($string,$end) = @_;
                   2208:     my $value;
                   2209:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2210: 	$value = $1;
                   2211:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2212: 	$value = $1;
                   2213:     }
                   2214:     return &unescape($value);
                   2215: }
                   2216: 
                   2217: sub array2str {
                   2218:   my (@array) = @_;
                   2219:   my $result=&arrayref2str(\@array);
                   2220:   $result=~s/^__ARRAY_REF__//;
                   2221:   $result=~s/__END_ARRAY_REF__$//;
                   2222:   return $result;
                   2223: }
                   2224: 
1.204     albertel 2225: sub arrayref2str {
                   2226:   my ($arrayref) = @_;
1.265     albertel 2227:   my $result='__ARRAY_REF__';
1.204     albertel 2228:   foreach my $elem (@$arrayref) {
1.265     albertel 2229:     if(ref($elem) eq 'ARRAY') {
                   2230:       $result.=&arrayref2str($elem).'&';
                   2231:     } elsif(ref($elem) eq 'HASH') {
                   2232:       $result.=&hashref2str($elem).'&';
                   2233:     } elsif(ref($elem)) {
                   2234:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2235:     } else {
                   2236:       $result.=&escape($elem).'&';
                   2237:     }
                   2238:   }
                   2239:   $result=~s/\&$//;
1.265     albertel 2240:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2241:   return $result;
                   2242: }
                   2243: 
1.168     albertel 2244: sub hash2str {
1.204     albertel 2245:   my (%hash) = @_;
                   2246:   my $result=&hashref2str(\%hash);
1.265     albertel 2247:   $result=~s/^__HASH_REF__//;
                   2248:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2249:   return $result;
                   2250: }
                   2251: 
                   2252: sub hashref2str {
                   2253:   my ($hashref)=@_;
1.265     albertel 2254:   my $result='__HASH_REF__';
1.495     albertel 2255:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2256:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2257:       $result.=&arrayref2str($_).'=';
1.204     albertel 2258:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2259:       $result.=&hashref2str($_).'=';
1.204     albertel 2260:     } elsif (ref($_)) {
1.265     albertel 2261:       $result.='=';
                   2262:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2263:     } else {
1.265     albertel 2264: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2265:     }
                   2266: 
1.265     albertel 2267:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2268:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2269:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2270:       $result.=&hashref2str($hashref->{$_}).'&';
                   2271:     } elsif(ref($hashref->{$_})) {
                   2272:        $result.='&';
                   2273:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2274:     } else {
1.265     albertel 2275:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2276:     }
                   2277:   }
1.168     albertel 2278:   $result=~s/\&$//;
1.265     albertel 2279:   $result .= '__END_HASH_REF__';
1.168     albertel 2280:   return $result;
                   2281: }
                   2282: 
                   2283: sub str2hash {
1.265     albertel 2284:     my ($string)=@_;
                   2285:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2286:     return %$hash;
                   2287: }
                   2288: 
                   2289: sub str2hashref {
1.168     albertel 2290:   my ($string) = @_;
1.265     albertel 2291: 
                   2292:   my %hash;
                   2293: 
                   2294:   if($string !~ /^__HASH_REF__/) {
                   2295:       if (! ($string eq '' || !defined($string))) {
                   2296: 	  $hash{'error'}='Not hash reference';
                   2297:       }
                   2298:       return (\%hash, $string);
                   2299:   }
                   2300: 
                   2301:   $string =~ s/^__HASH_REF__//;
                   2302: 
                   2303:   while($string !~ /^__END_HASH_REF__/) {
                   2304:       #key
                   2305:       my $key='';
                   2306:       if($string =~ /^__HASH_REF__/) {
                   2307:           ($key, $string)=&str2hashref($string);
                   2308:           if(defined($key->{'error'})) {
                   2309:               $hash{'error'}='Bad data';
                   2310:               return (\%hash, $string);
                   2311:           }
                   2312:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2313:           ($key, $string)=&str2arrayref($string);
                   2314:           if($key->[0] eq 'Array reference error') {
                   2315:               $hash{'error'}='Bad data';
                   2316:               return (\%hash, $string);
                   2317:           }
                   2318:       } else {
                   2319:           $string =~ s/^(.*?)=//;
1.267     albertel 2320: 	  $key=&unescape($1);
1.265     albertel 2321:       }
                   2322:       $string =~ s/^=//;
                   2323: 
                   2324:       #value
                   2325:       my $value='';
                   2326:       if($string =~ /^__HASH_REF__/) {
                   2327:           ($value, $string)=&str2hashref($string);
                   2328:           if(defined($value->{'error'})) {
                   2329:               $hash{'error'}='Bad data';
                   2330:               return (\%hash, $string);
                   2331:           }
                   2332:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2333:           ($value, $string)=&str2arrayref($string);
                   2334:           if($value->[0] eq 'Array reference error') {
                   2335:               $hash{'error'}='Bad data';
                   2336:               return (\%hash, $string);
                   2337:           }
                   2338:       } else {
                   2339: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2340:       }
                   2341:       $string =~ s/^&//;
                   2342: 
                   2343:       $hash{$key}=$value;
1.204     albertel 2344:   }
1.265     albertel 2345: 
                   2346:   $string =~ s/^__END_HASH_REF__//;
                   2347: 
                   2348:   return (\%hash, $string);
1.204     albertel 2349: }
                   2350: 
                   2351: sub str2array {
1.265     albertel 2352:     my ($string)=@_;
                   2353:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2354:     return @$array;
                   2355: }
                   2356: 
                   2357: sub str2arrayref {
1.204     albertel 2358:   my ($string) = @_;
1.265     albertel 2359:   my @array;
                   2360: 
                   2361:   if($string !~ /^__ARRAY_REF__/) {
                   2362:       if (! ($string eq '' || !defined($string))) {
                   2363: 	  $array[0]='Array reference error';
                   2364:       }
                   2365:       return (\@array, $string);
                   2366:   }
                   2367: 
                   2368:   $string =~ s/^__ARRAY_REF__//;
                   2369: 
                   2370:   while($string !~ /^__END_ARRAY_REF__/) {
                   2371:       my $value='';
                   2372:       if($string =~ /^__HASH_REF__/) {
                   2373:           ($value, $string)=&str2hashref($string);
                   2374:           if(defined($value->{'error'})) {
                   2375:               $array[0] ='Array reference error';
                   2376:               return (\@array, $string);
                   2377:           }
                   2378:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2379:           ($value, $string)=&str2arrayref($string);
                   2380:           if($value->[0] eq 'Array reference error') {
                   2381:               $array[0] ='Array reference error';
                   2382:               return (\@array, $string);
                   2383:           }
                   2384:       } else {
                   2385: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2386:       }
                   2387:       $string =~ s/^&//;
                   2388: 
                   2389:       push(@array, $value);
1.191     harris41 2390:   }
1.265     albertel 2391: 
                   2392:   $string =~ s/^__END_ARRAY_REF__//;
                   2393: 
                   2394:   return (\@array, $string);
1.168     albertel 2395: }
                   2396: 
1.167     albertel 2397: # -------------------------------------------------------------------Temp Store
                   2398: 
1.168     albertel 2399: sub tmpreset {
                   2400:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2401:   if (!$symb) {
                   2402:     $symb=&symbread();
1.620     albertel 2403:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2404:   }
                   2405:   $symb=escape($symb);
                   2406: 
1.620     albertel 2407:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2408:   $namespace=~s/\//\_/g;
                   2409:   $namespace=~s/\W//g;
                   2410: 
1.620     albertel 2411:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2412:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2413:   if ($domain eq 'public' && $stuname eq 'public') {
                   2414:       $stuname=$ENV{'REMOTE_ADDR'};
                   2415:   }
1.168     albertel 2416:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2417:   my %hash;
                   2418:   if (tie(%hash,'GDBM_File',
                   2419: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2420: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2421:     foreach my $key (keys %hash) {
1.180     albertel 2422:       if ($key=~ /:$symb/) {
1.168     albertel 2423: 	delete($hash{$key});
                   2424:       }
                   2425:     }
                   2426:   }
                   2427: }
                   2428: 
1.167     albertel 2429: sub tmpstore {
1.168     albertel 2430:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2431: 
                   2432:   if (!$symb) {
                   2433:     $symb=&symbread();
1.620     albertel 2434:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2435:   }
                   2436:   $symb=escape($symb);
                   2437: 
                   2438:   if (!$namespace) {
                   2439:     # I don't think we would ever want to store this for a course.
                   2440:     # it seems this will only be used if we don't have a course.
1.620     albertel 2441:     #$namespace=$env{'request.course.id'};
1.168     albertel 2442:     #if (!$namespace) {
1.620     albertel 2443:       $namespace=$env{'request.state'};
1.168     albertel 2444:     #}
                   2445:   }
                   2446:   $namespace=~s/\//\_/g;
                   2447:   $namespace=~s/\W//g;
1.620     albertel 2448:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2449:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2450:   if ($domain eq 'public' && $stuname eq 'public') {
                   2451:       $stuname=$ENV{'REMOTE_ADDR'};
                   2452:   }
1.168     albertel 2453:   my $now=time;
                   2454:   my %hash;
                   2455:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2456:   if (tie(%hash,'GDBM_File',
                   2457: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2458: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2459:     $hash{"version:$symb"}++;
                   2460:     my $version=$hash{"version:$symb"};
                   2461:     my $allkeys=''; 
                   2462:     foreach my $key (keys(%$storehash)) {
                   2463:       $allkeys.=$key.':';
1.591     albertel 2464:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2465:     }
                   2466:     $hash{"$version:$symb:timestamp"}=$now;
                   2467:     $allkeys.='timestamp';
                   2468:     $hash{"$version:keys:$symb"}=$allkeys;
                   2469:     if (untie(%hash)) {
                   2470:       return 'ok';
                   2471:     } else {
                   2472:       return "error:$!";
                   2473:     }
                   2474:   } else {
                   2475:     return "error:$!";
                   2476:   }
                   2477: }
1.167     albertel 2478: 
1.168     albertel 2479: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2480: 
1.168     albertel 2481: sub tmprestore {
                   2482:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2483: 
1.168     albertel 2484:   if (!$symb) {
                   2485:     $symb=&symbread();
1.620     albertel 2486:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2487:   }
                   2488:   $symb=escape($symb);
                   2489: 
1.620     albertel 2490:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2491: 
1.620     albertel 2492:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2493:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2494:   if ($domain eq 'public' && $stuname eq 'public') {
                   2495:       $stuname=$ENV{'REMOTE_ADDR'};
                   2496:   }
1.168     albertel 2497:   my %returnhash;
                   2498:   $namespace=~s/\//\_/g;
                   2499:   $namespace=~s/\W//g;
                   2500:   my %hash;
                   2501:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2502:   if (tie(%hash,'GDBM_File',
                   2503: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2504: 	  &GDBM_READER(),0640)) {
1.168     albertel 2505:     my $version=$hash{"version:$symb"};
                   2506:     $returnhash{'version'}=$version;
                   2507:     my $scope;
                   2508:     for ($scope=1;$scope<=$version;$scope++) {
                   2509:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2510:       my @keys=split(/:/,$vkeys);
                   2511:       my $key;
                   2512:       $returnhash{"$scope:keys"}=$vkeys;
                   2513:       foreach $key (@keys) {
1.591     albertel 2514: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2515: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2516:       }
                   2517:     }
1.168     albertel 2518:     if (!(untie(%hash))) {
                   2519:       return "error:$!";
                   2520:     }
                   2521:   } else {
                   2522:     return "error:$!";
                   2523:   }
                   2524:   return %returnhash;
1.167     albertel 2525: }
                   2526: 
1.9       www      2527: # ----------------------------------------------------------------------- Store
                   2528: 
                   2529: sub store {
1.124     www      2530:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2531:     my $home='';
                   2532: 
1.168     albertel 2533:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2534: 
1.213     www      2535:     $symb=&symbclean($symb);
1.122     albertel 2536:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2537: 
1.620     albertel 2538:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2539:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2540: 
                   2541:     &devalidate($symb,$stuname,$domain);
1.109     www      2542: 
                   2543:     $symb=escape($symb);
1.187     www      2544:     if (!$namespace) { 
1.620     albertel 2545:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2546:           return ''; 
                   2547:        } 
                   2548:     }
1.620     albertel 2549:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2550: 
                   2551:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2552:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2553: 
1.12      www      2554:     my $namevalue='';
1.191     harris41 2555:     foreach (keys %$storehash) {
1.591     albertel 2556:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2557:     }
1.12      www      2558:     $namevalue=~s/\&$//;
1.187     www      2559:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2560:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2561: }
                   2562: 
1.47      www      2563: # -------------------------------------------------------------- Critical Store
                   2564: 
                   2565: sub cstore {
1.124     www      2566:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2567:     my $home='';
                   2568: 
1.168     albertel 2569:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2570: 
1.213     www      2571:     $symb=&symbclean($symb);
1.122     albertel 2572:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2573: 
1.620     albertel 2574:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2575:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2576: 
                   2577:     &devalidate($symb,$stuname,$domain);
1.109     www      2578: 
                   2579:     $symb=escape($symb);
1.187     www      2580:     if (!$namespace) { 
1.620     albertel 2581:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2582:           return ''; 
                   2583:        } 
                   2584:     }
1.620     albertel 2585:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2586: 
                   2587:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2588:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2589: 
1.47      www      2590:     my $namevalue='';
1.191     harris41 2591:     foreach (keys %$storehash) {
1.591     albertel 2592:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2593:     }
1.47      www      2594:     $namevalue=~s/\&$//;
1.187     www      2595:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2596:     return critical
                   2597:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2598: }
                   2599: 
1.9       www      2600: # --------------------------------------------------------------------- Restore
                   2601: 
                   2602: sub restore {
1.124     www      2603:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2604:     my $home='';
                   2605: 
1.168     albertel 2606:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2607: 
1.122     albertel 2608:     if (!$symb) {
                   2609:       unless ($symb=escape(&symbread())) { return ''; }
                   2610:     } else {
1.213     www      2611:       $symb=&escape(&symbclean($symb));
1.122     albertel 2612:     }
1.188     www      2613:     if (!$namespace) { 
1.620     albertel 2614:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2615:           return ''; 
                   2616:        } 
                   2617:     }
1.620     albertel 2618:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2619:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2620:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2621:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2622: 
1.12      www      2623:     my %returnhash=();
1.191     harris41 2624:     foreach (split(/\&/,$answer)) {
1.12      www      2625: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2626:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2627:     }
1.75      www      2628:     my $version;
                   2629:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2630:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2631:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2632:        }
1.75      www      2633:     }
1.13      www      2634:     return %returnhash;
1.34      www      2635: }
                   2636: 
                   2637: # ---------------------------------------------------------- Course Description
                   2638: 
                   2639: sub coursedescription {
1.731     albertel 2640:     my ($courseid,$args)=@_;
1.34      www      2641:     $courseid=~s/^\///;
1.49      www      2642:     $courseid=~s/\_/\//g;
1.34      www      2643:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2644:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2645:     my $normalid=$cdomain.'_'.$cnum;
                   2646:     # need to always cache even if we get errors otherwise we keep 
                   2647:     # trying and trying and trying to get the course description.
                   2648:     my %envhash=();
                   2649:     my %returnhash=();
1.731     albertel 2650:     
                   2651:     my $expiretime=600;
                   2652:     if ($env{'request.course.id'} eq $normalid) {
                   2653: 	$expiretime=120;
                   2654:     }
                   2655: 
                   2656:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2657:     if (!$args->{'freshen_cache'}
                   2658: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2659: 	foreach my $key (keys(%env)) {
                   2660: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2661: 	    my ($setting) = $1;
                   2662: 	    $returnhash{$setting} = $env{$key};
                   2663: 	}
                   2664: 	return %returnhash;
                   2665:     }
                   2666: 
                   2667:     # get the data agin
                   2668:     if (!$args->{'one_time'}) {
                   2669: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2670:     }
1.34      www      2671:     if ($chome ne 'no_host') {
1.302     albertel 2672:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2673:        if (!exists($returnhash{'con_lost'})) {
                   2674:            $returnhash{'home'}= $chome;
                   2675: 	   $returnhash{'domain'} = $cdomain;
                   2676: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2677:            if (!defined($returnhash{'type'})) {
                   2678:                $returnhash{'type'} = 'Course';
                   2679:            }
1.130     albertel 2680:            while (my ($name,$value) = each %returnhash) {
1.53      www      2681:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2682:            }
1.270     www      2683:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2684:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2685: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2686:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2687:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2688:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2689:        }
                   2690:     }
1.731     albertel 2691:     if (!$args->{'one_time'}) {
                   2692: 	&appenv(%envhash);
                   2693:     }
1.302     albertel 2694:     return %returnhash;
1.461     www      2695: }
                   2696: 
                   2697: # -------------------------------------------------See if a user is privileged
                   2698: 
                   2699: sub privileged {
                   2700:     my ($username,$domain)=@_;
                   2701:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2702: 			&homeserver($username,$domain));
                   2703:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2704:     my $now=time;
                   2705:     if ($rolesdump ne '') {
                   2706:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2707: 	    if ($_!~/^rolesdef_/) {
1.461     www      2708: 		my ($area,$role)=split(/=/,$_);
                   2709: 		$area=~s/\_\w\w$//;
                   2710: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2711: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2712: 		    my $active=1;
                   2713: 		    if ($tend) {
                   2714: 			if ($tend<$now) { $active=0; }
                   2715: 		    }
                   2716: 		    if ($tstart) {
                   2717: 			if ($tstart>$now) { $active=0; }
                   2718: 		    }
                   2719: 		    if ($active) { return 1; }
                   2720: 		}
                   2721: 	    }
                   2722: 	}
                   2723:     }
                   2724:     return 0;
1.9       www      2725: }
1.1       albertel 2726: 
1.103     harris41 2727: # -------------------------------------------------------- Get user privileges
1.11      www      2728: 
                   2729: sub rolesinit {
                   2730:     my ($domain,$username,$authhost)=@_;
                   2731:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2732:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2733:     my %allroles=();
1.678     raeburn  2734:     my %allgroups=();   
1.11      www      2735:     my $now=time;
1.743     albertel 2736:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2737:     my $group_privs;
1.11      www      2738: 
                   2739:     if ($rolesdump ne '') {
1.191     harris41 2740:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2741: 	  if ($_!~/^rolesdef_/) {
1.11      www      2742:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2743: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2744:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2745: 	    if ($role=~/^cr/) { 
1.655     albertel 2746: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2747: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2748: 		    ($tend,$tstart)=split('_',$trest);
                   2749: 		} else {
                   2750: 		    $trole=$role;
                   2751: 		}
1.678     raeburn  2752:             } elsif ($role =~ m|^gr/|) {
                   2753:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2754:                 ($trole,$group_privs) = split(/\//,$trole);
                   2755:                 $group_privs = &unescape($group_privs);
1.587     albertel 2756: 	    } else {
                   2757: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2758: 	    }
1.743     albertel 2759: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2760: 					 $username);
                   2761: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2762:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2763:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2764:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2765: 		my $spec=$trole.'.'.$area;
                   2766: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2767: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2768:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2769:                 } elsif ($trole eq 'gr') {
                   2770:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2771: 		} else {
1.567     raeburn  2772:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2773: 		}
1.12      www      2774:             }
1.662     raeburn  2775:           }
1.191     harris41 2776:         }
1.743     albertel 2777:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2778:         $userroles{'user.adv'}    = $adv;
                   2779: 	$userroles{'user.author'} = $author;
1.620     albertel 2780:         $env{'user.adv'}=$adv;
1.11      www      2781:     }
1.743     albertel 2782:     return \%userroles;  
1.11      www      2783: }
                   2784: 
1.567     raeburn  2785: sub set_arearole {
                   2786:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2787: # log the associated role with the area
                   2788:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2789:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2790: }
                   2791: 
                   2792: sub custom_roleprivs {
                   2793:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2794:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2795:     my $homsvr=homeserver($rauthor,$rdomain);
                   2796:     if ($hostname{$homsvr} ne '') {
                   2797:         my ($rdummy,$roledef)=
                   2798:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2799:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2800:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2801:             if (defined($syspriv)) {
                   2802:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2803:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2804:             }
                   2805:             if ($tdomain ne '') {
                   2806:                 if (defined($dompriv)) {
                   2807:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2808:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2809:                 }
                   2810:                 if (($trest ne '') && (defined($coursepriv))) {
                   2811:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2812:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2813:                 }
                   2814:             }
                   2815:         }
                   2816:     }
                   2817: }
                   2818: 
1.678     raeburn  2819: sub group_roleprivs {
                   2820:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2821:     my $access = 1;
                   2822:     my $now = time;
                   2823:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2824:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2825:     if ($access) {
                   2826:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2827:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2828:     }
                   2829: }
1.567     raeburn  2830: 
                   2831: sub standard_roleprivs {
                   2832:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2833:     if (defined($pr{$trole.':s'})) {
                   2834:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2835:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2836:     }
                   2837:     if ($tdomain ne '') {
                   2838:         if (defined($pr{$trole.':d'})) {
                   2839:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2840:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2841:         }
                   2842:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2843:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2844:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2845:         }
                   2846:     }
                   2847: }
                   2848: 
                   2849: sub set_userprivs {
1.678     raeburn  2850:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2851:     my $author=0;
                   2852:     my $adv=0;
1.678     raeburn  2853:     my %grouproles = ();
                   2854:     if (keys(%{$allgroups}) > 0) {
                   2855:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2856:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2857:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2858:                 $trole = $1;
                   2859:                 $area = $2;
1.681     raeburn  2860:                 $sec = $3;
                   2861:                 $extendedarea = $area.$sec;
                   2862:                 if (exists($$allgroups{$area})) {
                   2863:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2864:                         my $spec = $trole.'.'.$extendedarea;
                   2865:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2866:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2867:                     }
                   2868:                 }
                   2869:             }
                   2870:         }
                   2871:     }
                   2872:     foreach (keys(%grouproles)) {
                   2873:         $$allroles{$_} = $grouproles{$_};
                   2874:     }
1.567     raeburn  2875:     foreach (keys %{$allroles}) {
                   2876:         my %thesepriv=();
                   2877:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2878:         foreach (split(/:/,$$allroles{$_})) {
                   2879:             if ($_ ne '') {
                   2880:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2881:                 if ($restrictions eq '') {
                   2882:                     $thesepriv{$privilege}='F';
                   2883:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2884:                     $thesepriv{$privilege}.=$restrictions;
                   2885:                 }
                   2886:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2887:             }
                   2888:         }
                   2889:         my $thesestr='';
                   2890:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2891:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2892:     }
                   2893:     return ($author,$adv);
                   2894: }
                   2895: 
1.12      www      2896: # --------------------------------------------------------------- get interface
                   2897: 
                   2898: sub get {
1.131     albertel 2899:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2900:    my $items='';
1.191     harris41 2901:    foreach (@$storearr) {
1.12      www      2902:        $items.=escape($_).'&';
1.191     harris41 2903:    }
1.12      www      2904:    $items=~s/\&$//;
1.620     albertel 2905:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2906:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2907:    my $uhome=&homeserver($uname,$udomain);
                   2908: 
1.133     albertel 2909:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2910:    my @pairs=split(/\&/,$rep);
1.273     albertel 2911:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2912:      return @pairs;
                   2913:    }
1.15      www      2914:    my %returnhash=();
1.42      www      2915:    my $i=0;
1.191     harris41 2916:    foreach (@$storearr) {
1.557     albertel 2917:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2918:       $i++;
1.191     harris41 2919:    }
1.15      www      2920:    return %returnhash;
1.27      www      2921: }
                   2922: 
                   2923: # --------------------------------------------------------------- del interface
                   2924: 
                   2925: sub del {
1.133     albertel 2926:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2927:    my $items='';
1.191     harris41 2928:    foreach (@$storearr) {
1.27      www      2929:        $items.=escape($_).'&';
1.191     harris41 2930:    }
1.27      www      2931:    $items=~s/\&$//;
1.620     albertel 2932:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2933:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2934:    my $uhome=&homeserver($uname,$udomain);
                   2935: 
                   2936:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2937: }
                   2938: 
                   2939: # -------------------------------------------------------------- dump interface
                   2940: 
                   2941: sub dump {
1.755     albertel 2942:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2943:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2944:     if (!$uname) { $uname=$env{'user.name'}; }
                   2945:     my $uhome=&homeserver($uname,$udomain);
                   2946:     if ($regexp) {
                   2947: 	$regexp=&escape($regexp);
                   2948:     } else {
                   2949: 	$regexp='.';
                   2950:     }
                   2951:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2952:     my @pairs=split(/\&/,$rep);
                   2953:     my %returnhash=();
                   2954:     foreach my $item (@pairs) {
                   2955: 	my ($key,$value)=split(/=/,$item,2);
                   2956: 	$key = &unescape($key);
                   2957: 	next if ($key =~ /^error: 2 /);
                   2958: 	$returnhash{$key}=&thaw_unescape($value);
                   2959:     }
                   2960:     return %returnhash;
1.407     www      2961: }
                   2962: 
1.717     albertel 2963: # --------------------------------------------------------- dumpstore interface
                   2964: 
                   2965: sub dumpstore {
                   2966:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2967:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2968: }
                   2969: 
1.407     www      2970: # -------------------------------------------------------------- keys interface
                   2971: 
                   2972: sub getkeys {
                   2973:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2974:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2975:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2976:    my $uhome=&homeserver($uname,$udomain);
                   2977:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2978:    my @keyarray=();
                   2979:    foreach (split(/\&/,$rep)) {
                   2980:       push (@keyarray,&unescape($_));
                   2981:    }
                   2982:    return @keyarray;
1.318     matthew  2983: }
                   2984: 
1.319     matthew  2985: # --------------------------------------------------------------- currentdump
                   2986: sub currentdump {
1.328     matthew  2987:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2988:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2989:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2990:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2991:    my $uhome = &homeserver($sname,$sdom);
                   2992:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2993:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2994:    #
1.318     matthew  2995:    my %returnhash=();
1.319     matthew  2996:    #
                   2997:    if ($rep eq "unknown_cmd") { 
                   2998:        # an old lond will not know currentdump
                   2999:        # Do a dump and make it look like a currentdump
1.326     matthew  3000:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3001:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3002:        my %hash = @tmp;
                   3003:        @tmp=();
1.424     matthew  3004:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3005:    } else {
                   3006:        my @pairs=split(/\&/,$rep);
                   3007:        foreach (@pairs) {
                   3008:            my ($key,$value)=split(/=/,$_);
                   3009:            my ($symb,$param) = split(/:/,$key);
                   3010:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3011:                                                         &thaw_unescape($value);
1.319     matthew  3012:        }
1.191     harris41 3013:    }
1.12      www      3014:    return %returnhash;
1.424     matthew  3015: }
                   3016: 
                   3017: sub convert_dump_to_currentdump{
                   3018:     my %hash = %{shift()};
                   3019:     my %returnhash;
                   3020:     # Code ripped from lond, essentially.  The only difference
                   3021:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3022:     # we might run in to problems with parameter names =~ /^v\./
                   3023:     while (my ($key,$value) = each(%hash)) {
                   3024:         my ($v,$symb,$param) = split(/:/,$key);
                   3025:         next if ($v eq 'version' || $symb eq 'keys');
                   3026:         next if (exists($returnhash{$symb}) &&
                   3027:                  exists($returnhash{$symb}->{$param}) &&
                   3028:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3029:         $returnhash{$symb}->{$param}=$value;
                   3030:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3031:     }
                   3032:     #
                   3033:     # Remove all of the keys in the hashes which keep track of
                   3034:     # the version of the parameter.
                   3035:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3036:         # use a foreach because we are going to delete from the hash.
                   3037:         foreach my $key (keys(%$param_hash)) {
                   3038:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3039:         }
                   3040:     }
                   3041:     return \%returnhash;
1.12      www      3042: }
                   3043: 
1.627     albertel 3044: # ------------------------------------------------------ critical inc interface
                   3045: 
                   3046: sub cinc {
                   3047:     return &inc(@_,'critical');
                   3048: }
                   3049: 
1.449     matthew  3050: # --------------------------------------------------------------- inc interface
                   3051: 
                   3052: sub inc {
1.627     albertel 3053:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3054:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3055:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3056:     my $uhome=&homeserver($uname,$udomain);
                   3057:     my $items='';
                   3058:     if (! ref($store)) {
                   3059:         # got a single value, so use that instead
                   3060:         $items = &escape($store).'=&';
                   3061:     } elsif (ref($store) eq 'SCALAR') {
                   3062:         $items = &escape($$store).'=&';        
                   3063:     } elsif (ref($store) eq 'ARRAY') {
                   3064:         $items = join('=&',map {&escape($_);} @{$store});
                   3065:     } elsif (ref($store) eq 'HASH') {
                   3066:         while (my($key,$value) = each(%{$store})) {
                   3067:             $items.= &escape($key).'='.&escape($value).'&';
                   3068:         }
                   3069:     }
                   3070:     $items=~s/\&$//;
1.627     albertel 3071:     if ($critical) {
                   3072: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3073:     } else {
                   3074: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3075:     }
1.449     matthew  3076: }
                   3077: 
1.12      www      3078: # --------------------------------------------------------------- put interface
                   3079: 
                   3080: sub put {
1.134     albertel 3081:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3082:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3083:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3084:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3085:    my $items='';
1.191     harris41 3086:    foreach (keys %$storehash) {
1.557     albertel 3087:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3088:    }
1.12      www      3089:    $items=~s/\&$//;
1.134     albertel 3090:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3091: }
                   3092: 
1.631     albertel 3093: # ------------------------------------------------------------ newput interface
                   3094: 
                   3095: sub newput {
                   3096:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3097:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3098:    if (!$uname) { $uname=$env{'user.name'}; }
                   3099:    my $uhome=&homeserver($uname,$udomain);
                   3100:    my $items='';
                   3101:    foreach my $key (keys(%$storehash)) {
                   3102:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3103:    }
                   3104:    $items=~s/\&$//;
                   3105:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3106: }
                   3107: 
                   3108: # ---------------------------------------------------------  putstore interface
                   3109: 
1.524     raeburn  3110: sub putstore {
1.715     albertel 3111:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3112:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3113:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3114:    my $uhome=&homeserver($uname,$udomain);
                   3115:    my $items='';
1.715     albertel 3116:    foreach my $key (keys(%$storehash)) {
                   3117:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3118:    }
1.715     albertel 3119:    $items=~s/\&$//;
1.716     albertel 3120:    my $esc_symb=&escape($symb);
                   3121:    my $esc_v=&escape($version);
1.715     albertel 3122:    my $reply =
1.716     albertel 3123:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3124: 	      $uhome);
                   3125:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3126:        # gfall back to way things use to be done
1.715     albertel 3127:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3128: 			    $uname);
1.524     raeburn  3129:    }
1.715     albertel 3130:    return $reply;
                   3131: }
                   3132: 
                   3133: sub old_putstore {
1.716     albertel 3134:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3135:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3136:     if (!$uname) { $uname=$env{'user.name'}; }
                   3137:     my $uhome=&homeserver($uname,$udomain);
                   3138:     my %newstorehash;
                   3139:     foreach (keys %$storehash) {
                   3140: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3141: 	$newstorehash{$key} = $storehash->{$_};
                   3142:     }
                   3143:     my $items='';
                   3144:     my %allitems = ();
                   3145:     foreach (keys %newstorehash) {
                   3146: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3147: 	    my $key = $1.':keys:'.$2;
                   3148: 	    $allitems{$key} .= $3.':';
                   3149: 	}
                   3150: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3151:     }
                   3152:     foreach (keys %allitems) {
                   3153: 	$allitems{$_} =~ s/\:$//;
                   3154: 	$items.= $_.'='.$allitems{$_}.'&';
                   3155:     }
                   3156:     $items=~s/\&$//;
                   3157:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3158: }
                   3159: 
1.47      www      3160: # ------------------------------------------------------ critical put interface
                   3161: 
                   3162: sub cput {
1.134     albertel 3163:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3164:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3165:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3166:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3167:    my $items='';
1.191     harris41 3168:    foreach (keys %$storehash) {
1.715     albertel 3169:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3170:    }
1.47      www      3171:    $items=~s/\&$//;
1.134     albertel 3172:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3173: }
                   3174: 
                   3175: # -------------------------------------------------------------- eget interface
                   3176: 
                   3177: sub eget {
1.133     albertel 3178:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3179:    my $items='';
1.191     harris41 3180:    foreach (@$storearr) {
1.12      www      3181:        $items.=escape($_).'&';
1.191     harris41 3182:    }
1.12      www      3183:    $items=~s/\&$//;
1.620     albertel 3184:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3185:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3186:    my $uhome=&homeserver($uname,$udomain);
                   3187:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3188:    my @pairs=split(/\&/,$rep);
                   3189:    my %returnhash=();
1.42      www      3190:    my $i=0;
1.191     harris41 3191:    foreach (@$storearr) {
1.557     albertel 3192:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3193:       $i++;
1.191     harris41 3194:    }
1.12      www      3195:    return %returnhash;
                   3196: }
                   3197: 
1.667     albertel 3198: # ------------------------------------------------------------ tmpput interface
                   3199: sub tmpput {
                   3200:     my ($storehash,$server)=@_;
                   3201:     my $items='';
                   3202:     foreach (keys(%$storehash)) {
                   3203: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3204:     }
                   3205:     $items=~s/\&$//;
                   3206:     return &reply("tmpput:$items",$server);
                   3207: }
                   3208: 
                   3209: # ------------------------------------------------------------ tmpget interface
                   3210: sub tmpget {
1.688     albertel 3211:     my ($token,$server)=@_;
                   3212:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3213:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3214:     my %returnhash;
                   3215:     foreach my $item (split(/\&/,$rep)) {
                   3216: 	my ($key,$value)=split(/=/,$item);
                   3217: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3218:     }
                   3219:     return %returnhash;
                   3220: }
                   3221: 
1.688     albertel 3222: # ------------------------------------------------------------ tmpget interface
                   3223: sub tmpdel {
                   3224:     my ($token,$server)=@_;
                   3225:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3226:     return &reply("tmpdel:$token",$server);
                   3227: }
                   3228: 
1.765     albertel 3229: # -------------------------------------------------- portfolio access checking
                   3230: 
                   3231: sub portfolio_access {
1.766     albertel 3232:     my ($requrl) = @_;
1.765     albertel 3233:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3234:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3235:     if ($result eq 'ok') {
1.766     albertel 3236:        return 'F';
1.765     albertel 3237:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3238:        return 'A';
1.765     albertel 3239:     }
1.766     albertel 3240:     return '';
1.765     albertel 3241: }
                   3242: 
                   3243: sub get_portfolio_access {
1.767     albertel 3244:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3245: 
                   3246:     if (!ref($access_hash)) {
                   3247: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3248: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3249: 						   $file_name);
                   3250: 	$access_hash = $access_controls{$file_name};
                   3251:     }
                   3252: 
1.765     albertel 3253:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3254:     my $now = time;
                   3255:     if (ref($access_hash) eq 'HASH') {
                   3256:         foreach my $key (keys(%{$access_hash})) {
                   3257:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3258:             if ($start > $now) {
                   3259:                 next;
                   3260:             }
                   3261:             if ($end && $end<$now) {
                   3262:                 next;
                   3263:             }
                   3264:             if ($scope eq 'public') {
                   3265:                 $public = $key;
                   3266:                 last;
                   3267:             } elsif ($scope eq 'guest') {
                   3268:                 $guest = $key;
                   3269:             } elsif ($scope eq 'domains') {
                   3270:                 push(@domains,$key);
                   3271:             } elsif ($scope eq 'users') {
                   3272:                 push(@users,$key);
                   3273:             } elsif ($scope eq 'course') {
                   3274:                 push(@courses,$key);
                   3275:             } elsif ($scope eq 'group') {
                   3276:                 push(@groups,$key);
                   3277:             }
                   3278:         }
                   3279:         if ($public) {
                   3280:             return 'ok';
                   3281:         }
                   3282:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3283:             if ($guest) {
                   3284:                 return $guest;
                   3285:             }
                   3286:         } else {
                   3287:             if (@domains > 0) {
                   3288:                 foreach my $domkey (@domains) {
                   3289:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3290:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3291:                             return 'ok';
                   3292:                         }
                   3293:                     }
                   3294:                 }
                   3295:             }
                   3296:             if (@users > 0) {
                   3297:                 foreach my $userkey (@users) {
                   3298:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3299:                         return 'ok';
                   3300:                     }
                   3301:                 }
                   3302:             }
                   3303:             my %roleshash;
                   3304:             my @courses_and_groups = @courses;
                   3305:             push(@courses_and_groups,@groups); 
                   3306:             if (@courses_and_groups > 0) {
                   3307:                 my (%allgroups,%allroles); 
                   3308:                 my ($start,$end,$role,$sec,$group);
                   3309:                 foreach my $envkey (%env) {
                   3310:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3311:                         my $cid = $2.'_'.$3; 
                   3312:                         if ($1 eq 'gr') {
                   3313:                             $group = $4;
                   3314:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3315:                         } else {
                   3316:                             if ($4 eq '') {
                   3317:                                 $sec = 'none';
                   3318:                             } else {
                   3319:                                 $sec = $4;
                   3320:                             }
                   3321:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3322:                         }
                   3323:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3324:                         my $cid = $2.'_'.$3;
                   3325:                         if ($4 eq '') {
                   3326:                             $sec = 'none';
                   3327:                         } else {
                   3328:                             $sec = $4;
                   3329:                         }
                   3330:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3331:                     }
                   3332:                 }
                   3333:                 if (keys(%allroles) == 0) {
                   3334:                     return;
                   3335:                 }
                   3336:                 foreach my $key (@courses_and_groups) {
                   3337:                     my %content = %{$$access_hash{$key}};
                   3338:                     my $cnum = $content{'number'};
                   3339:                     my $cdom = $content{'domain'};
                   3340:                     my $cid = $cdom.'_'.$cnum;
                   3341:                     if (!exists($allroles{$cid})) {
                   3342:                         next;
                   3343:                     }    
                   3344:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3345:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3346:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3347:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3348:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3349:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3350:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3351:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3352:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3353:                                         if (grep/^all$/,@sections) {
                   3354:                                             return 'ok';
                   3355:                                         } else {
                   3356:                                             if (grep/^$sec$/,@sections) {
                   3357:                                                 return 'ok';
                   3358:                                             }
                   3359:                                         }
                   3360:                                     }
                   3361:                                 }
                   3362:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3363:                                     if (grep/^none$/,@groups) {
                   3364:                                         return 'ok';
                   3365:                                     }
                   3366:                                 } else {
                   3367:                                     if (grep/^all$/,@groups) {
                   3368:                                         return 'ok';
                   3369:                                     } 
                   3370:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3371:                                         if (grep/^$group$/,@groups) {
                   3372:                                             return 'ok';
                   3373:                                         }
                   3374:                                     }
                   3375:                                 } 
                   3376:                             }
                   3377:                         }
                   3378:                     }
                   3379:                 }
                   3380:             }
                   3381:             if ($guest) {
                   3382:                 return $guest;
                   3383:             }
                   3384:         }
                   3385:     }
                   3386:     return;
                   3387: }
                   3388: 
                   3389: sub course_group_datechecker {
                   3390:     my ($dates,$now,$status) = @_;
                   3391:     my ($start,$end) = split(/\./,$dates);
                   3392:     if (!$start && !$end) {
                   3393:         return 'ok';
                   3394:     }
                   3395:     if (grep/^active$/,@{$status}) {
                   3396:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3397:             return 'ok';
                   3398:         }
                   3399:     }
                   3400:     if (grep/^previous$/,@{$status}) {
                   3401:         if ($end > $now ) {
                   3402:             return 'ok';
                   3403:         }
                   3404:     }
                   3405:     if (grep/^future$/,@{$status}) {
                   3406:         if ($start > $now) {
                   3407:             return 'ok';
                   3408:         }
                   3409:     }
                   3410:     return; 
                   3411: }
                   3412: 
                   3413: sub parse_portfolio_url {
                   3414:     my ($url) = @_;
                   3415: 
                   3416:     my ($type,$udom,$unum,$group,$file_name);
                   3417:     
                   3418:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3419: 	$type = 1;
                   3420:         $udom = $1;
                   3421:         $unum = $2;
                   3422:         $file_name = $3;
                   3423:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3424: 	$type = 2;
                   3425:         $udom = $1;
                   3426:         $unum = $2;
                   3427:         $group = $3;
                   3428:         $file_name = $3.'/'.$4;
                   3429:     }
                   3430:     if (wantarray) {
                   3431: 	return ($type,$udom,$unum,$file_name,$group);
                   3432:     }
                   3433:     return $type;
                   3434: }
                   3435: 
                   3436: sub is_portfolio_url {
                   3437:     my ($url) = @_;
                   3438:     return scalar(&parse_portfolio_url($url));
                   3439: }
                   3440: 
1.341     www      3441: # ---------------------------------------------- Custom access rule evaluation
                   3442: 
                   3443: sub customaccess {
                   3444:     my ($priv,$uri)=@_;
1.620     albertel 3445:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3446:     $urealm=~s/^\W//;
                   3447:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3448:     my $access=0;
                   3449:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3450: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3451:         if ($role) {
                   3452: 	   if ($role ne $urole) { next; }
                   3453:         }
                   3454:         foreach (split(/\s*\,\s*/,$realm)) {
                   3455:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3456:             if ($tdom) {
                   3457: 		if ($tdom ne $udom) { next; }
                   3458:             }
                   3459:             if ($tcrs) {
                   3460: 		if ($tcrs ne $ucrs) { next; }
                   3461:             }
                   3462:             if ($tsec) {
                   3463: 		if ($tsec ne $usec) { next; }
                   3464:             }
                   3465:             $access=($effect eq 'allow');
                   3466:             last;
1.342     www      3467:         }
1.402     bowersj2 3468: 	if ($realm eq '' && $role eq '') {
                   3469:             $access=($effect eq 'allow');
                   3470: 	}
1.341     www      3471:     }
                   3472:     return $access;
                   3473: }
                   3474: 
1.103     harris41 3475: # ------------------------------------------------- Check for a user privilege
1.12      www      3476: 
                   3477: sub allowed {
1.579     albertel 3478:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3479:     my $ver_orguri=$uri;
1.439     www      3480:     $uri=&deversion($uri);
1.152     www      3481:     my $orguri=$uri;
1.52      www      3482:     $uri=&declutter($uri);
1.545     banghart 3483:     
1.620     albertel 3484:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3485: # Free bre access to adm and meta resources
1.775     albertel 3486:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3487: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3488: 	&& ($priv eq 'bre')) {
1.14      www      3489: 	return 'F';
1.159     www      3490:     }
                   3491: 
1.545     banghart 3492: # Free bre access to user's own portfolio contents
1.714     raeburn  3493:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3494:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3495: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3496:         return 'F';
                   3497:     }
                   3498: 
1.762     raeburn  3499: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3500:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3501:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3502:         if (exists($env{'request.course.id'})) {
                   3503:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3504:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3505:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3506:                 my $courseprivid=$env{'request.course.id'};
                   3507:                 $courseprivid=~s/\_/\//;
                   3508:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3509:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3510:                     return $1; 
1.762     raeburn  3511:                 } else {
                   3512:                     if ($env{'request.course.sec'}) {
                   3513:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3514:                     }
                   3515:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3516:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3517:                         return $2;
                   3518:                     }
1.714     raeburn  3519:                 }
                   3520:             }
                   3521:         }
                   3522:     }
                   3523: 
1.159     www      3524: # Free bre to public access
                   3525: 
                   3526:     if ($priv eq 'bre') {
1.238     www      3527:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3528: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3529:            return 'F'; 
                   3530:         }
1.238     www      3531:         if ($copyright eq 'priv') {
                   3532:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3533: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3534: 		return '';
                   3535:             }
                   3536:         }
                   3537:         if ($copyright eq 'domain') {
                   3538:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3539: 	    unless (($env{'user.domain'} eq $1) ||
                   3540:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3541: 		return '';
                   3542:             }
1.262     matthew  3543:         }
1.620     albertel 3544:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3545:             # Library role, so allow browsing of resources in this domain.
                   3546:             return 'F';
1.238     www      3547:         }
1.341     www      3548:         if ($copyright eq 'custom') {
                   3549: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3550:         }
1.14      www      3551:     }
1.264     matthew  3552:     # Domain coordinator is trying to create a course
1.620     albertel 3553:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3554:         # uri is the requested domain in this case.
                   3555:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3556:         # a role of dc for the domain in question.
1.620     albertel 3557:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3558:     }
1.29      www      3559: 
1.52      www      3560:     my $thisallowed='';
                   3561:     my $statecond=0;
                   3562:     my $courseprivid='';
                   3563: 
                   3564: # Course
                   3565: 
1.620     albertel 3566:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3567:        $thisallowed.=$1;
                   3568:     }
1.29      www      3569: 
1.52      www      3570: # Domain
                   3571: 
1.620     albertel 3572:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3573:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3574:        $thisallowed.=$1;
                   3575:     }
1.52      www      3576: 
                   3577: # Course: uri itself is a course
1.66      www      3578:     my $courseuri=$uri;
                   3579:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3580:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3581: 
1.620     albertel 3582:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3583:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3584:        $thisallowed.=$1;
                   3585:     }
1.29      www      3586: 
1.665     albertel 3587: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3588: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3589:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3590: 	$thisallowed='';
1.671     raeburn  3591:         my ($match)=&is_on_map($uri);
                   3592:         if ($match) {
                   3593:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3594:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3595:                 $thisallowed.=$1;
                   3596:             }
                   3597:         } else {
1.705     albertel 3598:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3599:             if ($refuri) {
                   3600:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3601:                     $thisallowed='F';
1.671     raeburn  3602:                 } else {
                   3603:                     $refuri=&declutter($refuri);
                   3604:                     my ($match) = &is_on_map($refuri);
                   3605:                     if ($match) {
                   3606:                         $thisallowed='F';
                   3607:                     }
1.669     raeburn  3608:                 }
1.671     raeburn  3609:             }
                   3610:         }
1.314     www      3611:     }
1.492     albertel 3612: 
1.766     albertel 3613:     if ($priv eq 'bre'
                   3614: 	&& $thisallowed ne 'F' 
                   3615: 	&& $thisallowed ne '2'
                   3616: 	&& &is_portfolio_url($uri)) {
                   3617: 	$thisallowed = &portfolio_access($uri);
                   3618:     }
                   3619:     
1.52      www      3620: # Full access at system, domain or course-wide level? Exit.
1.29      www      3621: 
                   3622:     if ($thisallowed=~/F/) {
                   3623: 	return 'F';
                   3624:     }
                   3625: 
1.52      www      3626: # If this is generating or modifying users, exit with special codes
1.29      www      3627: 
1.643     www      3628:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3629: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3630: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3631: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3632: 	    unless ($auname) { return $thisallowed; }
                   3633: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3634: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3635: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3636: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3637: 	}
1.52      www      3638: 	return $thisallowed;
                   3639:     }
                   3640: #
1.103     harris41 3641: # Gathered so far: system, domain and course wide privileges
1.52      www      3642: #
                   3643: # Course: See if uri or referer is an individual resource that is part of 
                   3644: # the course
                   3645: 
1.620     albertel 3646:     if ($env{'request.course.id'}) {
1.232     www      3647: 
1.620     albertel 3648:        $courseprivid=$env{'request.course.id'};
                   3649:        if ($env{'request.course.sec'}) {
                   3650:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3651:        }
                   3652:        $courseprivid=~s/\_/\//;
                   3653:        my $checkreferer=1;
1.232     www      3654:        my ($match,$cond)=&is_on_map($uri);
                   3655:        if ($match) {
                   3656:            $statecond=$cond;
1.620     albertel 3657:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3658:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3659:                $thisallowed.=$1;
                   3660:                $checkreferer=0;
                   3661:            }
1.29      www      3662:        }
1.83      www      3663:        
1.148     www      3664:        if ($checkreferer) {
1.620     albertel 3665: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3666:             unless ($refuri) {
1.620     albertel 3667:                 foreach (keys %env) {
1.148     www      3668: 		    if ($_=~/^httpref\..*\*/) {
                   3669: 			my $pattern=$_;
1.156     www      3670:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3671:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3672:                         $pattern=~s/\//\\\//g;
1.152     www      3673:                         if ($orguri=~/$pattern/) {
1.620     albertel 3674: 			    $refuri=$env{$_};
1.148     www      3675:                         }
                   3676:                     }
1.191     harris41 3677:                 }
1.148     www      3678:             }
1.232     www      3679: 
1.148     www      3680:          if ($refuri) { 
1.152     www      3681: 	  $refuri=&declutter($refuri);
1.232     www      3682:           my ($match,$cond)=&is_on_map($refuri);
                   3683:             if ($match) {
                   3684:               my $refstatecond=$cond;
1.620     albertel 3685:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3686:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3687:                   $thisallowed.=$1;
1.53      www      3688:                   $uri=$refuri;
                   3689:                   $statecond=$refstatecond;
1.52      www      3690:               }
                   3691:           }
1.148     www      3692:         }
1.29      www      3693:        }
1.52      www      3694:    }
1.29      www      3695: 
1.52      www      3696: #
1.103     harris41 3697: # Gathered now: all privileges that could apply, and condition number
1.52      www      3698: # 
                   3699: #
                   3700: # Full or no access?
                   3701: #
1.29      www      3702: 
1.52      www      3703:     if ($thisallowed=~/F/) {
                   3704: 	return 'F';
                   3705:     }
1.29      www      3706: 
1.52      www      3707:     unless ($thisallowed) {
                   3708:         return '';
                   3709:     }
1.29      www      3710: 
1.52      www      3711: # Restrictions exist, deal with them
                   3712: #
                   3713: #   C:according to course preferences
                   3714: #   R:according to resource settings
                   3715: #   L:unless locked
                   3716: #   X:according to user session state
                   3717: #
                   3718: 
                   3719: # Possibly locked functionality, check all courses
1.54      www      3720: # Locks might take effect only after 10 minutes cache expiration for other
                   3721: # courses, and 2 minutes for current course
1.52      www      3722: 
                   3723:     my $envkey;
                   3724:     if ($thisallowed=~/L/) {
1.620     albertel 3725:         foreach $envkey (keys %env) {
1.54      www      3726:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3727:                my $courseid=$2;
                   3728:                my $roleid=$1.'.'.$2;
1.92      www      3729:                $courseid=~s/^\///;
1.54      www      3730:                my $expiretime=600;
1.620     albertel 3731:                if ($env{'request.role'} eq $roleid) {
1.54      www      3732: 		  $expiretime=120;
                   3733:                }
                   3734: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3735:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3736:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3737: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3738:                }
1.620     albertel 3739:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3740:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3741: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3742:                        &log($env{'user.domain'},$env{'user.name'},
                   3743:                             $env{'user.home'},
1.57      www      3744:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3745:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3746:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3747: 		       return '';
                   3748:                    }
                   3749:                }
1.620     albertel 3750:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3751:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3752: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3753:                        &log($env{'user.domain'},$env{'user.name'},
                   3754:                             $env{'user.home'},
1.57      www      3755:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3756:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3757:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3758: 		       return '';
                   3759:                    }
                   3760:                }
                   3761: 	   }
1.29      www      3762:        }
1.52      www      3763:     }
                   3764:    
                   3765: #
                   3766: # Rest of the restrictions depend on selected course
                   3767: #
                   3768: 
1.620     albertel 3769:     unless ($env{'request.course.id'}) {
1.766     albertel 3770: 	if ($thisallowed eq 'A') {
                   3771: 	    return 'A';
                   3772: 	} else {
                   3773: 	    return '1';
                   3774: 	}
1.52      www      3775:     }
1.29      www      3776: 
1.52      www      3777: #
                   3778: # Now user is definitely in a course
                   3779: #
1.53      www      3780: 
                   3781: 
                   3782: # Course preferences
                   3783: 
                   3784:    if ($thisallowed=~/C/) {
1.620     albertel 3785:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3786:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3787:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3788: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3789: 	   if ($priv ne 'pch') { 
                   3790: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3791: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3792: 			$env{'request.course.id'});
                   3793: 	   }
1.237     www      3794:            return '';
                   3795:        }
                   3796: 
1.620     albertel 3797:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3798: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3799: 	   if ($priv ne 'pch') { 
                   3800: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3801: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3802: 			$env{'request.course.id'});
                   3803: 	   }
1.54      www      3804:            return '';
                   3805:        }
1.53      www      3806:    }
                   3807: 
                   3808: # Resource preferences
                   3809: 
                   3810:    if ($thisallowed=~/R/) {
1.620     albertel 3811:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3812:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3813: 	   if ($priv ne 'pch') { 
                   3814: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3815: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3816: 	   }
                   3817: 	   return '';
1.54      www      3818:        }
1.53      www      3819:    }
1.30      www      3820: 
1.246     www      3821: # Restricted by state or randomout?
1.30      www      3822: 
1.52      www      3823:    if ($thisallowed=~/X/) {
1.620     albertel 3824:       if ($env{'acc.randomout'}) {
1.579     albertel 3825: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3826:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3827:             return ''; 
                   3828:          }
1.247     www      3829:       }
                   3830:       if (&condval($statecond)) {
1.52      www      3831: 	 return '2';
                   3832:       } else {
                   3833:          return '';
                   3834:       }
                   3835:    }
1.30      www      3836: 
1.766     albertel 3837:     if ($thisallowed eq 'A') {
                   3838: 	return 'A';
                   3839:     }
1.52      www      3840:    return 'F';
1.232     www      3841: }
                   3842: 
1.710     albertel 3843: sub split_uri_for_cond {
                   3844:     my $uri=&deversion(&declutter(shift));
                   3845:     my @uriparts=split(/\//,$uri);
                   3846:     my $filename=pop(@uriparts);
                   3847:     my $pathname=join('/',@uriparts);
                   3848:     return ($pathname,$filename);
                   3849: }
1.232     www      3850: # --------------------------------------------------- Is a resource on the map?
                   3851: 
                   3852: sub is_on_map {
1.710     albertel 3853:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3854:     #Trying to find the conditional for the file
1.620     albertel 3855:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3856: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3857:     if ($match) {
1.289     bowersj2 3858: 	return (1,$1);
                   3859:     } else {
1.434     www      3860: 	return (0,0);
1.289     bowersj2 3861:     }
1.12      www      3862: }
                   3863: 
1.427     www      3864: # --------------------------------------------------------- Get symb from alias
                   3865: 
                   3866: sub get_symb_from_alias {
                   3867:     my $symb=shift;
                   3868:     my ($map,$resid,$url)=&decode_symb($symb);
                   3869: # Already is a symb
                   3870:     if ($url) { return $symb; }
                   3871: # Must be an alias
                   3872:     my $aliassymb='';
                   3873:     my %bighash;
1.620     albertel 3874:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3875:                             &GDBM_READER(),0640)) {
                   3876:         my $rid=$bighash{'mapalias_'.$symb};
                   3877: 	if ($rid) {
                   3878: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3879: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3880: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3881: 	}
                   3882:         untie %bighash;
                   3883:     }
                   3884:     return $aliassymb;
                   3885: }
                   3886: 
1.12      www      3887: # ----------------------------------------------------------------- Define Role
                   3888: 
                   3889: sub definerole {
                   3890:   if (allowed('mcr','/')) {
                   3891:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3892:     foreach (split(':',$sysrole)) {
1.21      www      3893: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3894:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3895:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3896: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3897:                return "refused:s:$crole&$cqual"; 
                   3898:             }
                   3899:         }
1.191     harris41 3900:     }
1.392     www      3901:     foreach (split(':',$domrole)) {
1.21      www      3902: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3903:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3904:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3905: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3906:                return "refused:d:$crole&$cqual"; 
                   3907:             }
                   3908:         }
1.191     harris41 3909:     }
1.392     www      3910:     foreach (split(':',$courole)) {
1.21      www      3911: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3912:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3913:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3914: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3915:                return "refused:c:$crole&$cqual"; 
                   3916:             }
                   3917:         }
1.191     harris41 3918:     }
1.620     albertel 3919:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3920:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3921: 	        "rolesdef_$rolename=".
                   3922:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3923:     return reply($command,$env{'user.home'});
1.12      www      3924:   } else {
                   3925:     return 'refused';
                   3926:   }
1.105     harris41 3927: }
                   3928: 
                   3929: # ---------------- Make a metadata query against the network of library servers
                   3930: 
                   3931: sub metadata_query {
1.244     matthew  3932:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3933:     my %rhash;
1.244     matthew  3934:     my @server_list = (defined($server_array) ? @$server_array
                   3935:                                               : keys(%libserv) );
                   3936:     for my $server (@server_list) {
1.118     harris41 3937: 	unless ($custom or $customshow) {
                   3938: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3939: 	    $rhash{$server}=$reply;
                   3940: 	}
                   3941: 	else {
                   3942: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3943: 			     &escape($custom).':'.&escape($customshow),
                   3944: 			     $server);
                   3945: 	    $rhash{$server}=$reply;
                   3946: 	}
1.112     harris41 3947:     }
1.118     harris41 3948:     return \%rhash;
1.240     www      3949: }
                   3950: 
                   3951: # ----------------------------------------- Send log queries and wait for reply
                   3952: 
                   3953: sub log_query {
                   3954:     my ($uname,$udom,$query,%filters)=@_;
                   3955:     my $uhome=&homeserver($uname,$udom);
                   3956:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3957:     my $uhost=$hostname{$uhome};
1.241     www      3958:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3959:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3960:                        $uhome);
1.479     albertel 3961:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3962:     return get_query_reply($queryid);
                   3963: }
                   3964: 
1.508     raeburn  3965: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3966: 
                   3967: sub fetch_enrollment_query {
1.511     raeburn  3968:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3969:     my $homeserver;
1.547     raeburn  3970:     my $maxtries = 1;
1.508     raeburn  3971:     if ($context eq 'automated') {
                   3972:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3973:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3974:     } else {
                   3975:         $homeserver = &homeserver($cnum,$dom);
                   3976:     }
1.506     raeburn  3977:     my $host=$hostname{$homeserver};
                   3978:     my $cmd = '';
                   3979:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3980:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3981:     }
                   3982:     $cmd =~ s/%%$//;
                   3983:     $cmd = &escape($cmd);
                   3984:     my $query = 'fetchenrollment';
1.620     albertel 3985:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3986:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3987:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3988:         return 'error: '.$queryid;
                   3989:     }
1.506     raeburn  3990:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3991:     my $tries = 1;
                   3992:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3993:         $reply = &get_query_reply($queryid);
                   3994:         $tries ++;
                   3995:     }
1.526     raeburn  3996:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3997:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3998:     } else {
1.515     raeburn  3999:         my @responses = split/:/,$reply;
                   4000:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   4001:             foreach (@responses) {
                   4002:                 my ($key,$value) = split/=/,$_;
                   4003:                 $$replyref{$key} = $value;
                   4004:             }
                   4005:         } else {
1.506     raeburn  4006:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   4007:             foreach (@responses) {
                   4008:                 my ($key,$value) = split/=/,$_;
                   4009:                 $$replyref{$key} = $value;
                   4010:                 if ($value > 0) {
                   4011:                     foreach (@{$$affiliatesref{$key}}) {
                   4012:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   4013:                         my $destname = $pathname.'/'.$filename;
                   4014:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4015:                         if ($xml_classlist =~ /^error/) {
                   4016:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4017:                         } else {
1.506     raeburn  4018:                             if ( open(FILE,">$destname") ) {
                   4019:                                 print FILE &unescape($xml_classlist);
                   4020:                                 close(FILE);
1.526     raeburn  4021:                             } else {
                   4022:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4023:                             }
                   4024:                         }
                   4025:                     }
                   4026:                 }
                   4027:             }
                   4028:         }
                   4029:         return 'ok';
                   4030:     }
                   4031:     return 'error';
                   4032: }
                   4033: 
1.242     www      4034: sub get_query_reply {
                   4035:     my $queryid=shift;
1.240     www      4036:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4037:     my $reply='';
                   4038:     for (1..100) {
                   4039: 	sleep 2;
                   4040:         if (-e $replyfile.'.end') {
1.448     albertel 4041: 	    if (open(my $fh,$replyfile)) {
1.240     www      4042:                $reply.=<$fh>;
1.448     albertel 4043:                close($fh);
1.240     www      4044: 	   } else { return 'error: reply_file_error'; }
1.242     www      4045:            return &unescape($reply);
                   4046: 	}
1.240     www      4047:     }
1.242     www      4048:     return 'timeout:'.$queryid;
1.240     www      4049: }
                   4050: 
                   4051: sub courselog_query {
1.241     www      4052: #
                   4053: # possible filters:
                   4054: # url: url or symb
                   4055: # username
                   4056: # domain
                   4057: # action: view, submit, grade
                   4058: # start: timestamp
                   4059: # end: timestamp
                   4060: #
1.240     www      4061:     my (%filters)=@_;
1.620     albertel 4062:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4063:     if ($filters{'url'}) {
                   4064: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4065:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4066:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4067:     }
1.620     albertel 4068:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4069:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4070:     return &log_query($cname,$cdom,'courselog',%filters);
                   4071: }
                   4072: 
                   4073: sub userlog_query {
                   4074:     my ($uname,$udom,%filters)=@_;
                   4075:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4076: }
                   4077: 
1.506     raeburn  4078: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4079: 
                   4080: sub auto_run {
1.508     raeburn  4081:     my ($cnum,$cdom) = @_;
                   4082:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4083:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4084:     return $response;
                   4085: }
1.776     albertel 4086: 
1.506     raeburn  4087: sub auto_get_sections {
1.508     raeburn  4088:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4089:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4090:     my @secs = ();
1.511     raeburn  4091:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4092:     unless ($response eq 'refused') {
                   4093:         @secs = split/:/,$response;
                   4094:     }
                   4095:     return @secs;
                   4096: }
1.776     albertel 4097: 
1.506     raeburn  4098: sub auto_new_course {
1.508     raeburn  4099:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4100:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4101:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4102:     return $response;
                   4103: }
1.776     albertel 4104: 
1.506     raeburn  4105: sub auto_validate_courseID {
1.508     raeburn  4106:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4107:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4108:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4109:     return $response;
                   4110: }
1.776     albertel 4111: 
1.506     raeburn  4112: sub auto_create_password {
1.508     raeburn  4113:     my ($cnum,$cdom,$authparam) = @_;
                   4114:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4115:     my $create_passwd = 0;
                   4116:     my $authchk = '';
1.511     raeburn  4117:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4118:     if ($response eq 'refused') {
                   4119:         $authchk = 'refused';
                   4120:     } else {
                   4121:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4122:     }
                   4123:     return ($authparam,$create_passwd,$authchk);
                   4124: }
                   4125: 
1.706     raeburn  4126: sub auto_photo_permission {
                   4127:     my ($cnum,$cdom,$students) = @_;
                   4128:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4129:     my ($outcome,$perm_reqd,$conditions) = 
                   4130: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4131:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4132: 	return (undef,undef);
                   4133:     }
1.706     raeburn  4134:     return ($outcome,$perm_reqd,$conditions);
                   4135: }
                   4136: 
                   4137: sub auto_checkphotos {
                   4138:     my ($uname,$udom,$pid) = @_;
                   4139:     my $homeserver = &homeserver($uname,$udom);
                   4140:     my ($result,$resulttype);
                   4141:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4142: 				   &escape($uname).':'.&escape($pid),
                   4143: 				   $homeserver));
1.709     albertel 4144:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4145: 	return (undef,undef);
                   4146:     }
1.706     raeburn  4147:     if ($outcome) {
                   4148:         ($result,$resulttype) = split(/:/,$outcome);
                   4149:     } 
                   4150:     return ($result,$resulttype);
                   4151: }
                   4152: 
                   4153: sub auto_photochoice {
                   4154:     my ($cnum,$cdom) = @_;
                   4155:     my $homeserver = &homeserver($cnum,$cdom);
                   4156:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4157: 						       &escape($cdom),
                   4158: 						       $homeserver)));
1.709     albertel 4159:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4160: 	return (undef,undef);
                   4161:     }
1.706     raeburn  4162:     return ($update,$comment);
                   4163: }
                   4164: 
                   4165: sub auto_photoupdate {
                   4166:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4167:     my $homeserver = &homeserver($cnum,$dom);
                   4168:     my $host=$hostname{$homeserver};
                   4169:     my $cmd = '';
                   4170:     my $maxtries = 1;
                   4171:     foreach (keys %{$affiliatesref}) {
                   4172:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4173:     }
                   4174:     $cmd =~ s/%%$//;
                   4175:     $cmd = &escape($cmd);
                   4176:     my $query = 'institutionalphotos';
                   4177:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4178:     unless ($queryid=~/^\Q$host\E\_/) {
                   4179:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4180:         return 'error: '.$queryid;
                   4181:     }
                   4182:     my $reply = &get_query_reply($queryid);
                   4183:     my $tries = 1;
                   4184:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4185:         $reply = &get_query_reply($queryid);
                   4186:         $tries ++;
                   4187:     }
                   4188:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4189:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4190:     } else {
                   4191:         my @responses = split(/:/,$reply);
                   4192:         my $outcome = shift(@responses); 
                   4193:         foreach my $item (@responses) {
                   4194:             my ($key,$value) = split(/=/,$item);
                   4195:             $$photo{$key} = $value;
                   4196:         }
                   4197:         return $outcome;
                   4198:     }
                   4199:     return 'error';
                   4200: }
                   4201: 
1.521     raeburn  4202: sub auto_instcode_format {
                   4203:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   4204:     my $courses = '';
1.772     raeburn  4205:     my @homeservers;
1.521     raeburn  4206:     if ($caller eq 'global') {
1.584     raeburn  4207:         foreach my $tryserver (keys %libserv) {
                   4208:             if ($hostdom{$tryserver} eq $codedom) {
1.772     raeburn  4209:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
                   4210:                     push(@homeservers,$tryserver);
                   4211:                 }
1.584     raeburn  4212:             }
                   4213:         }
1.521     raeburn  4214:     } else {
1.772     raeburn  4215:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4216:     }
                   4217:     foreach (keys %{$instcodes}) {
                   4218:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   4219:     }
                   4220:     chop($courses);
1.772     raeburn  4221:     my $ok_response = 0;
                   4222:     my $response;
                   4223:     while (@homeservers > 0 && $ok_response == 0) {
                   4224:         my $server = shift(@homeservers); 
                   4225:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4226:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4227:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
                   4228:                                                             split/:/,$response;
                   4229:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4230:             push(@{$codetitles},&str2array($codetitles_str));
                   4231:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4232:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4233:             $ok_response = 1;
                   4234:         }
                   4235:     }
                   4236:     if ($ok_response) {
1.521     raeburn  4237:         return 'ok';
1.772     raeburn  4238:     } else {
                   4239:         return $response;
1.521     raeburn  4240:     }
                   4241: }
                   4242: 
1.777     albertel 4243: sub auto_validate_class_sec {
1.773     raeburn  4244:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4245:     my $homeserver = &homeserver($cnum,$cdom);
                   4246:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4247:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4248:     return $response;
                   4249: }
                   4250: 
1.679     raeburn  4251: # ------------------------------------------------------- Course Group routines
                   4252: 
                   4253: sub get_coursegroups {
1.683     raeburn  4254:     my ($cdom,$cnum,$group) = @_;
                   4255:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4256: }
                   4257: 
                   4258: sub modify_coursegroup {
                   4259:     my ($cdom,$cnum,$groupsettings) = @_;
                   4260:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4261: }
                   4262: 
                   4263: sub modify_group_roles {
                   4264:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4265:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4266:     my $role = 'gr/'.&escape($userprivs);
                   4267:     my ($uname,$udom) = split(/:/,$user);
                   4268:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4269:     if ($result eq 'ok') {
                   4270:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4271:     }
1.679     raeburn  4272:     return $result;
                   4273: }
                   4274: 
                   4275: sub modify_coursegroup_membership {
                   4276:     my ($cdom,$cnum,$membership) = @_;
                   4277:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4278:     return $result;
                   4279: }
                   4280: 
1.682     raeburn  4281: sub get_active_groups {
                   4282:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4283:     my $now = time;
                   4284:     my %groups = ();
                   4285:     foreach my $key (keys(%env)) {
                   4286:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4287:             my ($start,$end) = split(/\./,$env{$key});
                   4288:             if (($end!=0) && ($end<$now)) { next; }
                   4289:             if (($start!=0) && ($start>$now)) { next; }
                   4290:             if ($1 eq $cdom && $2 eq $cnum) {
                   4291:                 $groups{$3} = $env{$key} ;
                   4292:             }
                   4293:         }
                   4294:     }
                   4295:     return %groups;
                   4296: }
                   4297: 
1.683     raeburn  4298: sub get_group_membership {
                   4299:     my ($cdom,$cnum,$group) = @_;
                   4300:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4301: }
                   4302: 
                   4303: sub get_users_groups {
                   4304:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4305:     my @usersgroups;
1.683     raeburn  4306:     my $cachetime=1800;
                   4307:     $courseid=~s/\_/\//g;
                   4308:     $courseid=~s/^(\w)/\/$1/;
                   4309: 
                   4310:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4311:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4312:     if (defined($cached)) {
1.734     albertel 4313:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4314:     } else {  
                   4315:         $grouplist = '';
                   4316:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4317:         my ($tmp) = keys(%roleshash);
                   4318:         if ($tmp=~/^error:/) {
                   4319:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4320:         } else {
                   4321:             my $access_end = $env{'course.'.$courseid.
                   4322:                                   '.default_enrollment_end_date'};
                   4323:             my $now = time;
1.734     albertel 4324:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4325:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4326:                     my $group = $1;
                   4327:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4328:                         my $start = $2;
                   4329:                         my $end = $1;
                   4330:                         if ($start == -1) { next; } # deleted from group
                   4331:                         if (($start!=0) && ($start>$now)) { next; }
                   4332:                         if (($end!=0) && ($end<$now)) {
                   4333:                             if ($access_end && $access_end < $now) {
                   4334:                                 if ($access_end - $end < 86400) {
                   4335:                                     push(@usersgroups,$group);
                   4336:                                 }
                   4337:                             }
                   4338:                             next;
                   4339:                         }
                   4340:                         push(@usersgroups,$group);
                   4341:                     }
1.683     raeburn  4342:                 }
                   4343:             }
1.733     raeburn  4344:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4345:             $grouplist = join(':',@usersgroups);
                   4346:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4347:         }
                   4348:     }
1.733     raeburn  4349:     return @usersgroups;
1.683     raeburn  4350: }
                   4351: 
                   4352: sub devalidate_getgroups_cache {
                   4353:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4354:     my $courseid = $cdom.'_'.$cnum;
                   4355:     $courseid=~s/\_/\//g;
                   4356:     $courseid=~s/^(\w)/\/$1/;
                   4357:     my $hashid="$udom:$uname:$courseid";
                   4358:     &devalidate_cache_new('getgroups',$hashid);
                   4359: }
                   4360: 
1.12      www      4361: # ------------------------------------------------------------------ Plain Text
                   4362: 
                   4363: sub plaintext {
1.742     raeburn  4364:     my ($short,$type,$cid) = @_;
1.758     albertel 4365:     if ($short =~ /^cr/) {
                   4366: 	return (split('/',$short))[-1];
                   4367:     }
1.742     raeburn  4368:     if (!defined($cid)) {
                   4369:         $cid = $env{'request.course.id'};
                   4370:     }
                   4371:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4372:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4373:                                           '.plaintext'});
                   4374:     }
                   4375:     my %rolenames = (
                   4376:                       Course => 'std',
                   4377:                       Group => 'alt1',
                   4378:                     );
                   4379:     if (defined($type) && 
                   4380:          defined($rolenames{$type}) && 
                   4381:          defined($prp{$short}{$rolenames{$type}})) {
                   4382:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4383:     } else {
                   4384:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4385:     }
1.12      www      4386: }
                   4387: 
                   4388: # ----------------------------------------------------------------- Assign Role
                   4389: 
                   4390: sub assignrole {
1.357     www      4391:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4392:     my $mrole;
                   4393:     if ($role =~ /^cr\//) {
1.393     www      4394:         my $cwosec=$url;
                   4395:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4396: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4397:            &logthis('Refused custom assignrole: '.
                   4398:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4399: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4400:            return 'refused'; 
                   4401:         }
1.21      www      4402:         $mrole='cr';
1.678     raeburn  4403:     } elsif ($role =~ /^gr\//) {
                   4404:         my $cwogrp=$url;
                   4405:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4406:         unless (&allowed('mdg',$cwogrp)) {
                   4407:             &logthis('Refused group assignrole: '.
                   4408:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4409:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4410:             return 'refused';
                   4411:         }
                   4412:         $mrole='gr';
1.21      www      4413:     } else {
1.82      www      4414:         my $cwosec=$url;
1.83      www      4415:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4416:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4417:            &logthis('Refused assignrole: '.
                   4418:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4419: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4420:            return 'refused'; 
                   4421:         }
1.21      www      4422:         $mrole=$role;
                   4423:     }
1.620     albertel 4424:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4425:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4426:     if ($end) { $command.='_'.$end; }
1.21      www      4427:     if ($start) {
                   4428: 	if ($end) { 
1.81      www      4429:            $command.='_'.$start; 
1.21      www      4430:         } else {
1.81      www      4431:            $command.='_0_'.$start;
1.21      www      4432:         }
                   4433:     }
1.739     raeburn  4434:     my $origstart = $start;
                   4435:     my $origend = $end;
1.357     www      4436: # actually delete
                   4437:     if ($deleteflag) {
1.373     www      4438: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4439: # modify command to delete the role
1.620     albertel 4440:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4441:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4442: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4443: # set start and finish to negative values for userrolelog
                   4444:            $start=-1;
                   4445:            $end=-1;
                   4446:         }
                   4447:     }
                   4448: # send command
1.349     www      4449:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4450: # log new user role if status is ok
1.349     www      4451:     if ($answer eq 'ok') {
1.663     raeburn  4452: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4453: # for course roles, perform group memberships changes triggered by role change.
                   4454:         unless ($role =~ /^gr/) {
                   4455:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4456:                                              $origstart);
                   4457:         }
1.349     www      4458:     }
                   4459:     return $answer;
1.169     harris41 4460: }
                   4461: 
                   4462: # -------------------------------------------------- Modify user authentication
1.197     www      4463: # Overrides without validation
                   4464: 
1.169     harris41 4465: sub modifyuserauth {
                   4466:     my ($udom,$uname,$umode,$upass)=@_;
                   4467:     my $uhome=&homeserver($uname,$udom);
1.197     www      4468:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4469:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4470:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4471:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4472:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4473: 		     &escape($upass),$uhome);
1.620     albertel 4474:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4475:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4476:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4477:     &log($udom,,$uname,$uhome,
1.620     albertel 4478:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4479:                                      $env{'user.name'}.', '.$umode.
1.197     www      4480:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4481:     unless ($reply eq 'ok') {
1.197     www      4482:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4483: 	return 'error: '.$reply;
                   4484:     }   
1.170     harris41 4485:     return 'ok';
1.80      www      4486: }
                   4487: 
1.81      www      4488: # --------------------------------------------------------------- Modify a user
1.80      www      4489: 
1.81      www      4490: sub modifyuser {
1.206     matthew  4491:     my ($udom,    $uname, $uid,
                   4492:         $umode,   $upass, $first,
                   4493:         $middle,  $last,  $gene,
1.387     www      4494:         $forceid, $desiredhome, $email)=@_;
1.198     www      4495:     $udom=~s/\W//g;
                   4496:     $uname=~s/\W//g;
1.81      www      4497:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4498:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4499: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4500:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4501:                                      ' desiredhome not specified'). 
1.620     albertel 4502:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4503:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4504:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4505: # ----------------------------------------------------------------- Create User
1.406     albertel 4506:     if (($uhome eq 'no_host') && 
                   4507: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4508:         my $unhome='';
1.209     matthew  4509:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4510:             $unhome = $desiredhome;
1.620     albertel 4511: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4512: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4513:         } else { # load balancing routine for determining $unhome
1.80      www      4514:             my $tryserver;
1.81      www      4515:             my $loadm=10000000;
1.80      www      4516:             foreach $tryserver (keys %libserv) {
                   4517: 	       if ($hostdom{$tryserver} eq $udom) {
                   4518:                   my $answer=reply('load',$tryserver);
                   4519:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4520: 		      $loadm=$answer;
                   4521:                       $unhome=$tryserver;
                   4522:                   }
                   4523: 	       }
                   4524: 	    }
                   4525:         }
                   4526:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4527: 	    return 'error: unable to find a home server for '.$uname.
                   4528:                    ' in domain '.$udom;
1.80      www      4529:         }
                   4530:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4531:                          &escape($upass),$unhome);
                   4532: 	unless ($reply eq 'ok') {
                   4533:             return 'error: '.$reply;
                   4534:         }   
1.230     stredwic 4535:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4536:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4537: 	    return 'error: unable verify users home machine.';
1.80      www      4538:         }
1.209     matthew  4539:     }   # End of creation of new user
1.80      www      4540: # ---------------------------------------------------------------------- Add ID
                   4541:     if ($uid) {
                   4542:        $uid=~tr/A-Z/a-z/;
                   4543:        my %uidhash=&idrget($udom,$uname);
1.196     www      4544:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4545:          && (!$forceid)) {
1.80      www      4546: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4547: 	      return 'error: user id "'.$uid.'" does not match '.
                   4548:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4549:           }
                   4550:        } else {
                   4551: 	  &idput($udom,($uname => $uid));
                   4552:        }
                   4553:     }
                   4554: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4555:     my @tmp=&get('environment',
1.134     albertel 4556: 		   ['firstname','middlename','lastname','generation'],
                   4557: 		   $udom,$uname);
1.313     matthew  4558:     my %names;
                   4559:     if ($tmp[0] =~ m/^error:.*/) { 
                   4560:         %names=(); 
                   4561:     } else {
                   4562:         %names = @tmp;
                   4563:     }
1.388     www      4564: #
                   4565: # Make sure to not trash student environment if instructor does not bother
                   4566: # to supply name and email information
                   4567: #
                   4568:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4569:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4570:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4571:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4572:     if ($email) {
                   4573:        $email=~s/[^\w\@\.\-\,]//gs;
                   4574:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4575: 			   $names{'critnotification'} = $email;
                   4576: 			   $names{'permanentemail'} = $email; }
                   4577:     }
1.134     albertel 4578:     my $reply = &put('environment', \%names, $udom,$uname);
                   4579:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4580:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4581:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4582:              $umode.', '.$first.', '.$middle.', '.
                   4583: 	     $last.', '.$gene.' by '.
1.620     albertel 4584:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4585:     return 'ok';
1.80      www      4586: }
                   4587: 
1.81      www      4588: # -------------------------------------------------------------- Modify student
1.80      www      4589: 
1.81      www      4590: sub modifystudent {
                   4591:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4592:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4593:     if (!$cid) {
1.620     albertel 4594: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4595: 	    return 'not_in_class';
                   4596: 	}
1.80      www      4597:     }
                   4598: # --------------------------------------------------------------- Make the user
1.81      www      4599:     my $reply=&modifyuser
1.209     matthew  4600: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4601:          $desiredhome,$email);
1.80      www      4602:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4603:     # This will cause &modify_student_enrollment to get the uid from the
                   4604:     # students environment
                   4605:     $uid = undef if (!$forceid);
1.455     albertel 4606:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4607: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4608:     return $reply;
                   4609: }
                   4610: 
                   4611: sub modify_student_enrollment {
1.515     raeburn  4612:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4613:     my ($cdom,$cnum,$chome);
                   4614:     if (!$cid) {
1.620     albertel 4615: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4616: 	    return 'not_in_class';
                   4617: 	}
1.620     albertel 4618: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4619: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4620:     } else {
                   4621: 	($cdom,$cnum)=split(/_/,$cid);
                   4622:     }
1.620     albertel 4623:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4624:     if (!$chome) {
1.457     raeburn  4625: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4626:     }
1.455     albertel 4627:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4628:     # Make sure the user exists
1.81      www      4629:     my $uhome=&homeserver($uname,$udom);
                   4630:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4631: 	return 'error: no such user';
                   4632:     }
1.297     matthew  4633:     # Get student data if we were not given enough information
                   4634:     if (!defined($first)  || $first  eq '' || 
                   4635:         !defined($last)   || $last   eq '' || 
                   4636:         !defined($uid)    || $uid    eq '' || 
                   4637:         !defined($middle) || $middle eq '' || 
                   4638:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4639:         # They did not supply us with enough data to enroll the student, so
                   4640:         # we need to pick up more information.
1.297     matthew  4641:         my %tmp = &get('environment',
1.294     matthew  4642:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4643:                        ,$udom,$uname);
                   4644: 
1.455     albertel 4645:         #foreach (keys(%tmp)) {
                   4646:         #    &logthis("key $_ = ".$tmp{$_});
                   4647:         #}
1.294     matthew  4648:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4649:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4650:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4651:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4652:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4653:     }
1.556     albertel 4654:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4655:     my $reply=cput('classlist',
                   4656: 		   {"$uname:$udom" => 
1.515     raeburn  4657: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4658: 		   $cdom,$cnum);
1.81      www      4659:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4660: 	return 'error: '.$reply;
1.652     albertel 4661:     } else {
                   4662: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4663:     }
1.297     matthew  4664:     # Add student role to user
1.83      www      4665:     my $uurl='/'.$cid;
1.81      www      4666:     $uurl=~s/\_/\//g;
                   4667:     if ($usec) {
                   4668: 	$uurl.='/'.$usec;
                   4669:     }
                   4670:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4671: }
                   4672: 
1.556     albertel 4673: sub format_name {
                   4674:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4675:     my $name;
                   4676:     if ($first ne 'lastname') {
                   4677: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4678:     } else {
                   4679: 	if ($lastname=~/\S/) {
                   4680: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4681: 	    $name=~s/\s+,/,/;
                   4682: 	} else {
                   4683: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4684: 	}
                   4685:     }
                   4686:     $name=~s/^\s+//;
                   4687:     $name=~s/\s+$//;
                   4688:     $name=~s/\s+/ /g;
                   4689:     return $name;
                   4690: }
                   4691: 
1.84      www      4692: # ------------------------------------------------- Write to course preferences
                   4693: 
                   4694: sub writecoursepref {
                   4695:     my ($courseid,%prefs)=@_;
                   4696:     $courseid=~s/^\///;
                   4697:     $courseid=~s/\_/\//g;
                   4698:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4699:     my $chome=homeserver($cnum,$cdomain);
                   4700:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4701: 	return 'error: no such course';
                   4702:     }
                   4703:     my $cstring='';
1.191     harris41 4704:     foreach (keys %prefs) {
1.84      www      4705: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4706:     }
1.84      www      4707:     $cstring=~s/\&$//;
                   4708:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4709: }
                   4710: 
                   4711: # ---------------------------------------------------------- Make/modify course
                   4712: 
                   4713: sub createcourse {
1.741     raeburn  4714:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4715:         $course_owner,$crstype)=@_;
1.84      www      4716:     $url=&declutter($url);
                   4717:     my $cid='';
1.264     matthew  4718:     unless (&allowed('ccc',$udom)) {
1.84      www      4719:         return 'refused';
                   4720:     }
                   4721: # ------------------------------------------------------------------- Create ID
1.674     www      4722:    my $uname=int(1+rand(9)).
                   4723:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4724:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4725:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4726: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4727:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4728:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4729:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4730:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4731:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4732:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4733:            return 'error: unable to generate unique course-ID';
                   4734:        } 
                   4735:    }
1.264     matthew  4736: # ------------------------------------------------ Check supplied server name
1.620     albertel 4737:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4738:     if (! exists($libserv{$course_server})) {
                   4739:         return 'error:bad server name '.$course_server;
                   4740:     }
1.84      www      4741: # ------------------------------------------------------------- Make the course
                   4742:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4743:                       $course_server);
1.84      www      4744:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4745:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4746:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4747: 	return 'error: no such course';
                   4748:     }
1.271     www      4749: # ----------------------------------------------------------------- Course made
1.516     raeburn  4750: # log existence
                   4751:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4752:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4753:                   &escape($crstype),$uhome);
1.358     www      4754:     &flushcourselogs();
                   4755: # set toplevel url
1.271     www      4756:     my $topurl=$url;
                   4757:     unless ($nonstandard) {
                   4758: # ------------------------------------------ For standard courses, make top url
                   4759:         my $mapurl=&clutter($url);
1.278     www      4760:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4761:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4762: <map>
                   4763: <resource id="1" type="start"></resource>
                   4764: <resource id="2" src="$mapurl"></resource>
                   4765: <resource id="3" type="finish"></resource>
                   4766: <link index="1" from="1" to="2"></link>
                   4767: <link index="2" from="2" to="3"></link>
                   4768: </map>
                   4769: ENDINITMAP
                   4770:         $topurl=&declutter(
1.638     albertel 4771:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4772:                           );
                   4773:     }
                   4774: # ----------------------------------------------------------- Write preferences
1.84      www      4775:     &writecoursepref($udom.'_'.$uname,
                   4776:                      ('description' => $description,
1.271     www      4777:                       'url'         => $topurl));
1.84      www      4778:     return '/'.$udom.'/'.$uname;
                   4779: }
                   4780: 
1.21      www      4781: # ---------------------------------------------------------- Assign Custom Role
                   4782: 
                   4783: sub assigncustomrole {
1.357     www      4784:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4785:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4786:                        $end,$start,$deleteflag);
1.21      www      4787: }
                   4788: 
                   4789: # ----------------------------------------------------------------- Revoke Role
                   4790: 
                   4791: sub revokerole {
1.357     www      4792:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4793:     my $now=time;
1.357     www      4794:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4795: }
                   4796: 
                   4797: # ---------------------------------------------------------- Revoke Custom Role
                   4798: 
                   4799: sub revokecustomrole {
1.357     www      4800:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4801:     my $now=time;
1.357     www      4802:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4803:            $deleteflag);
1.17      www      4804: }
                   4805: 
1.533     banghart 4806: # ------------------------------------------------------------ Disk usage
1.535     albertel 4807: sub diskusage {
1.533     banghart 4808:     my ($udom,$uname,$directoryRoot)=@_;
                   4809:     $directoryRoot =~ s/\/$//;
1.535     albertel 4810:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4811:     return $listing;
1.512     banghart 4812: }
                   4813: 
1.566     banghart 4814: sub is_locked {
                   4815:     my ($file_name, $domain, $user) = @_;
                   4816:     my @check;
                   4817:     my $is_locked;
                   4818:     push @check, $file_name;
1.613     albertel 4819:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4820: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4821:     my ($tmp)=keys(%locked);
                   4822:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4823:     
1.566     banghart 4824:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4825:         $is_locked = 'false';
                   4826:         foreach my $entry (@{$locked{$file_name}}) {
                   4827:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4828:                $is_locked = 'true';
                   4829:                last;
1.745     raeburn  4830:            }
                   4831:        }
1.566     banghart 4832:     } else {
                   4833:         $is_locked = 'false';
                   4834:     }
                   4835: }
                   4836: 
1.759     albertel 4837: sub declutter_portfile {
                   4838:     my ($file) = @_;
                   4839:     &logthis("got $file");
                   4840:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4841:     &logthis("ret $file");
                   4842:     return $file;
                   4843: }
                   4844: 
1.559     banghart 4845: # ------------------------------------------------------------- Mark as Read Only
                   4846: 
                   4847: sub mark_as_readonly {
                   4848:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4849:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4850:     my ($tmp)=keys(%current_permissions);
                   4851:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4852:     foreach my $file (@{$files}) {
1.759     albertel 4853: 	$file = &declutter_portfile($file);
1.561     banghart 4854:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4855:     }
1.613     albertel 4856:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4857:     return;
                   4858: }
                   4859: 
1.572     banghart 4860: # ------------------------------------------------------------Save Selected Files
                   4861: 
                   4862: sub save_selected_files {
                   4863:     my ($user, $path, @files) = @_;
                   4864:     my $filename = $user."savedfiles";
1.573     banghart 4865:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4866:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4867:     foreach my $file (@files) {
1.620     albertel 4868:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4869:     }
                   4870:     foreach my $file (@other_files) {
1.574     banghart 4871:         print (OUT $file."\n");
1.572     banghart 4872:     }
1.574     banghart 4873:     close (OUT);
1.572     banghart 4874:     return 'ok';
                   4875: }
                   4876: 
1.574     banghart 4877: sub clear_selected_files {
                   4878:     my ($user) = @_;
                   4879:     my $filename = $user."savedfiles";
                   4880:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4881:     print (OUT undef);
                   4882:     close (OUT);
                   4883:     return ("ok");    
                   4884: }
                   4885: 
1.572     banghart 4886: sub files_in_path {
                   4887:     my ($user, $path) = @_;
                   4888:     my $filename = $user."savedfiles";
                   4889:     my %return_files;
1.574     banghart 4890:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4891:     while (my $line_in = <IN>) {
1.574     banghart 4892:         chomp ($line_in);
                   4893:         my @paths_and_file = split (m!/!, $line_in);
                   4894:         my $file_part = pop (@paths_and_file);
                   4895:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4896:         $path_part.='/';
                   4897:         my $path_and_file = $path_part.$file_part;
                   4898:         if ($path_part eq $path) {
                   4899:             $return_files{$file_part}= 'selected';
                   4900:         }
                   4901:     }
1.574     banghart 4902:     close (IN);
                   4903:     return (\%return_files);
1.572     banghart 4904: }
                   4905: 
                   4906: # called in portfolio select mode, to show files selected NOT in current directory
                   4907: sub files_not_in_path {
                   4908:     my ($user, $path) = @_;
                   4909:     my $filename = $user."savedfiles";
                   4910:     my @return_files;
                   4911:     my $path_part;
1.574     banghart 4912:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4913:     while (<IN>) {
                   4914:         #ok, I know it's clunky, but I want it to work
                   4915:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4916:         my $file_part = pop (@paths_and_file);
                   4917:         chomp ($file_part);
                   4918:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4919:         $path_part .= '/';
                   4920:         my $path_and_file = $path_part.$file_part;
                   4921:         if ($path_part ne $path) {
1.574     banghart 4922:             push (@return_files, ($path_and_file));
1.572     banghart 4923:         }
                   4924:     }
1.574     banghart 4925:     close (OUT);
                   4926:     return (@return_files);
1.572     banghart 4927: }
                   4928: 
1.745     raeburn  4929: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4930: 
1.745     raeburn  4931: sub get_portfile_permissions {
                   4932:     my ($domain,$user) = @_;
1.613     albertel 4933:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4934:     my ($tmp)=keys(%current_permissions);
                   4935:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4936:     return \%current_permissions;
                   4937: }
                   4938: 
                   4939: #---------------------------------------------Get portfolio file access controls
                   4940: 
1.749     raeburn  4941: sub get_access_controls {
1.745     raeburn  4942:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4943:     my %access;
                   4944:     my $real_file = $file;
                   4945:     $file =~ s/\.meta$//;
1.745     raeburn  4946:     if (defined($file)) {
1.749     raeburn  4947:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4948:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 4949:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  4950:             }
                   4951:         }
1.745     raeburn  4952:     } else {
1.749     raeburn  4953:         foreach my $key (keys(%{$current_permissions})) {
                   4954:             if ($key =~ /\0accesscontrol$/) {
                   4955:                 if (defined($group)) {
                   4956:                     if ($key !~ m-^\Q$group\E/-) {
                   4957:                         next;
                   4958:                     }
                   4959:                 }
                   4960:                 my ($fullpath) = split(/\0/,$key);
                   4961:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4962:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4963:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4964:                     }
                   4965:                 }
                   4966:             }
                   4967:         }
                   4968:     }
                   4969:     return %access;
                   4970: }
                   4971: 
                   4972: sub modify_access_controls {
                   4973:     my ($file_name,$changes,$domain,$user)=@_;
                   4974:     my ($outcome,$deloutcome);
                   4975:     my %store_permissions;
                   4976:     my %new_values;
                   4977:     my %new_control;
                   4978:     my %translation;
                   4979:     my @deletions = ();
                   4980:     my $now = time;
                   4981:     if (exists($$changes{'activate'})) {
                   4982:         if (ref($$changes{'activate'}) eq 'HASH') {
                   4983:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   4984:             my $numnew = scalar(@newitems);
                   4985:             for (my $i=0; $i<$numnew; $i++) {
                   4986:                 my $newkey = $newitems[$i];
                   4987:                 my $newid = &Apache::loncommon::get_cgi_id();
                   4988:                 $newkey =~ s/^(\d+)/$newid/;
                   4989:                 $translation{$1} = $newid;
                   4990:                 $new_values{$file_name."\0".$newkey} = 
                   4991:                                           $$changes{'activate'}{$newitems[$i]};
                   4992:                 $new_control{$newkey} = $now;
                   4993:             }
                   4994:         }
                   4995:     }
                   4996:     my %todelete;
                   4997:     my %changed_items;
                   4998:     foreach my $action ('delete','update') {
                   4999:         if (exists($$changes{$action})) {
                   5000:             if (ref($$changes{$action}) eq 'HASH') {
                   5001:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5002:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5003:                     if ($action eq 'delete') { 
                   5004:                         $todelete{$itemnum} = 1;
                   5005:                     } else {
                   5006:                         $changed_items{$itemnum} = $key;
                   5007:                     }
                   5008:                 }
1.745     raeburn  5009:             }
                   5010:         }
1.749     raeburn  5011:     }
                   5012:     # get lock on access controls for file.
                   5013:     my $lockhash = {
                   5014:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5015:                                                        ':'.$env{'user.domain'},
                   5016:                    }; 
                   5017:     my $tries = 0;
                   5018:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5019:    
                   5020:     while (($gotlock ne 'ok') && $tries <3) {
                   5021:         $tries ++;
                   5022:         sleep 1;
                   5023:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5024:     }
                   5025:     if ($gotlock eq 'ok') {
                   5026:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5027:         my ($tmp)=keys(%curr_permissions);
                   5028:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5029:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5030:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5031:             if (ref($curr_controls) eq 'HASH') {
                   5032:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5033:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5034:                     if (defined($todelete{$itemnum})) {
                   5035:                         push(@deletions,$file_name."\0".$control_item);
                   5036:                     } else {
                   5037:                         if (defined($changed_items{$itemnum})) {
                   5038:                             $new_control{$changed_items{$itemnum}} = $now;
                   5039:                             push(@deletions,$file_name."\0".$control_item);
                   5040:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5041:                         } else {
                   5042:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5043:                         }
                   5044:                     }
1.745     raeburn  5045:                 }
                   5046:             }
                   5047:         }
1.749     raeburn  5048:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5049:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5050:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5051:         #  remove lock
                   5052:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5053:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5054:     } else {
                   5055:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5056:     }
1.749     raeburn  5057:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5058: }
                   5059: 
                   5060: #------------------------------------------------------Get Marked as Read Only
                   5061: 
                   5062: sub get_marked_as_readonly {
                   5063:     my ($domain,$user,$what,$group) = @_;
                   5064:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5065:     my @readonly_files;
1.629     banghart 5066:     my $cmp1=$what;
                   5067:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5068:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5069:         if (defined($group)) {
                   5070:             if ($file_name !~ m-^\Q$group\E/-) {
                   5071:                 next;
                   5072:             }
                   5073:         }
1.561     banghart 5074:         if (ref($value) eq "ARRAY"){
                   5075:             foreach my $stored_what (@{$value}) {
1.629     banghart 5076:                 my $cmp2=$stored_what;
1.759     albertel 5077:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5078:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5079:                 }
1.629     banghart 5080:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5081:                     push(@readonly_files, $file_name);
1.745     raeburn  5082:                     last;
1.563     banghart 5083:                 } elsif (!defined($what)) {
                   5084:                     push(@readonly_files, $file_name);
1.745     raeburn  5085:                     last;
1.561     banghart 5086:                 }
                   5087:             }
1.745     raeburn  5088:         }
1.561     banghart 5089:     }
                   5090:     return @readonly_files;
                   5091: }
1.577     banghart 5092: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5093: 
1.577     banghart 5094: sub get_marked_as_readonly_hash {
1.745     raeburn  5095:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5096:     my %readonly_files;
1.745     raeburn  5097:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5098:         if (defined($group)) {
                   5099:             if ($file_name !~ m-^\Q$group\E/-) {
                   5100:                 next;
                   5101:             }
                   5102:         }
1.577     banghart 5103:         if (ref($value) eq "ARRAY"){
                   5104:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5105:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5106:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5107:                         if ($lock_descriptor eq 'graded') {
                   5108:                             $readonly_files{$file_name} = 'graded';
                   5109:                         } elsif ($lock_descriptor eq 'handback') {
                   5110:                             $readonly_files{$file_name} = 'handback';
                   5111:                         } else {
                   5112:                             if (!exists($readonly_files{$file_name})) {
                   5113:                                 $readonly_files{$file_name} = 'locked';
                   5114:                             }
                   5115:                         }
1.745     raeburn  5116:                     }
1.750     banghart 5117:                 } 
1.577     banghart 5118:             }
                   5119:         } 
                   5120:     }
                   5121:     return %readonly_files;
                   5122: }
1.559     banghart 5123: # ------------------------------------------------------------ Unmark as Read Only
                   5124: 
                   5125: sub unmark_as_readonly {
1.629     banghart 5126:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5127:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5128:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5129:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5130:     my $symb_crs = $what;
                   5131:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5132:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5133:     my ($tmp)=keys(%current_permissions);
                   5134:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5135:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5136:     foreach my $file (@readonly_files) {
1.759     albertel 5137: 	my $clean_file = &declutter_portfile($file);
                   5138: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5139: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5140:         my @new_locks;
                   5141:         my @del_keys;
                   5142:         if (ref($current_locks) eq "ARRAY"){
                   5143:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5144:                 my $compare=$locker;
1.749     raeburn  5145:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5146:                     $compare=join('',@{$locker});
1.746     raeburn  5147:                     if ($compare ne $symb_crs) {
                   5148:                         push(@new_locks, $locker);
                   5149:                     }
1.563     banghart 5150:                 }
                   5151:             }
1.650     albertel 5152:             if (scalar(@new_locks) > 0) {
1.563     banghart 5153:                 $current_permissions{$file} = \@new_locks;
                   5154:             } else {
                   5155:                 push(@del_keys, $file);
1.613     albertel 5156:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5157:                 delete($current_permissions{$file});
1.563     banghart 5158:             }
                   5159:         }
1.561     banghart 5160:     }
1.613     albertel 5161:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5162:     return;
                   5163: }
1.512     banghart 5164: 
1.17      www      5165: # ------------------------------------------------------------ Directory lister
                   5166: 
                   5167: sub dirlist {
1.253     stredwic 5168:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5169: 
1.18      www      5170:     $uri=~s/^\///;
                   5171:     $uri=~s/\/$//;
1.253     stredwic 5172:     my ($udom, $uname);
                   5173:     (undef,$udom,$uname)=split(/\//,$uri);
                   5174:     if(defined($userdomain)) {
                   5175:         $udom = $userdomain;
                   5176:     }
                   5177:     if(defined($username)) {
                   5178:         $uname = $username;
                   5179:     }
                   5180: 
                   5181:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5182:     if(defined($alternateDirectoryRoot)) {
                   5183:         $dirRoot = $alternateDirectoryRoot;
                   5184:         $dirRoot =~ s/\/$//;
1.751     banghart 5185:     }
1.253     stredwic 5186: 
                   5187:     if($udom) {
                   5188:         if($uname) {
1.605     matthew  5189:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5190:                               homeserver($uname,$udom));
1.605     matthew  5191:             my @listing_results;
                   5192:             if ($listing eq 'unknown_cmd') {
                   5193:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5194:                                homeserver($uname,$udom));
                   5195:                 @listing_results = split(/:/,$listing);
                   5196:             } else {
                   5197:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5198:             }
                   5199:             return @listing_results;
1.253     stredwic 5200:         } elsif(!defined($alternateDirectoryRoot)) {
                   5201:             my $tryserver;
                   5202:             my %allusers=();
                   5203:             foreach $tryserver (keys %libserv) {
                   5204:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5205:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5206:                                       $udom, $tryserver);
1.605     matthew  5207:                     my @listing_results;
                   5208:                     if ($listing eq 'unknown_cmd') {
                   5209:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5210:                                        $udom, $tryserver);
                   5211:                         @listing_results = split(/:/,$listing);
                   5212:                     } else {
                   5213:                         @listing_results =
                   5214:                             map { &unescape($_); } split(/:/,$listing);
                   5215:                     }
                   5216:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5217:                         $listing_results[0] ne 'empty'       &&
                   5218:                         $listing_results[0] ne 'con_lost') {
                   5219:                         foreach (@listing_results) {
1.253     stredwic 5220:                             my ($entry,@stat)=split(/&/,$_);
                   5221:                             $allusers{$entry}=1;
                   5222:                         }
                   5223:                     }
1.191     harris41 5224:                 }
1.253     stredwic 5225:             }
                   5226:             my $alluserstr='';
                   5227:             foreach (sort keys %allusers) {
                   5228:                 $alluserstr.=$_.'&user:';
                   5229:             }
                   5230:             $alluserstr=~s/:$//;
                   5231:             return split(/:/,$alluserstr);
                   5232:         } else {
                   5233:             my @emptyResults = ();
                   5234:             push(@emptyResults, 'missing user name');
                   5235:             return split(':',@emptyResults);
                   5236:         }
                   5237:     } elsif(!defined($alternateDirectoryRoot)) {
                   5238:         my $tryserver;
                   5239:         my %alldom=();
                   5240:         foreach $tryserver (keys %libserv) {
                   5241:             $alldom{$hostdom{$tryserver}}=1;
                   5242:         }
                   5243:         my $alldomstr='';
                   5244:         foreach (sort keys %alldom) {
1.397     albertel 5245:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5246:         }
                   5247:         $alldomstr=~s/:$//;
                   5248:         return split(/:/,$alldomstr);       
                   5249:     } else {
                   5250:         my @emptyResults = ();
                   5251:         push(@emptyResults, 'missing domain');
                   5252:         return split(':',@emptyResults);
1.275     stredwic 5253:     }
                   5254: }
                   5255: 
                   5256: # --------------------------------------------- GetFileTimestamp
                   5257: # This function utilizes dirlist and returns the date stamp for
                   5258: # when it was last modified.  It will also return an error of -1
                   5259: # if an error occurs
                   5260: 
1.410     matthew  5261: ##
                   5262: ## FIXME: This subroutine assumes its caller knows something about the
                   5263: ## directory structure of the home server for the student ($root).
                   5264: ## Not a good assumption to make.  Since this is for looking up files
                   5265: ## in user directories, the full path should be constructed by lond, not
                   5266: ## whatever machine we request data from.
                   5267: ##
1.275     stredwic 5268: sub GetFileTimestamp {
                   5269:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5270:     $studentDomain=~s/\W//g;
                   5271:     $studentName=~s/\W//g;
                   5272:     my $subdir=$studentName.'__';
                   5273:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5274:     my $proname="$studentDomain/$subdir/$studentName";
                   5275:     $proname .= '/'.$filename;
1.375     matthew  5276:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5277:                                               $studentName, $root);
1.275     stredwic 5278:     my @stats = split('&', $fileStat);
                   5279:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5280:         # @stats contains first the filename, then the stat output
                   5281:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5282:     } else {
                   5283:         return -1;
1.253     stredwic 5284:     }
1.26      www      5285: }
                   5286: 
1.712     albertel 5287: sub stat_file {
                   5288:     my ($uri) = @_;
1.787     albertel 5289:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5290: 
1.712     albertel 5291:     my ($udom,$uname,$file,$dir);
                   5292:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5293: 	($udom,$uname,$file) =
                   5294: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5295: 	$file = 'userfiles/'.$file;
1.740     www      5296: 	$dir = &propath($udom,$uname);
1.712     albertel 5297:     }
                   5298:     if ($uri =~ m-^/res/-) {
                   5299: 	($udom,$uname) = 
                   5300: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5301: 	$file = $uri;
                   5302:     }
                   5303: 
                   5304:     if (!$udom || !$uname || !$file) {
                   5305: 	# unable to handle the uri
                   5306: 	return ();
                   5307:     }
                   5308: 
                   5309:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5310:     my @stats = split('&', $result);
1.721     banghart 5311:     
1.712     albertel 5312:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5313: 	shift(@stats); #filename is first
                   5314: 	return @stats;
                   5315:     }
                   5316:     return ();
                   5317: }
                   5318: 
1.26      www      5319: # -------------------------------------------------------- Value of a Condition
                   5320: 
1.713     albertel 5321: # gets the value of a specific preevaluated condition
                   5322: #    stored in the string  $env{user.state.<cid>}
                   5323: # or looks up a condition reference in the bighash and if if hasn't
                   5324: # already been evaluated recurses into docondval to get the value of
                   5325: # the condition, then memoizing it to 
                   5326: #   $env{user.state.<cid>.<condition>}
1.40      www      5327: sub directcondval {
                   5328:     my $number=shift;
1.620     albertel 5329:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5330: 	&Apache::lonuserstate::evalstate();
                   5331:     }
1.713     albertel 5332:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5333: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5334:     } elsif ($number =~ /^_/) {
                   5335: 	my $sub_condition;
                   5336: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5337: 		&GDBM_READER(),0640)) {
                   5338: 	    $sub_condition=$bighash{'conditions'.$number};
                   5339: 	    untie(%bighash);
                   5340: 	}
                   5341: 	my $value = &docondval($sub_condition);
                   5342: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5343: 	return $value;
                   5344:     }
1.620     albertel 5345:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5346:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5347:     } else {
                   5348:        return 2;
                   5349:     }
                   5350: }
                   5351: 
1.713     albertel 5352: # get the collection of conditions for this resource
1.26      www      5353: sub condval {
                   5354:     my $condidx=shift;
1.54      www      5355:     my $allpathcond='';
1.713     albertel 5356:     foreach my $cond (split(/\|/,$condidx)) {
                   5357: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5358: 	    $allpathcond.=
                   5359: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5360: 	}
1.191     harris41 5361:     }
1.54      www      5362:     $allpathcond=~s/\|$//;
1.713     albertel 5363:     return &docondval($allpathcond);
                   5364: }
                   5365: 
                   5366: #evaluates an expression of conditions
                   5367: sub docondval {
                   5368:     my ($allpathcond) = @_;
                   5369:     my $result=0;
                   5370:     if ($env{'request.course.id'}
                   5371: 	&& defined($allpathcond)) {
                   5372: 	my $operand='|';
                   5373: 	my @stack;
                   5374: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5375: 	    if ($chunk eq '(') {
                   5376: 		push @stack,($operand,$result);
                   5377: 	    } elsif ($chunk eq ')') {
                   5378: 		my $before=pop @stack;
                   5379: 		if (pop @stack eq '&') {
                   5380: 		    $result=$result>$before?$before:$result;
                   5381: 		} else {
                   5382: 		    $result=$result>$before?$result:$before;
                   5383: 		}
                   5384: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5385: 		$operand=$chunk;
                   5386: 	    } else {
                   5387: 		my $new=directcondval($chunk);
                   5388: 		if ($operand eq '&') {
                   5389: 		    $result=$result>$new?$new:$result;
                   5390: 		} else {
                   5391: 		    $result=$result>$new?$result:$new;
                   5392: 		}
                   5393: 	    }
                   5394: 	}
1.26      www      5395:     }
                   5396:     return $result;
1.421     albertel 5397: }
                   5398: 
                   5399: # ---------------------------------------------------- Devalidate courseresdata
                   5400: 
                   5401: sub devalidatecourseresdata {
                   5402:     my ($coursenum,$coursedomain)=@_;
                   5403:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5404:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5405: }
                   5406: 
1.763     www      5407: 
1.200     www      5408: # --------------------------------------------------- Course Resourcedata Query
                   5409: 
1.624     albertel 5410: sub get_courseresdata {
                   5411:     my ($coursenum,$coursedomain)=@_;
1.200     www      5412:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5413:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5414:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5415:     my %dumpreply;
1.417     albertel 5416:     unless (defined($cached)) {
1.624     albertel 5417: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5418: 	$result=\%dumpreply;
1.251     albertel 5419: 	my ($tmp) = keys(%dumpreply);
                   5420: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5421: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5422: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5423: 	    return $tmp;
1.416     albertel 5424: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5425: 	    $result=undef;
1.599     albertel 5426: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5427: 	}
                   5428:     }
1.624     albertel 5429:     return $result;
                   5430: }
                   5431: 
1.633     albertel 5432: sub devalidateuserresdata {
                   5433:     my ($uname,$udom)=@_;
                   5434:     my $hashid="$udom:$uname";
                   5435:     &devalidate_cache_new('userres',$hashid);
                   5436: }
                   5437: 
1.624     albertel 5438: sub get_userresdata {
                   5439:     my ($uname,$udom)=@_;
                   5440:     #most student don\'t have any data set, check if there is some data
                   5441:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5442: 
                   5443:     my $hashid="$udom:$uname";
                   5444:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5445:     if (!defined($cached)) {
                   5446: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5447: 	$result=\%resourcedata;
                   5448: 	&do_cache_new('userres',$hashid,$result,600);
                   5449:     }
                   5450:     my ($tmp)=keys(%$result);
                   5451:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5452: 	return $result;
                   5453:     }
                   5454:     #error 2 occurs when the .db doesn't exist
                   5455:     if ($tmp!~/error: 2 /) {
1.672     albertel 5456: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5457: 		 " Trying to get resource data for ".
                   5458: 		 $uname." at ".$udom.": ".
                   5459: 		 $tmp."</font>");
                   5460:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5461: 	#&EXT_cache_set($udom,$uname);
                   5462: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5463: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5464:     }
                   5465:     return $tmp;
                   5466: }
                   5467: 
                   5468: sub resdata {
                   5469:     my ($name,$domain,$type,@which)=@_;
                   5470:     my $result;
                   5471:     if ($type eq 'course') {
                   5472: 	$result=&get_courseresdata($name,$domain);
                   5473:     } elsif ($type eq 'user') {
                   5474: 	$result=&get_userresdata($name,$domain);
                   5475:     }
                   5476:     if (!ref($result)) { return $result; }    
1.251     albertel 5477:     foreach my $item (@which) {
1.417     albertel 5478: 	if (defined($result->{$item})) {
                   5479: 	    return $result->{$item};
1.251     albertel 5480: 	}
1.250     albertel 5481:     }
1.291     albertel 5482:     return undef;
1.200     www      5483: }
                   5484: 
1.379     matthew  5485: #
                   5486: # EXT resource caching routines
                   5487: #
                   5488: 
                   5489: sub clear_EXT_cache_status {
1.383     albertel 5490:     &delenv('cache.EXT.');
1.379     matthew  5491: }
                   5492: 
                   5493: sub EXT_cache_status {
                   5494:     my ($target_domain,$target_user) = @_;
1.383     albertel 5495:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5496:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5497:         # We know already the user has no data
                   5498:         return 1;
                   5499:     } else {
                   5500:         return 0;
                   5501:     }
                   5502: }
                   5503: 
                   5504: sub EXT_cache_set {
                   5505:     my ($target_domain,$target_user) = @_;
1.383     albertel 5506:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5507:     #&appenv($cachename => time);
1.379     matthew  5508: }
                   5509: 
1.28      www      5510: # --------------------------------------------------------- Value of a Variable
1.58      www      5511: sub EXT {
1.715     albertel 5512: 
1.395     albertel 5513:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5514:     unless ($varname) { return ''; }
1.218     albertel 5515:     #get real user name/domain, courseid and symb
                   5516:     my $courseid;
1.359     albertel 5517:     my $publicuser;
1.427     www      5518:     if ($symbparm) {
                   5519: 	$symbparm=&get_symb_from_alias($symbparm);
                   5520:     }
1.218     albertel 5521:     if (!($uname && $udom)) {
1.360     albertel 5522:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5523: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5524:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5525:     } else {
1.620     albertel 5526: 	$courseid=$env{'request.course.id'};
1.218     albertel 5527:     }
1.48      www      5528:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5529:     my $rest;
1.320     albertel 5530:     if (defined($therest[0])) {
1.48      www      5531:        $rest=join('.',@therest);
                   5532:     } else {
                   5533:        $rest='';
                   5534:     }
1.320     albertel 5535: 
1.57      www      5536:     my $qualifierrest=$qualifier;
                   5537:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5538:     my $spacequalifierrest=$space;
                   5539:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5540:     if ($realm eq 'user') {
1.48      www      5541: # --------------------------------------------------------------- user.resource
                   5542: 	if ($space eq 'resource') {
1.651     albertel 5543: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5544: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5545: 		 &&
1.744     albertel 5546: 		 ($symbparm eq &symbread()) ) {	
                   5547: 		# if we are in the middle of processing the resource the
                   5548: 		# get the value we are planning on committing
                   5549:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5550:                     return $Apache::lonhomework::results{$qualifierrest};
                   5551:                 } else {
                   5552:                     return $Apache::lonhomework::history{$qualifierrest};
                   5553:                 }
1.335     albertel 5554: 	    } else {
1.359     albertel 5555: 		my %restored;
1.620     albertel 5556: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5557: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5558: 		} else {
                   5559: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5560: 		}
1.335     albertel 5561: 		return $restored{$qualifierrest};
                   5562: 	    }
1.48      www      5563: # ----------------------------------------------------------------- user.access
                   5564:         } elsif ($space eq 'access') {
1.218     albertel 5565: 	    # FIXME - not supporting calls for a specific user
1.48      www      5566:             return &allowed($qualifier,$rest);
                   5567: # ------------------------------------------ user.preferences, user.environment
                   5568:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5569: 	    if (($uname eq $env{'user.name'}) &&
                   5570: 		($udom eq $env{'user.domain'})) {
                   5571: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5572: 	    } else {
1.359     albertel 5573: 		my %returnhash;
                   5574: 		if (!$publicuser) {
                   5575: 		    %returnhash=&userenvironment($udom,$uname,
                   5576: 						 $qualifierrest);
                   5577: 		}
1.218     albertel 5578: 		return $returnhash{$qualifierrest};
                   5579: 	    }
1.48      www      5580: # ----------------------------------------------------------------- user.course
                   5581:         } elsif ($space eq 'course') {
1.218     albertel 5582: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5583:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5584: # ------------------------------------------------------------------- user.role
                   5585:         } elsif ($space eq 'role') {
1.218     albertel 5586: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5587:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5588:             if ($qualifier eq 'value') {
                   5589: 		return $role;
                   5590:             } elsif ($qualifier eq 'extent') {
                   5591:                 return $where;
                   5592:             }
                   5593: # ----------------------------------------------------------------- user.domain
                   5594:         } elsif ($space eq 'domain') {
1.218     albertel 5595:             return $udom;
1.48      www      5596: # ------------------------------------------------------------------- user.name
                   5597:         } elsif ($space eq 'name') {
1.218     albertel 5598:             return $uname;
1.48      www      5599: # ---------------------------------------------------- Any other user namespace
1.29      www      5600:         } else {
1.359     albertel 5601: 	    my %reply;
                   5602: 	    if (!$publicuser) {
                   5603: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5604: 	    }
                   5605: 	    return $reply{$qualifierrest};
1.48      www      5606:         }
1.236     www      5607:     } elsif ($realm eq 'query') {
                   5608: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5609:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5610: 						[$spacequalifierrest]);
1.620     albertel 5611: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5612:    } elsif ($realm eq 'request') {
1.48      www      5613: # ------------------------------------------------------------- request.browser
                   5614:         if ($space eq 'browser') {
1.430     www      5615: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5616: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5617: 		    return 1;
                   5618: 		} else {
                   5619: 		    return 0;
                   5620: 		}
                   5621: 	    } else {
1.620     albertel 5622: 		return $env{'browser.'.$qualifier};
1.430     www      5623: 	    }
1.57      www      5624: # ------------------------------------------------------------ request.filename
                   5625:         } else {
1.620     albertel 5626:             return $env{'request.'.$spacequalifierrest};
1.29      www      5627:         }
1.28      www      5628:     } elsif ($realm eq 'course') {
1.48      www      5629: # ---------------------------------------------------------- course.description
1.620     albertel 5630:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5631:     } elsif ($realm eq 'resource') {
1.165     www      5632: 
1.620     albertel 5633: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5634: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5635: 	}
1.693     albertel 5636: 
                   5637: 	if ($space eq 'title') {
                   5638: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5639: 	    return &gettitle($symbparm);
                   5640: 	}
                   5641: 	
                   5642: 	if ($space eq 'map') {
                   5643: 	    my ($map) = &decode_symb($symbparm);
                   5644: 	    return &symbread($map);
                   5645: 	}
                   5646: 
                   5647: 	my ($section, $group, @groups);
1.593     albertel 5648: 	my ($courselevelm,$courselevel);
1.539     albertel 5649: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5650: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5651: 
1.218     albertel 5652: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5653: 
1.60      www      5654: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5655: 	    my $symbp=$symbparm;
1.735     albertel 5656: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5657: 
                   5658: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5659: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5660: 
1.620     albertel 5661: 	    if (($env{'user.name'} eq $uname) &&
                   5662: 		($env{'user.domain'} eq $udom)) {
                   5663: 		$section=$env{'request.course.sec'};
1.733     raeburn  5664:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5665:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5666: 	    } else {
1.539     albertel 5667: 		if (! defined($usection)) {
1.551     albertel 5668: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5669: 		} else {
                   5670: 		    $section = $usection;
                   5671: 		}
1.733     raeburn  5672:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5673: 	    }
                   5674: 
                   5675: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5676: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5677: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5678: 
1.593     albertel 5679: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5680: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5681: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5682: 
1.60      www      5683: # ----------------------------------------------------------- first, check user
1.624     albertel 5684: 
                   5685: 	    my $userreply=&resdata($uname,$udom,'user',
                   5686: 				       ($courselevelr,$courselevelm,
                   5687: 					$courselevel));
                   5688: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5689: 
1.594     albertel 5690: # ------------------------------------------------ second, check some of course
1.684     raeburn  5691:             my $coursereply;
1.691     raeburn  5692:             if (@groups > 0) {
                   5693:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5694:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5695:                 if (defined($coursereply)) { return $coursereply; }
                   5696:             }
1.96      www      5697: 
1.684     raeburn  5698: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5699: 				     $env{'course.'.$courseid.'.domain'},
                   5700: 				     'course',
                   5701: 				     ($seclevelr,$seclevelm,$seclevel,
                   5702: 				      $courselevelr));
1.287     albertel 5703: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5704: 
1.60      www      5705: # ------------------------------------------------------ third, check map parms
1.218     albertel 5706: 	    my %parmhash=();
                   5707: 	    my $thisparm='';
                   5708: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5709: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5710: 		    &GDBM_READER(),0640)) {
1.218     albertel 5711: 		$thisparm=$parmhash{$symbparm};
                   5712: 		untie(%parmhash);
                   5713: 	    }
                   5714: 	    if ($thisparm) { return $thisparm; }
                   5715: 	}
1.594     albertel 5716: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5717: 
1.218     albertel 5718: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5719: 	my $filename;
                   5720: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5721: 	if ($symbparm) {
1.409     www      5722: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5723: 	} else {
1.620     albertel 5724: 	    $filename=$env{'request.filename'};
1.282     albertel 5725: 	}
                   5726: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5727: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5728: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5729: 	if (defined($metadata)) { return $metadata; }
1.142     www      5730: 
1.594     albertel 5731: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5732: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5733: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5734: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5735: 				     $env{'course.'.$courseid.'.domain'},
                   5736: 				     'course',
                   5737: 				     ($courselevelm,$courselevel));
1.593     albertel 5738: 	    if (defined($coursereply)) { return $coursereply; }
                   5739: 	}
1.145     www      5740: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5741: 	unless ($space eq '0') {
1.336     albertel 5742: 	    my @parts=split(/_/,$space);
                   5743: 	    my $id=pop(@parts);
                   5744: 	    my $part=join('_',@parts);
                   5745: 	    if ($part eq '') { $part='0'; }
                   5746: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5747: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5748: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5749: 	}
1.395     albertel 5750: 	if ($recurse) { return undef; }
                   5751: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5752: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5753: 
1.48      www      5754: # ---------------------------------------------------- Any other user namespace
                   5755:     } elsif ($realm eq 'environment') {
                   5756: # ----------------------------------------------------------------- environment
1.620     albertel 5757: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5758: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5759: 	} else {
1.770     albertel 5760: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5761: 		return '';
                   5762: 	    }
1.219     albertel 5763: 	    my %returnhash=&userenvironment($udom,$uname,
                   5764: 					    $spacequalifierrest);
                   5765: 	    return $returnhash{$spacequalifierrest};
                   5766: 	}
1.28      www      5767:     } elsif ($realm eq 'system') {
1.48      www      5768: # ----------------------------------------------------------------- system.time
                   5769: 	if ($space eq 'time') {
                   5770: 	    return time;
                   5771:         }
1.696     albertel 5772:     } elsif ($realm eq 'server') {
                   5773: # ----------------------------------------------------------------- system.time
                   5774: 	if ($space eq 'name') {
                   5775: 	    return $ENV{'SERVER_NAME'};
                   5776:         }
1.28      www      5777:     }
1.48      www      5778:     return '';
1.61      www      5779: }
                   5780: 
1.691     raeburn  5781: sub check_group_parms {
                   5782:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5783:     my @groupitems = ();
                   5784:     my $resultitem;
                   5785:     my @levels = ($symbparm,$mapparm,$what);
                   5786:     foreach my $group (@{$groups}) {
                   5787:         foreach my $level (@levels) {
                   5788:              my $item = $courseid.'.['.$group.'].'.$level;
                   5789:              push(@groupitems,$item);
                   5790:         }
                   5791:     }
                   5792:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5793:                             $env{'course.'.$courseid.'.domain'},
                   5794:                                      'course',@groupitems);
                   5795:     return $coursereply;
                   5796: }
                   5797: 
                   5798: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5799:     my ($courseid,@groups) = @_;
                   5800:     @groups = sort(@groups);
1.691     raeburn  5801:     return @groups;
                   5802: }
                   5803: 
1.395     albertel 5804: sub packages_tab_default {
                   5805:     my ($uri,$varname)=@_;
                   5806:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5807: 
                   5808:     my (@extension,@specifics,$do_default);
                   5809:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5810: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5811: 	if ($pack_type eq 'default') {
                   5812: 	    $do_default=1;
                   5813: 	} elsif ($pack_type eq 'extension') {
                   5814: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5815: 	} else {
                   5816: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5817: 	}
                   5818:     }
                   5819:     # first look for a package that matches the requested part id
                   5820:     foreach my $package (@specifics) {
                   5821: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5822: 	next if ($pack_part ne $part);
                   5823: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5824: 	    return $packagetab{"$pack_type&$name&default"};
                   5825: 	}
                   5826:     }
                   5827:     # look for any possible matching non extension_ package
                   5828:     foreach my $package (@specifics) {
                   5829: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5830: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5831: 	    return $packagetab{"$pack_type&$name&default"};
                   5832: 	}
1.585     albertel 5833: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5834: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5835: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5836: 	}
                   5837:     }
1.738     albertel 5838:     # look for any posible extension_ match
                   5839:     foreach my $package (@extension) {
                   5840: 	my ($package,$pack_type)=@{$package};
                   5841: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5842: 	    return $packagetab{"$pack_type&$name&default"};
                   5843: 	}
                   5844: 	if (defined($packagetab{$package."&$name&default"})) {
                   5845: 	    return $packagetab{$package."&$name&default"};
                   5846: 	}
                   5847:     }
                   5848:     # look for a global default setting
                   5849:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5850: 	return $packagetab{"default&$name&default"};
                   5851:     }
1.395     albertel 5852:     return undef;
                   5853: }
                   5854: 
1.334     albertel 5855: sub add_prefix_and_part {
                   5856:     my ($prefix,$part)=@_;
                   5857:     my $keyroot;
                   5858:     if (defined($prefix) && $prefix !~ /^__/) {
                   5859: 	# prefix that has a part already
                   5860: 	$keyroot=$prefix;
                   5861:     } elsif (defined($prefix)) {
                   5862: 	# prefix that is missing a part
                   5863: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5864:     } else {
                   5865: 	# no prefix at all
                   5866: 	if (defined($part)) { $keyroot='_'.$part; }
                   5867:     }
                   5868:     return $keyroot;
                   5869: }
                   5870: 
1.71      www      5871: # ---------------------------------------------------------------- Get metadata
                   5872: 
1.599     albertel 5873: my %metaentry;
1.71      www      5874: sub metadata {
1.176     www      5875:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5876:     $uri=&declutter($uri);
1.288     albertel 5877:     # if it is a non metadata possible uri return quickly
1.529     albertel 5878:     if (($uri eq '') || 
                   5879: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5880: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5881:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5882: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5883: 	return undef;
1.288     albertel 5884:     }
1.73      www      5885:     my $filename=$uri;
                   5886:     $uri=~s/\.meta$//;
1.172     www      5887: #
                   5888: # Is the metadata already cached?
1.177     www      5889: # Look at timestamp of caching
1.172     www      5890: # Everything is cached by the main uri, libraries are never directly cached
                   5891: #
1.428     albertel 5892:     if (!defined($liburi)) {
1.599     albertel 5893: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5894: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5895:     }
                   5896:     {
1.172     www      5897: #
                   5898: # Is this a recursive call for a library?
                   5899: #
1.599     albertel 5900: #	if (! exists($metacache{$uri})) {
                   5901: #	    $metacache{$uri}={};
                   5902: #	}
1.171     www      5903:         if ($liburi) {
                   5904: 	    $liburi=&declutter($liburi);
                   5905:             $filename=$liburi;
1.401     bowersj2 5906:         } else {
1.599     albertel 5907: 	    &devalidate_cache_new('meta',$uri);
                   5908: 	    undef(%metaentry);
1.401     bowersj2 5909: 	}
1.140     www      5910:         my %metathesekeys=();
1.73      www      5911:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5912: 	my $metastring;
1.768     albertel 5913: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5914: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5915: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5916: 	    $metastring=&getfile($file);
1.489     albertel 5917: 	}
1.208     albertel 5918:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5919:         my $token;
1.140     www      5920:         undef %metathesekeys;
1.71      www      5921:         while ($token=$parser->get_token) {
1.339     albertel 5922: 	    if ($token->[0] eq 'S') {
                   5923: 		if (defined($token->[2]->{'package'})) {
1.172     www      5924: #
                   5925: # This is a package - get package info
                   5926: #
1.339     albertel 5927: 		    my $package=$token->[2]->{'package'};
                   5928: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5929: 		    if (defined($token->[2]->{'id'})) { 
                   5930: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5931: 		    }
1.599     albertel 5932: 		    if ($metaentry{':packages'}) {
                   5933: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5934: 		    } else {
1.599     albertel 5935: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5936: 		    }
1.736     albertel 5937: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5938: 			my $part=$keyroot;
                   5939: 			$part=~s/^\_//;
1.736     albertel 5940: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5941: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5942: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5943: 			    # ignore package.tab specified default values
                   5944:                             # here &package_tab_default() will fetch those
                   5945: 			    if ($subp eq 'default') { next; }
1.736     albertel 5946: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5947: 			    my $unikey;
                   5948: 			    if ($pack =~ /_0$/) {
                   5949: 				$unikey='parameter_0_'.$name;
                   5950: 				$part=0;
                   5951: 			    } else {
                   5952: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5953: 			    }
1.339     albertel 5954: 			    if ($subp eq 'display') {
                   5955: 				$value.=' [Part: '.$part.']';
                   5956: 			    }
1.599     albertel 5957: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5958: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5959: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5960: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5961: 			    }
1.599     albertel 5962: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5963: 				$metaentry{':'.$unikey}=
                   5964: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5965: 			    }
1.339     albertel 5966: 			}
                   5967: 		    }
                   5968: 		} else {
1.172     www      5969: #
                   5970: # This is not a package - some other kind of start tag
1.339     albertel 5971: #
                   5972: 		    my $entry=$token->[1];
                   5973: 		    my $unikey;
                   5974: 		    if ($entry eq 'import') {
                   5975: 			$unikey='';
                   5976: 		    } else {
                   5977: 			$unikey=$entry;
                   5978: 		    }
                   5979: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5980: 
                   5981: 		    if (defined($token->[2]->{'id'})) { 
                   5982: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5983: 		    }
1.175     www      5984: 
1.339     albertel 5985: 		    if ($entry eq 'import') {
1.175     www      5986: #
                   5987: # Importing a library here
1.339     albertel 5988: #
                   5989: 			if ($depthcount<20) {
                   5990: 			    my $location=$parser->get_text('/import');
                   5991: 			    my $dir=$filename;
                   5992: 			    $dir=~s|[^/]*$||;
                   5993: 			    $location=&filelocation($dir,$location);
1.736     albertel 5994: 			    my $metadata = 
                   5995: 				&metadata($uri,'keys', $location,$unikey,
                   5996: 					  $depthcount+1);
                   5997: 			    foreach my $meta (split(',',$metadata)) {
                   5998: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   5999: 				$metathesekeys{$meta}=1;
1.339     albertel 6000: 			    }
                   6001: 			}
                   6002: 		    } else { 
                   6003: 			
                   6004: 			if (defined($token->[2]->{'name'})) { 
                   6005: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6006: 			}
                   6007: 			$metathesekeys{$unikey}=1;
1.736     albertel 6008: 			foreach my $param (@{$token->[3]}) {
                   6009: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6010: 				$token->[2]->{$param};
1.339     albertel 6011: 			}
                   6012: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6013: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6014: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6015: 		 # only ws inside the tag, and not in default, so use default
                   6016: 		 # as value
1.599     albertel 6017: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6018: 			} else {
1.321     albertel 6019: 		  # either something interesting inside the tag or default
                   6020:                   # uninteresting
1.599     albertel 6021: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6022: 			}
1.172     www      6023: # end of not-a-package not-a-library import
1.339     albertel 6024: 		    }
1.172     www      6025: # end of not-a-package start tag
1.339     albertel 6026: 		}
1.172     www      6027: # the next is the end of "start tag"
1.339     albertel 6028: 	    }
                   6029: 	}
1.483     albertel 6030: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6031: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6032: 	    #no specific packages #how's our extension
                   6033: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6034: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6035: 					 \%metathesekeys);
                   6036: 	}
1.599     albertel 6037: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6038: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6039: 		#no specific packages well let's get default then
                   6040: 		if ($key!~/^default&/) { next; }
1.488     albertel 6041: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6042: 					     \%metathesekeys);
                   6043: 	    }
                   6044: 	}
1.338     www      6045: # are there custom rights to evaluate
1.599     albertel 6046: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6047: 
1.338     www      6048:     #
                   6049:     # Importing a rights file here
1.339     albertel 6050:     #
                   6051: 	    unless ($depthcount) {
1.599     albertel 6052: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6053: 		my $dir=$filename;
                   6054: 		$dir=~s|[^/]*$||;
                   6055: 		$location=&filelocation($dir,$location);
1.736     albertel 6056: 		my $rights_metadata =
                   6057: 		    &metadata($uri,'keys',$location,'_rights',
                   6058: 			      $depthcount+1);
                   6059: 		foreach my $rights (split(',',$rights_metadata)) {
                   6060: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6061: 		    $metathesekeys{$rights}=1;
1.339     albertel 6062: 		}
                   6063: 	    }
                   6064: 	}
1.737     albertel 6065: 	# uniqifiy package listing
                   6066: 	my %seen;
                   6067: 	my @uniq_packages =
                   6068: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6069: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6070: 
                   6071: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6072: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6073: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6074: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6075: # this is the end of "was not already recently cached
1.71      www      6076:     }
1.599     albertel 6077:     return $metaentry{':'.$what};
1.261     albertel 6078: }
                   6079: 
1.488     albertel 6080: sub metadata_create_package_def {
1.483     albertel 6081:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6082:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6083:     if ($subp eq 'default') { next; }
                   6084:     
1.599     albertel 6085:     if (defined($metaentry{':packages'})) {
                   6086: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6087:     } else {
1.599     albertel 6088: 	$metaentry{':packages'}=$package;
1.483     albertel 6089:     }
                   6090:     my $value=$packagetab{$key};
                   6091:     my $unikey;
                   6092:     $unikey='parameter_0_'.$name;
1.599     albertel 6093:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6094:     $$metathesekeys{$unikey}=1;
1.599     albertel 6095:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6096: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6097:     }
1.599     albertel 6098:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6099: 	$metaentry{':'.$unikey}=
                   6100: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6101:     }
                   6102: }
                   6103: 
1.261     albertel 6104: sub metadata_generate_part0 {
                   6105:     my ($metadata,$metacache,$uri) = @_;
                   6106:     my %allnames;
1.737     albertel 6107:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6108: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6109: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6110: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6111: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6112: 	    $allnames{$name}=$part;
                   6113: 	  }
                   6114: 	}
                   6115:     }
                   6116:     foreach my $name (keys(%allnames)) {
                   6117:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6118:       my $key=":parameter_0_$name";
1.261     albertel 6119:       $$metacache{"$key.part"}='0';
                   6120:       $$metacache{"$key.name"}=$name;
1.428     albertel 6121:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6122: 					   $allnames{$name}.'_'.$name.
                   6123: 					   '.type'};
1.428     albertel 6124:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6125: 			     '.display'};
1.644     www      6126:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6127:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6128:       $$metacache{"$key.display"}=$olddis;
                   6129:     }
1.71      www      6130: }
                   6131: 
1.764     albertel 6132: # ------------------------------------------------------ Devalidate title cache
                   6133: 
                   6134: sub devalidate_title_cache {
                   6135:     my ($url)=@_;
                   6136:     if (!$env{'request.course.id'}) { return; }
                   6137:     my $symb=&symbread($url);
                   6138:     if (!$symb) { return; }
                   6139:     my $key=$env{'request.course.id'}."\0".$symb;
                   6140:     &devalidate_cache_new('title',$key);
                   6141: }
                   6142: 
1.301     www      6143: # ------------------------------------------------- Get the title of a resource
                   6144: 
                   6145: sub gettitle {
                   6146:     my $urlsymb=shift;
                   6147:     my $symb=&symbread($urlsymb);
1.534     albertel 6148:     if ($symb) {
1.620     albertel 6149: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6150: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6151: 	if (defined($cached)) { 
                   6152: 	    return $result;
                   6153: 	}
1.534     albertel 6154: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6155: 	my $title='';
                   6156: 	my %bighash;
1.620     albertel 6157: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6158: 		&GDBM_READER(),0640)) {
                   6159: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6160: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6161: 	    untie %bighash;
                   6162: 	}
                   6163: 	$title=~s/\&colon\;/\:/gs;
                   6164: 	if ($title) {
1.599     albertel 6165: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6166: 	}
                   6167: 	$urlsymb=$url;
                   6168:     }
                   6169:     my $title=&metadata($urlsymb,'title');
                   6170:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6171:     return $title;
1.301     www      6172: }
1.613     albertel 6173: 
1.614     albertel 6174: sub get_slot {
                   6175:     my ($which,$cnum,$cdom)=@_;
                   6176:     if (!$cnum || !$cdom) {
                   6177: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 6178: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6179: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6180:     }
1.703     albertel 6181:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6182:     my %slotinfo;
                   6183:     if (exists($remembered{$key})) {
                   6184: 	$slotinfo{$which} = $remembered{$key};
                   6185:     } else {
                   6186: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6187: 	&Apache::lonhomework::showhash(%slotinfo);
                   6188: 	my ($tmp)=keys(%slotinfo);
                   6189: 	if ($tmp=~/^error:/) { return (); }
                   6190: 	$remembered{$key} = $slotinfo{$which};
                   6191:     }
1.616     albertel 6192:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6193: 	return %{$slotinfo{$which}};
                   6194:     }
                   6195:     return $slotinfo{$which};
1.614     albertel 6196: }
1.31      www      6197: # ------------------------------------------------- Update symbolic store links
                   6198: 
                   6199: sub symblist {
                   6200:     my ($mapname,%newhash)=@_;
1.438     www      6201:     $mapname=&deversion(&declutter($mapname));
1.31      www      6202:     my %hash;
1.620     albertel 6203:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6204:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6205:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6206: 	    foreach my $url (keys %newhash) {
                   6207: 		next if ($url eq 'last_known'
                   6208: 			 && $env{'form.no_update_last_known'});
                   6209: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6210: 						    $newhash{$url}->[1],
                   6211: 						    $newhash{$url}->[0]);
1.191     harris41 6212:             }
1.31      www      6213:             if (untie(%hash)) {
                   6214: 		return 'ok';
                   6215:             }
                   6216:         }
                   6217:     }
                   6218:     return 'error';
1.212     www      6219: }
                   6220: 
                   6221: # --------------------------------------------------------------- Verify a symb
                   6222: 
                   6223: sub symbverify {
1.510     www      6224:     my ($symb,$thisurl)=@_;
                   6225:     my $thisfn=$thisurl;
1.439     www      6226:     $thisfn=&declutter($thisfn);
1.215     www      6227: # direct jump to resource in page or to a sequence - will construct own symbs
                   6228:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6229: # check URL part
1.409     www      6230:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6231: 
1.431     www      6232:     unless ($url eq $thisfn) { return 0; }
1.213     www      6233: 
1.216     www      6234:     $symb=&symbclean($symb);
1.510     www      6235:     $thisurl=&deversion($thisurl);
1.439     www      6236:     $thisfn=&deversion($thisfn);
1.213     www      6237: 
                   6238:     my %bighash;
                   6239:     my $okay=0;
1.431     www      6240: 
1.620     albertel 6241:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6242:                             &GDBM_READER(),0640)) {
1.510     www      6243:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6244:         unless ($ids) { 
1.510     www      6245:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6246:         }
                   6247:         if ($ids) {
                   6248: # ------------------------------------------------------------------- Has ID(s)
                   6249: 	    foreach (split(/\,/,$ids)) {
1.644     www      6250: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6251:                if (
                   6252:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6253:    eq $symb) { 
1.620     albertel 6254: 		   if (($env{'request.role.adv'}) ||
                   6255: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6256: 		       $okay=1; 
                   6257: 		   }
                   6258: 	       }
1.216     www      6259: 	   }
                   6260:         }
1.213     www      6261: 	untie(%bighash);
                   6262:     }
                   6263:     return $okay;
1.31      www      6264: }
                   6265: 
1.210     www      6266: # --------------------------------------------------------------- Clean-up symb
                   6267: 
                   6268: sub symbclean {
                   6269:     my $symb=shift;
1.568     albertel 6270:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6271: # remove version from map
                   6272:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6273: 
1.210     www      6274: # remove version from URL
                   6275:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6276: 
1.507     www      6277: # remove wrapper
                   6278: 
1.510     www      6279:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6280:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6281:     return $symb;
1.409     www      6282: }
                   6283: 
                   6284: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6285: 
                   6286: sub encode_symb {
                   6287:     my ($map,$resid,$url)=@_;
                   6288:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6289: }
1.409     www      6290: 
                   6291: sub decode_symb {
1.568     albertel 6292:     my $symb=shift;
                   6293:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6294:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6295:     return (&fixversion($map),$resid,&fixversion($url));
                   6296: }
                   6297: 
                   6298: sub fixversion {
                   6299:     my $fn=shift;
1.609     banghart 6300:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6301:     my %bighash;
                   6302:     my $uri=&clutter($fn);
1.620     albertel 6303:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6304: # is this cached?
1.599     albertel 6305:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6306:     if (defined($cached)) { return $result; }
                   6307: # unfortunately not cached, or expired
1.620     albertel 6308:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6309: 	    &GDBM_READER(),0640)) {
                   6310:  	if ($bighash{'version_'.$uri}) {
                   6311:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6312:  	    unless (($version eq 'mostrecent') || 
                   6313: 		    ($version==&getversion($uri))) {
1.440     www      6314:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6315:  	    }
                   6316:  	}
                   6317:  	untie %bighash;
1.413     www      6318:     }
1.599     albertel 6319:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6320: }
                   6321: 
                   6322: sub deversion {
                   6323:     my $url=shift;
                   6324:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6325:     return $url;
1.210     www      6326: }
                   6327: 
1.31      www      6328: # ------------------------------------------------------ Return symb list entry
                   6329: 
                   6330: sub symbread {
1.249     www      6331:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6332:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6333:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6334: # no filename provided? try from environment
1.44      www      6335:     unless ($thisfn) {
1.620     albertel 6336:         if ($env{'request.symb'}) {
                   6337: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6338: 	}
1.620     albertel 6339: 	$thisfn=$env{'request.filename'};
1.44      www      6340:     }
1.569     albertel 6341:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6342: # is that filename actually a symb? Verify, clean, and return
                   6343:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6344: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6345: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6346: 	}
1.242     www      6347:     }
1.44      www      6348:     $thisfn=declutter($thisfn);
1.31      www      6349:     my %hash;
1.37      www      6350:     my %bighash;
                   6351:     my $syval='';
1.620     albertel 6352:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6353:         my $targetfn = $thisfn;
1.609     banghart 6354:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6355:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6356:         }
1.687     albertel 6357: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6358: 	    $targetfn=$1;
                   6359: 	}
1.620     albertel 6360:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6361:                       &GDBM_READER(),0640)) {
1.481     raeburn  6362: 	    $syval=$hash{$targetfn};
1.37      www      6363:             untie(%hash);
                   6364:         }
                   6365: # ---------------------------------------------------------- There was an entry
                   6366:         if ($syval) {
1.601     albertel 6367: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6368: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6369: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6370: 		    #return $env{$cache_str}='';
1.601     albertel 6371: 		#}    
                   6372: 		#$syval.=$1;
                   6373: 	    #}
1.37      www      6374:         } else {
                   6375: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6376:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6377:                             &GDBM_READER(),0640)) {
1.37      www      6378: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6379:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6380:               unless ($ids) { 
                   6381:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6382:               }
                   6383:               unless ($ids) {
                   6384: # alias?
                   6385: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6386:               }
1.37      www      6387:               if ($ids) {
                   6388: # ------------------------------------------------------------------- Has ID(s)
                   6389:                  my @possibilities=split(/\,/,$ids);
1.39      www      6390:                  if ($#possibilities==0) {
                   6391: # ----------------------------------------------- There is only one possibility
1.37      www      6392: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6393: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6394: 						    $resid,$thisfn);
1.249     www      6395:                  } elsif (!$donotrecurse) {
1.39      www      6396: # ------------------------------------------ There is more than one possibility
                   6397:                      my $realpossible=0;
1.191     harris41 6398:                      foreach (@possibilities) {
1.39      www      6399: 			 my $file=$bighash{'src_'.$_};
                   6400:                          if (&allowed('bre',$file)) {
                   6401:          		    my ($mapid,$resid)=split(/\./,$_);
                   6402:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6403: 				$realpossible++;
1.626     albertel 6404:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6405: 						    $resid,$thisfn);
1.39      www      6406:                             }
                   6407: 			 }
1.191     harris41 6408:                      }
1.39      www      6409: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6410:                  } else {
                   6411:                      $syval='';
1.37      www      6412:                  }
                   6413: 	      }
                   6414:               untie(%bighash)
1.481     raeburn  6415:            }
1.31      www      6416:         }
1.62      www      6417:         if ($syval) {
1.620     albertel 6418: 	    return $env{$cache_str}=$syval;
1.62      www      6419:         }
1.31      www      6420:     }
1.44      www      6421:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6422:     return $env{$cache_str}='';
1.31      www      6423: }
                   6424: 
                   6425: # ---------------------------------------------------------- Return random seed
                   6426: 
1.32      www      6427: sub numval {
                   6428:     my $txt=shift;
                   6429:     $txt=~tr/A-J/0-9/;
                   6430:     $txt=~tr/a-j/0-9/;
                   6431:     $txt=~tr/K-T/0-9/;
                   6432:     $txt=~tr/k-t/0-9/;
                   6433:     $txt=~tr/U-Z/0-5/;
                   6434:     $txt=~tr/u-z/0-5/;
                   6435:     $txt=~s/\D//g;
1.564     albertel 6436:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6437:     return int($txt);
1.368     albertel 6438: }
                   6439: 
1.484     albertel 6440: sub numval2 {
                   6441:     my $txt=shift;
                   6442:     $txt=~tr/A-J/0-9/;
                   6443:     $txt=~tr/a-j/0-9/;
                   6444:     $txt=~tr/K-T/0-9/;
                   6445:     $txt=~tr/k-t/0-9/;
                   6446:     $txt=~tr/U-Z/0-5/;
                   6447:     $txt=~tr/u-z/0-5/;
                   6448:     $txt=~s/\D//g;
                   6449:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6450:     my $total;
                   6451:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6452:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6453:     return int($total);
                   6454: }
                   6455: 
1.575     albertel 6456: sub numval3 {
                   6457:     use integer;
                   6458:     my $txt=shift;
                   6459:     $txt=~tr/A-J/0-9/;
                   6460:     $txt=~tr/a-j/0-9/;
                   6461:     $txt=~tr/K-T/0-9/;
                   6462:     $txt=~tr/k-t/0-9/;
                   6463:     $txt=~tr/U-Z/0-5/;
                   6464:     $txt=~tr/u-z/0-5/;
                   6465:     $txt=~s/\D//g;
                   6466:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6467:     my $total;
                   6468:     foreach my $val (@txts) { $total+=$val; }
                   6469:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6470:     return $total;
                   6471: }
                   6472: 
1.675     albertel 6473: sub digest {
                   6474:     my ($data)=@_;
                   6475:     my $digest=&Digest::MD5::md5($data);
                   6476:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6477:     my ($e,$f);
                   6478:     {
                   6479:         use integer;
                   6480:         $e=($a+$b);
                   6481:         $f=($c+$d);
                   6482:         if ($_64bit) {
                   6483:             $e=(($e<<32)>>32);
                   6484:             $f=(($f<<32)>>32);
                   6485:         }
                   6486:     }
                   6487:     if (wantarray) {
                   6488: 	return ($e,$f);
                   6489:     } else {
                   6490: 	my $g;
                   6491: 	{
                   6492: 	    use integer;
                   6493: 	    $g=($e+$f);
                   6494: 	    if ($_64bit) {
                   6495: 		$g=(($g<<32)>>32);
                   6496: 	    }
                   6497: 	}
                   6498: 	return $g;
                   6499:     }
                   6500: }
                   6501: 
1.368     albertel 6502: sub latest_rnd_algorithm_id {
1.675     albertel 6503:     return '64bit5';
1.366     albertel 6504: }
1.32      www      6505: 
1.503     albertel 6506: sub get_rand_alg {
                   6507:     my ($courseid)=@_;
                   6508:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6509:     if ($courseid) {
1.620     albertel 6510: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6511:     }
                   6512:     return &latest_rnd_algorithm_id();
                   6513: }
                   6514: 
1.562     albertel 6515: sub validCODE {
                   6516:     my ($CODE)=@_;
                   6517:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6518:     return 0;
                   6519: }
                   6520: 
1.491     albertel 6521: sub getCODE {
1.620     albertel 6522:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6523:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6524: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6525: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6526: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6527:     }
                   6528:     return undef;
                   6529: }
                   6530: 
1.31      www      6531: sub rndseed {
1.155     albertel 6532:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6533: 
                   6534:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6535:     if (!$symb) {
1.366     albertel 6536: 	unless ($symb=$wsymb) { return time; }
                   6537:     }
                   6538:     if (!$courseid) { $courseid=$wcourseid; }
                   6539:     if (!$domain) { $domain=$wdomain; }
                   6540:     if (!$username) { $username=$wusername }
1.503     albertel 6541:     my $which=&get_rand_alg();
1.491     albertel 6542:     if (defined(&getCODE())) {
1.675     albertel 6543: 	if ($which eq '64bit5') {
                   6544: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6545: 	} elsif ($which eq '64bit4') {
1.575     albertel 6546: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6547: 	} else {
                   6548: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6549: 	}
1.675     albertel 6550:     } elsif ($which eq '64bit5') {
                   6551: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6552:     } elsif ($which eq '64bit4') {
                   6553: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6554:     } elsif ($which eq '64bit3') {
                   6555: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6556:     } elsif ($which eq '64bit2') {
                   6557: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6558:     } elsif ($which eq '64bit') {
                   6559: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6560:     }
                   6561:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6562: }
                   6563: 
                   6564: sub rndseed_32bit {
                   6565:     my ($symb,$courseid,$domain,$username)=@_;
                   6566:     {
                   6567: 	use integer;
                   6568: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6569: 	my $symbseed=numval($symb) << 22;
                   6570: 	my $namechck=unpack("%32C*",$username) << 17;
                   6571: 	my $nameseed=numval($username) << 12;
                   6572: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6573: 	my $courseseed=unpack("%32C*",$courseid);
                   6574: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6575: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6576: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6577: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6578: 	return $num;
                   6579:     }
                   6580: }
                   6581: 
                   6582: sub rndseed_64bit {
                   6583:     my ($symb,$courseid,$domain,$username)=@_;
                   6584:     {
                   6585: 	use integer;
                   6586: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6587: 	my $symbseed=numval($symb) << 10;
                   6588: 	my $namechck=unpack("%32S*",$username);
                   6589: 	
                   6590: 	my $nameseed=numval($username) << 21;
                   6591: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6592: 	my $courseseed=unpack("%32S*",$courseid);
                   6593: 	
                   6594: 	my $num1=$symbchck+$symbseed+$namechck;
                   6595: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6596: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6597: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6598: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6599: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6600: 	return "$num1,$num2";
1.155     albertel 6601:     }
1.366     albertel 6602: }
                   6603: 
1.443     albertel 6604: sub rndseed_64bit2 {
                   6605:     my ($symb,$courseid,$domain,$username)=@_;
                   6606:     {
                   6607: 	use integer;
                   6608: 	# strings need to be an even # of cahracters long, it it is odd the
                   6609:         # last characters gets thrown away
                   6610: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6611: 	my $symbseed=numval($symb) << 10;
                   6612: 	my $namechck=unpack("%32S*",$username.' ');
                   6613: 	
                   6614: 	my $nameseed=numval($username) << 21;
1.501     albertel 6615: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6616: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6617: 	
                   6618: 	my $num1=$symbchck+$symbseed+$namechck;
                   6619: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6620: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6621: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6622: 	return "$num1,$num2";
                   6623:     }
                   6624: }
                   6625: 
                   6626: sub rndseed_64bit3 {
                   6627:     my ($symb,$courseid,$domain,$username)=@_;
                   6628:     {
                   6629: 	use integer;
                   6630: 	# strings need to be an even # of cahracters long, it it is odd the
                   6631:         # last characters gets thrown away
                   6632: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6633: 	my $symbseed=numval2($symb) << 10;
                   6634: 	my $namechck=unpack("%32S*",$username.' ');
                   6635: 	
                   6636: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6637: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6638: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6639: 	
                   6640: 	my $num1=$symbchck+$symbseed+$namechck;
                   6641: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6642: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6643: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6644: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6645: 	
1.503     albertel 6646: 	return "$num1:$num2";
1.443     albertel 6647:     }
                   6648: }
                   6649: 
1.575     albertel 6650: sub rndseed_64bit4 {
                   6651:     my ($symb,$courseid,$domain,$username)=@_;
                   6652:     {
                   6653: 	use integer;
                   6654: 	# strings need to be an even # of cahracters long, it it is odd the
                   6655:         # last characters gets thrown away
                   6656: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6657: 	my $symbseed=numval3($symb) << 10;
                   6658: 	my $namechck=unpack("%32S*",$username.' ');
                   6659: 	
                   6660: 	my $nameseed=numval3($username) << 21;
                   6661: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6662: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6663: 	
                   6664: 	my $num1=$symbchck+$symbseed+$namechck;
                   6665: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6666: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6667: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6668: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6669: 	
                   6670: 	return "$num1:$num2";
                   6671:     }
                   6672: }
                   6673: 
1.675     albertel 6674: sub rndseed_64bit5 {
                   6675:     my ($symb,$courseid,$domain,$username)=@_;
                   6676:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6677:     return "$num1:$num2";
                   6678: }
                   6679: 
1.366     albertel 6680: sub rndseed_CODE_64bit {
                   6681:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6682:     {
1.366     albertel 6683: 	use integer;
1.443     albertel 6684: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6685: 	my $symbseed=numval2($symb);
1.491     albertel 6686: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6687: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6688: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6689: 	my $num1=$symbseed+$CODEchck;
                   6690: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6691: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6692: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6693: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6694: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6695: 	return "$num1:$num2";
1.366     albertel 6696:     }
                   6697: }
                   6698: 
1.575     albertel 6699: sub rndseed_CODE_64bit4 {
                   6700:     my ($symb,$courseid,$domain,$username)=@_;
                   6701:     {
                   6702: 	use integer;
                   6703: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6704: 	my $symbseed=numval3($symb);
                   6705: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6706: 	my $CODEseed=numval3(&getCODE());
                   6707: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6708: 	my $num1=$symbseed+$CODEchck;
                   6709: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6710: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6711: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6712: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6713: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6714: 	return "$num1:$num2";
                   6715:     }
                   6716: }
                   6717: 
1.675     albertel 6718: sub rndseed_CODE_64bit5 {
                   6719:     my ($symb,$courseid,$domain,$username)=@_;
                   6720:     my $code = &getCODE();
                   6721:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6722:     return "$num1:$num2";
                   6723: }
                   6724: 
1.366     albertel 6725: sub setup_random_from_rndseed {
                   6726:     my ($rndseed)=@_;
1.503     albertel 6727:     if ($rndseed =~/([,:])/) {
                   6728: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6729: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6730:     } else {
                   6731: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6732:     }
1.36      albertel 6733: }
                   6734: 
1.474     albertel 6735: sub latest_receipt_algorithm_id {
                   6736:     return 'receipt2';
                   6737: }
                   6738: 
1.480     www      6739: sub recunique {
                   6740:     my $fucourseid=shift;
                   6741:     my $unique;
1.620     albertel 6742:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6743: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6744:     } else {
                   6745: 	$unique=$perlvar{'lonReceipt'};
                   6746:     }
                   6747:     return unpack("%32C*",$unique);
                   6748: }
                   6749: 
                   6750: sub recprefix {
                   6751:     my $fucourseid=shift;
                   6752:     my $prefix;
1.620     albertel 6753:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6754: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6755:     } else {
                   6756: 	$prefix=$perlvar{'lonHostID'};
                   6757:     }
                   6758:     return unpack("%32C*",$prefix);
                   6759: }
                   6760: 
1.76      www      6761: sub ireceipt {
1.474     albertel 6762:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6763:     my $cuname=unpack("%32C*",$funame);
                   6764:     my $cudom=unpack("%32C*",$fudom);
                   6765:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6766:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6767:     my $cunique=&recunique($fucourseid);
1.474     albertel 6768:     my $cpart=unpack("%32S*",$part);
1.480     www      6769:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6770:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6771: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6772: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6773: 			       " and ".($cpart%$cudom));
                   6774: 			       
                   6775: 	$return.= ($cunique%$cuname+
                   6776: 		   $cunique%$cudom+
                   6777: 		   $cusymb%$cuname+
                   6778: 		   $cusymb%$cudom+
                   6779: 		   $cucourseid%$cuname+
                   6780: 		   $cucourseid%$cudom+
                   6781: 		   $cpart%$cuname+
                   6782: 		   $cpart%$cudom);
                   6783:     } else {
                   6784: 	$return.= ($cunique%$cuname+
                   6785: 		   $cunique%$cudom+
                   6786: 		   $cusymb%$cuname+
                   6787: 		   $cusymb%$cudom+
                   6788: 		   $cucourseid%$cuname+
                   6789: 		   $cucourseid%$cudom);
                   6790:     }
                   6791:     return $return;
1.76      www      6792: }
                   6793: 
                   6794: sub receipt {
1.474     albertel 6795:     my ($part)=@_;
                   6796:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6797:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6798: }
1.260     ng       6799: 
1.36      albertel 6800: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6801: # returns either the contents of the file or 
                   6802: # -1 if the file doesn't exist
1.481     raeburn  6803: #
                   6804: # if the target is a file that was uploaded via DOCS, 
                   6805: # a check will be made to see if a current copy exists on the local server,
                   6806: # if it does this will be served, otherwise a copy will be retrieved from
                   6807: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6808: # the local server.   
1.472     albertel 6809: 
1.36      albertel 6810: sub getfile {
1.538     albertel 6811:     my ($file) = @_;
1.609     banghart 6812:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6813:     &repcopy($file);
                   6814:     return &readfile($file);
                   6815: }
                   6816: 
                   6817: sub repcopy_userfile {
                   6818:     my ($file)=@_;
1.609     banghart 6819:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6820:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6821:     my ($cdom,$cnum,$filename) = 
                   6822: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6823:     my ($info,$rtncode);
                   6824:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6825:     if (-e "$file") {
                   6826: 	my @fileinfo = stat($file);
                   6827: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6828: 	if ($lwpresp ne 'ok') {
                   6829: 	    if ($rtncode eq '404') {
1.538     albertel 6830: 		unlink($file);
1.482     albertel 6831: 	    }
1.517     albertel 6832: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6833: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6834: 	    #my $response=$ua->request($request);
                   6835: 	    #if ($response->is_success()) {
                   6836: 	#	return $response->content;
                   6837: 	#    } else {
                   6838: 	#	return -1;
                   6839: 	#    }
1.482     albertel 6840: 	    return -1;
                   6841: 	}
                   6842: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6843: 	    return 'ok';
1.482     albertel 6844: 	}
                   6845: 	$info = '';
1.538     albertel 6846: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6847: 	if ($lwpresp ne 'ok') {
                   6848: 	    return -1;
                   6849: 	}
                   6850:     } else {
1.538     albertel 6851: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6852: 	if ($lwpresp ne 'ok') {
1.517     albertel 6853: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6854: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6855: 	    my $response=$ua->request($request);
                   6856: 	    if ($response->is_success()) {
1.538     albertel 6857: 		$info=$response->content;
1.517     albertel 6858: 	    } else {
                   6859: 		return -1;
                   6860: 	    }
1.482     albertel 6861: 	}
                   6862: 	my @parts = ($cdom,$cnum); 
                   6863: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6864: 	    push @parts, split(/\//,$1);
1.518     albertel 6865: 	}
1.538     albertel 6866: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6867: 	foreach my $part (@parts) {
                   6868: 	    $path .= '/'.$part;
                   6869: 	    if (!-e $path) {
                   6870: 		mkdir($path,0770);
                   6871: 	    }
                   6872: 	}
                   6873:     }
1.538     albertel 6874:     open(FILE,">$file");
1.482     albertel 6875:     print FILE $info;
                   6876:     close(FILE);
1.607     raeburn  6877:     return 'ok';
1.481     raeburn  6878: }
                   6879: 
1.517     albertel 6880: sub tokenwrapper {
                   6881:     my $uri=shift;
1.552     albertel 6882:     $uri=~s|^http\://([^/]+)||;
                   6883:     $uri=~s|^/||;
1.620     albertel 6884:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6885:     my $token=$1;
1.552     albertel 6886:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6887:     if ($udom && $uname && $file) {
                   6888: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6889:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6890:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6891:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6892:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6893:     } else {
                   6894:         return '/adm/notfound.html';
                   6895:     }
                   6896: }
                   6897: 
1.481     raeburn  6898: sub getuploaded {
                   6899:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6900:     $uri=~s/^\///;
                   6901:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6902:     my $ua=new LWP::UserAgent;
                   6903:     my $request=new HTTP::Request($reqtype,$uri);
                   6904:     my $response=$ua->request($request);
                   6905:     $$rtncode = $response->code;
1.482     albertel 6906:     if (! $response->is_success()) {
                   6907: 	return 'failed';
                   6908:     }      
                   6909:     if ($reqtype eq 'HEAD') {
1.486     www      6910: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6911:     } elsif ($reqtype eq 'GET') {
                   6912: 	$$info = $response->content;
1.472     albertel 6913:     }
1.482     albertel 6914:     return 'ok';
1.36      albertel 6915: }
                   6916: 
1.481     raeburn  6917: sub readfile {
                   6918:     my $file = shift;
                   6919:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6920:     my $fh;
                   6921:     open($fh,"<$file");
                   6922:     my $a='';
                   6923:     while (<$fh>) { $a .=$_; }
                   6924:     return $a;
                   6925: }
                   6926: 
1.36      albertel 6927: sub filelocation {
1.590     banghart 6928:     my ($dir,$file) = @_;
                   6929:     my $location;
                   6930:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6931: 
                   6932:     if ($file =~ m-^/adm/-) {
                   6933: 	$file=~s-^/adm/wrapper/-/-;
                   6934: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6935:     }
1.590     banghart 6936:     if ($file=~m:^/~:) { # is a contruction space reference
                   6937:         $location = $file;
                   6938:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6939:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6940: 	# is a correct contruction space reference
                   6941:         $location = $file;
1.609     banghart 6942:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6943:         my ($udom,$uname,$filename)=
1.609     banghart 6944:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6945:         my $home=&homeserver($uname,$udom);
                   6946:         my $is_me=0;
                   6947:         my @ids=&current_machine_ids();
                   6948:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6949:         if ($is_me) {
1.740     www      6950:   	    $location=&propath($udom,$uname).
1.590     banghart 6951:   	      '/userfiles/'.$filename;
                   6952:         } else {
                   6953:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6954:   	      $udom.'/'.$uname.'/'.$filename;
                   6955:         }
                   6956:     } else {
                   6957:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6958:         $file=~s:^/res/:/:;
                   6959:         if ( !( $file =~ m:^/:) ) {
                   6960:             $location = $dir. '/'.$file;
                   6961:         } else {
                   6962:             $location = '/home/httpd/html/res'.$file;
                   6963:         }
1.59      albertel 6964:     }
1.590     banghart 6965:     $location=~s://+:/:g; # remove duplicate /
                   6966:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6967:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6968:     return $location;
1.46      www      6969: }
1.36      albertel 6970: 
1.46      www      6971: sub hreflocation {
                   6972:     my ($dir,$file)=@_;
1.460     albertel 6973:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6974: 	$file=filelocation($dir,$file);
1.700     albertel 6975:     } elsif ($file=~m-^/adm/-) {
                   6976: 	$file=~s-^/adm/wrapper/-/-;
                   6977: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6978:     }
                   6979:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6980: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6981:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6982: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6983:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6984: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6985: 	    -/uploaded/$1/$2/-x;
1.46      www      6986:     }
1.462     albertel 6987:     return $file;
1.465     albertel 6988: }
                   6989: 
                   6990: sub current_machine_domains {
                   6991:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6992:     my @domains;
                   6993:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6994: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6995: 	if ($hostname eq $name) {
                   6996: 	    push(@domains,$hostdom{$id});
                   6997: 	}
                   6998:     }
                   6999:     return @domains;
                   7000: }
                   7001: 
                   7002: sub current_machine_ids {
                   7003:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7004:     my @ids;
                   7005:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7006: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7007: 	if ($hostname eq $name) {
                   7008: 	    push(@ids,$id);
                   7009: 	}
                   7010:     }
                   7011:     return @ids;
1.31      www      7012: }
                   7013: 
                   7014: # ------------------------------------------------------------- Declutters URLs
                   7015: 
                   7016: sub declutter {
                   7017:     my $thisfn=shift;
1.569     albertel 7018:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7019:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7020:     $thisfn=~s/^\///;
1.697     albertel 7021:     $thisfn=~s|^adm/wrapper/||;
                   7022:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7023:     $thisfn=~s/^res\///;
1.235     www      7024:     $thisfn=~s/\?.+$//;
1.268     www      7025:     return $thisfn;
                   7026: }
                   7027: 
                   7028: # ------------------------------------------------------------- Clutter up URLs
                   7029: 
                   7030: sub clutter {
                   7031:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7032:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7033:        $thisfn='/res'.$thisfn; 
                   7034:     }
1.694     albertel 7035:     if ($thisfn !~m|/adm|) {
1.695     albertel 7036: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7037: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7038: 	} else {
                   7039: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7040: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7041: 	    if ($embstyle eq 'ssi'
                   7042: 		|| ($embstyle eq 'hdn')
                   7043: 		|| ($embstyle eq 'rat')
                   7044: 		|| ($embstyle eq 'prv')
                   7045: 		|| ($embstyle eq 'ign')) {
                   7046: 		#do nothing with these
                   7047: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7048: 		|| ($embstyle eq 'emb')
                   7049: 		|| ($embstyle eq 'wrp')) {
                   7050: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7051: 	    } elsif ($embstyle eq 'unk'
                   7052: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7053: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7054: 	    } else {
1.718     www      7055: #		&logthis("Got a blank emb style");
1.695     albertel 7056: 	    }
1.694     albertel 7057: 	}
                   7058:     }
1.31      www      7059:     return $thisfn;
1.12      www      7060: }
                   7061: 
1.787     albertel 7062: sub clutter_with_no_wrapper {
                   7063:     my $uri = &clutter(shift);
                   7064:     if ($uri =~ m-^/adm/-) {
                   7065: 	$uri =~ s-^/adm/wrapper/-/-;
                   7066: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7067:     }
                   7068:     return $uri;
                   7069: }
                   7070: 
1.557     albertel 7071: sub freeze_escape {
                   7072:     my ($value)=@_;
                   7073:     if (ref($value)) {
                   7074: 	$value=&nfreeze($value);
                   7075: 	return '__FROZEN__'.&escape($value);
                   7076:     }
                   7077:     return &escape($value);
                   7078: }
                   7079: 
1.11      www      7080: 
1.557     albertel 7081: sub thaw_unescape {
                   7082:     my ($value)=@_;
                   7083:     if ($value =~ /^__FROZEN__/) {
                   7084: 	substr($value,0,10,undef);
                   7085: 	$value=&unescape($value);
                   7086: 	return &thaw($value);
                   7087:     }
                   7088:     return &unescape($value);
                   7089: }
                   7090: 
1.436     albertel 7091: sub correct_line_ends {
                   7092:     my ($result)=@_;
                   7093:     $$result =~s/\r\n/\n/mg;
                   7094:     $$result =~s/\r/\n/mg;
1.415     albertel 7095: }
1.1       albertel 7096: # ================================================================ Main Program
                   7097: 
1.184     www      7098: sub goodbye {
1.204     albertel 7099:    &logthis("Starting Shut down");
1.443     albertel 7100: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7101:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7102: #converted
1.599     albertel 7103: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7104:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7105: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7106: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7107: #1.1 only
1.599     albertel 7108: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7109: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7110: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7111: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7112:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7113:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7114:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7115:    &flushcourselogs();
                   7116:    &logthis("Shutting down");
                   7117: }
                   7118: 
1.179     www      7119: BEGIN {
1.228     harris41 7120: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7121:     unless ($readit) {
1.217     harris41 7122: {
1.781     raeburn  7123:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7124:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7125: }
1.1       albertel 7126: 
1.327     albertel 7127: # ------------------------------------------------------------ Read domain file
                   7128: {
                   7129:     %domaindescription = ();
                   7130:     %domain_auth_def = ();
                   7131:     %domain_auth_arg_def = ();
1.448     albertel 7132:     my $fh;
                   7133:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7134:        while (<$fh>) {
1.390     matthew  7135:            next if (/^(\#|\s*$)/);
                   7136: #           next if /^\#/;
1.327     albertel 7137:            chomp;
1.403     www      7138:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7139: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7140: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7141:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7142: 	   $domaindescription{$domain}=$domain_description;
                   7143: 	   $domain_lang_def{$domain}=$def_lang;
                   7144: 	   $domain_city{$domain}=$city;
                   7145: 	   $domain_longi{$domain}=$longi;
                   7146: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7147:            $domain_primary{$domain}=$primary;
1.403     www      7148: 
1.448     albertel 7149:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7150: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7151: 	}
1.327     albertel 7152:     }
1.448     albertel 7153:     close ($fh);
1.327     albertel 7154: }
                   7155: 
                   7156: 
1.1       albertel 7157: # ------------------------------------------------------------- Read hosts file
                   7158: {
1.448     albertel 7159:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7160: 
                   7161:     while (my $configline=<$config>) {
1.303     matthew  7162:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7163:        chomp($configline);
1.595     albertel 7164:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7165:        $name=~s/\s//g;
1.595     albertel 7166:        if ($id && $domain && $role && $name) {
1.252     albertel 7167: 	 $hostname{$id}=$name;
                   7168: 	 $hostdom{$id}=$domain;
                   7169: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7170:        }
1.1       albertel 7171:     }
1.448     albertel 7172:     close($config);
1.619     albertel 7173:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7174:     #&get_iphost();
1.1       albertel 7175: }
                   7176: 
1.598     albertel 7177: sub get_iphost {
                   7178:     if (%iphost) { return %iphost; }
1.653     albertel 7179:     my %name_to_ip;
1.598     albertel 7180:     foreach my $id (keys(%hostname)) {
                   7181: 	my $name=$hostname{$id};
1.653     albertel 7182: 	my $ip;
                   7183: 	if (!exists($name_to_ip{$name})) {
                   7184: 	    $ip = gethostbyname($name);
                   7185: 	    if (!$ip || length($ip) ne 4) {
                   7186: 		&logthis("Skipping host $id name $name no IP found\n");
                   7187: 		next;
                   7188: 	    }
                   7189: 	    $ip=inet_ntoa($ip);
                   7190: 	    $name_to_ip{$name} = $ip;
                   7191: 	} else {
                   7192: 	    $ip = $name_to_ip{$name};
1.598     albertel 7193: 	}
                   7194: 	push(@{$iphost{$ip}},$id);
                   7195:     }
                   7196:     return %iphost;
                   7197: }
                   7198: 
1.1       albertel 7199: # ------------------------------------------------------ Read spare server file
                   7200: {
1.448     albertel 7201:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7202: 
                   7203:     while (my $configline=<$config>) {
                   7204:        chomp($configline);
1.284     matthew  7205:        if ($configline) {
1.784     albertel 7206: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7207: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7208: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7209:        }
                   7210:     }
1.448     albertel 7211:     close($config);
1.1       albertel 7212: }
1.11      www      7213: # ------------------------------------------------------------ Read permissions
                   7214: {
1.448     albertel 7215:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7216: 
                   7217:     while (my $configline=<$config>) {
1.448     albertel 7218: 	chomp($configline);
                   7219: 	if ($configline) {
                   7220: 	    my ($role,$perm)=split(/ /,$configline);
                   7221: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7222: 	}
1.11      www      7223:     }
1.448     albertel 7224:     close($config);
1.11      www      7225: }
                   7226: 
                   7227: # -------------------------------------------- Read plain texts for permissions
                   7228: {
1.448     albertel 7229:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7230: 
                   7231:     while (my $configline=<$config>) {
1.448     albertel 7232: 	chomp($configline);
                   7233: 	if ($configline) {
1.742     raeburn  7234: 	    my ($short,@plain)=split(/:/,$configline);
                   7235:             %{$prp{$short}} = ();
                   7236: 	    if (@plain > 0) {
                   7237:                 $prp{$short}{'std'} = $plain[0];
                   7238:                 for (my $i=1; $i<@plain; $i++) {
                   7239:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7240:                 }
                   7241:             }
1.448     albertel 7242: 	}
1.135     www      7243:     }
1.448     albertel 7244:     close($config);
1.135     www      7245: }
                   7246: 
                   7247: # ---------------------------------------------------------- Read package table
                   7248: {
1.448     albertel 7249:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7250: 
                   7251:     while (my $configline=<$config>) {
1.483     albertel 7252: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7253: 	chomp($configline);
                   7254: 	my ($short,$plain)=split(/:/,$configline);
                   7255: 	my ($pack,$name)=split(/\&/,$short);
                   7256: 	if ($plain ne '') {
                   7257: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7258: 	    $packagetab{$short}=$plain; 
                   7259: 	}
1.11      www      7260:     }
1.448     albertel 7261:     close($config);
1.329     matthew  7262: }
                   7263: 
                   7264: # ------------- set up temporary directory
                   7265: {
                   7266:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7267: 
1.11      www      7268: }
                   7269: 
1.599     albertel 7270: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7271: 
1.281     www      7272: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7273: $dumpcount=0;
1.22      www      7274: 
1.163     harris41 7275: &logtouch();
1.672     albertel 7276: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7277: $readit=1;
1.564     albertel 7278:     {
                   7279: 	use integer;
                   7280: 	my $test=(2**32)+1;
1.568     albertel 7281: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7282: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7283:     }
1.195     www      7284: }
1.1       albertel 7285: }
1.179     www      7286: 
1.1       albertel 7287: 1;
1.191     harris41 7288: __END__
                   7289: 
1.243     albertel 7290: =pod
                   7291: 
1.191     harris41 7292: =head1 NAME
                   7293: 
1.243     albertel 7294: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7295: 
                   7296: =head1 SYNOPSIS
                   7297: 
1.243     albertel 7298: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7299: 
                   7300:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7301: 
1.243     albertel 7302: Common parameters:
                   7303: 
                   7304: =over 4
                   7305: 
                   7306: =item *
                   7307: 
                   7308: $uname : an internal username (if $cname expecting a course Id specifically)
                   7309: 
                   7310: =item *
                   7311: 
                   7312: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7313: 
                   7314: =item *
                   7315: 
                   7316: $symb : a resource instance identifier
                   7317: 
                   7318: =item *
                   7319: 
                   7320: $namespace : the name of a .db file that contains the data needed or
                   7321: being set.
                   7322: 
                   7323: =back
                   7324: 
1.394     bowersj2 7325: =head1 OVERVIEW
1.191     harris41 7326: 
1.394     bowersj2 7327: lonnet provides subroutines which interact with the
                   7328: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7329: about classes, users, and resources.
1.243     albertel 7330: 
                   7331: For many of these objects you can also use this to store data about
                   7332: them or modify them in various ways.
1.191     harris41 7333: 
1.394     bowersj2 7334: =head2 Symbs
1.191     harris41 7335: 
1.394     bowersj2 7336: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7337: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7338: map, the resource number of the resource in the map, and the URL of
                   7339: the resource itself. The latter is somewhat redundant, but might help
                   7340: if maps change.
                   7341: 
                   7342: An example is
                   7343: 
                   7344:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7345: 
                   7346: The respective map entry is
                   7347: 
                   7348:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7349:   title="Problem 2">
                   7350:  </resource>
                   7351: 
                   7352: Symbs are used by the random number generator, as well as to store and
                   7353: restore data specific to a certain instance of for example a problem.
                   7354: 
                   7355: =head2 Storing And Retrieving Data
                   7356: 
                   7357: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7358: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7359: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7360: is is the non-critical message twin of cstore. These functions are for
                   7361: handlers to store a perl hash to a user's permanent data space in an
                   7362: easy manner, and to retrieve it again on another call. It is expected
                   7363: that a handler would use this once at the beginning to retrieve data,
                   7364: and then again once at the end to send only the new data back.
                   7365: 
                   7366: The data is stored in the user's data directory on the user's
                   7367: homeserver under the ID of the course.
                   7368: 
                   7369: The hash that is returned by restore will have all of the previous
                   7370: value for all of the elements of the hash.
                   7371: 
                   7372: Example:
                   7373: 
                   7374:  #creating a hash
                   7375:  my %hash;
                   7376:  $hash{'foo'}='bar';
                   7377: 
                   7378:  #storing it
                   7379:  &Apache::lonnet::cstore(\%hash);
                   7380: 
                   7381:  #changing a value
                   7382:  $hash{'foo'}='notbar';
                   7383: 
                   7384:  #adding a new value
                   7385:  $hash{'bar'}='foo';
                   7386:  &Apache::lonnet::cstore(\%hash);
                   7387: 
                   7388:  #retrieving the hash
                   7389:  my %history=&Apache::lonnet::restore();
                   7390: 
                   7391:  #print the hash
                   7392:  foreach my $key (sort(keys(%history))) {
                   7393:    print("\%history{$key} = $history{$key}");
                   7394:  }
                   7395: 
                   7396: Will print out:
1.191     harris41 7397: 
1.394     bowersj2 7398:  %history{1:foo} = bar
                   7399:  %history{1:keys} = foo:timestamp
                   7400:  %history{1:timestamp} = 990455579
                   7401:  %history{2:bar} = foo
                   7402:  %history{2:foo} = notbar
                   7403:  %history{2:keys} = foo:bar:timestamp
                   7404:  %history{2:timestamp} = 990455580
                   7405:  %history{bar} = foo
                   7406:  %history{foo} = notbar
                   7407:  %history{timestamp} = 990455580
                   7408:  %history{version} = 2
                   7409: 
                   7410: Note that the special hash entries C<keys>, C<version> and
                   7411: C<timestamp> were added to the hash. C<version> will be equal to the
                   7412: total number of versions of the data that have been stored. The
                   7413: C<timestamp> attribute will be the UNIX time the hash was
                   7414: stored. C<keys> is available in every historical section to list which
                   7415: keys were added or changed at a specific historical revision of a
                   7416: hash.
                   7417: 
                   7418: B<Warning>: do not store the hash that restore returns directly. This
                   7419: will cause a mess since it will restore the historical keys as if the
                   7420: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7421: 
1.394     bowersj2 7422: Calling convention:
1.191     harris41 7423: 
1.394     bowersj2 7424:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7425:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7426: 
1.394     bowersj2 7427: For more detailed information, see lonnet specific documentation.
1.191     harris41 7428: 
1.394     bowersj2 7429: =head1 RETURN MESSAGES
1.191     harris41 7430: 
1.394     bowersj2 7431: =over 4
1.191     harris41 7432: 
1.394     bowersj2 7433: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7434: 
1.394     bowersj2 7435: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7436: when the connection is brought back up
1.191     harris41 7437: 
1.394     bowersj2 7438: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7439: for later delivery
1.191     harris41 7440: 
1.394     bowersj2 7441: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7442: 
1.394     bowersj2 7443: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7444: that was requested
1.191     harris41 7445: 
1.243     albertel 7446: =back
1.191     harris41 7447: 
1.243     albertel 7448: =head1 PUBLIC SUBROUTINES
1.191     harris41 7449: 
1.243     albertel 7450: =head2 Session Environment Functions
1.191     harris41 7451: 
1.243     albertel 7452: =over 4
1.191     harris41 7453: 
1.394     bowersj2 7454: =item * 
                   7455: X<appenv()>
                   7456: B<appenv(%hash)>: the value of %hash is written to
                   7457: the user envirnoment file, and will be restored for each access this
1.620     albertel 7458: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7459: process
1.191     harris41 7460: 
                   7461: =item *
1.394     bowersj2 7462: X<delenv()>
                   7463: B<delenv($regexp)>: removes all items from the session
                   7464: environment file that matches the regular expression in $regexp. The
1.620     albertel 7465: values are also delted from the current processes %env.
1.191     harris41 7466: 
1.243     albertel 7467: =back
                   7468: 
                   7469: =head2 User Information
1.191     harris41 7470: 
1.243     albertel 7471: =over 4
1.191     harris41 7472: 
                   7473: =item *
1.394     bowersj2 7474: X<queryauthenticate()>
                   7475: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7476: authentication scheme
                   7477: 
                   7478: =item *
1.394     bowersj2 7479: X<authenticate()>
                   7480: B<authenticate($uname,$upass,$udom)>: try to
                   7481: authenticate user from domain's lib servers (first use the current
                   7482: one). C<$upass> should be the users password.
1.191     harris41 7483: 
                   7484: =item *
1.394     bowersj2 7485: X<homeserver()>
                   7486: B<homeserver($uname,$udom)>: find the server which has
                   7487: the user's directory and files (there must be only one), this caches
                   7488: the answer, and also caches if there is a borken connection.
1.191     harris41 7489: 
                   7490: =item *
1.394     bowersj2 7491: X<idget()>
                   7492: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7493: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7494: username, and only 1 username per ID in a specific domain) (returns
                   7495: hash: id=>name,id=>name)
1.191     harris41 7496: 
                   7497: =item *
1.394     bowersj2 7498: X<idrget()>
                   7499: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7500: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7501: 
                   7502: =item *
1.394     bowersj2 7503: X<idput()>
                   7504: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7505: 
                   7506: =item *
1.394     bowersj2 7507: X<rolesinit()>
                   7508: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7509: 
                   7510: =item *
1.551     albertel 7511: X<getsection()>
                   7512: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7513: course $cname, return section name/number or '' for "not in course"
                   7514: and '-1' for "no section"
                   7515: 
                   7516: =item *
1.394     bowersj2 7517: X<userenvironment()>
                   7518: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7519: passed in @what from the requested user's environment, returns a hash
                   7520: 
                   7521: =back
                   7522: 
                   7523: =head2 User Roles
                   7524: 
                   7525: =over 4
                   7526: 
                   7527: =item *
                   7528: 
                   7529: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7530: actions
                   7531:  F: full access
                   7532:  U,I,K: authentication modes (cxx only)
                   7533:  '': forbidden
                   7534:  1: user needs to choose course
                   7535:  2: browse allowed
1.766     albertel 7536:  A: passphrase authentication needed
1.243     albertel 7537: 
                   7538: =item *
                   7539: 
                   7540: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7541: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7542: and course level
                   7543: 
                   7544: =item *
                   7545: 
                   7546: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7547: explanation of a user role term
                   7548: 
                   7549: =back
                   7550: 
                   7551: =head2 User Modification
                   7552: 
                   7553: =over 4
                   7554: 
                   7555: =item *
                   7556: 
                   7557: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7558: user for the level given by URL.  Optional start and end dates (leave empty
                   7559: string or zero for "no date")
1.191     harris41 7560: 
                   7561: =item *
                   7562: 
1.243     albertel 7563: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7564: change a users, password, possible return values are: ok,
                   7565: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7566: refused
1.191     harris41 7567: 
                   7568: =item *
                   7569: 
1.243     albertel 7570: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7571: 
                   7572: =item *
                   7573: 
1.243     albertel 7574: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7575: modify user
1.191     harris41 7576: 
                   7577: =item *
                   7578: 
1.286     matthew  7579: modifystudent
                   7580: 
                   7581: modify a students enrollment and identification information.
                   7582: The course id is resolved based on the current users environment.  
                   7583: This means the envoking user must be a course coordinator or otherwise
                   7584: associated with a course.
                   7585: 
1.297     matthew  7586: This call is essentially a wrapper for lonnet::modifyuser and
                   7587: lonnet::modify_student_enrollment
1.286     matthew  7588: 
                   7589: Inputs: 
                   7590: 
                   7591: =over 4
                   7592: 
                   7593: =item B<$udom> Students loncapa domain
                   7594: 
                   7595: =item B<$uname> Students loncapa login name
                   7596: 
                   7597: =item B<$uid> Students id/student number
                   7598: 
                   7599: =item B<$umode> Students authentication mode
                   7600: 
                   7601: =item B<$upass> Students password
                   7602: 
                   7603: =item B<$first> Students first name
                   7604: 
                   7605: =item B<$middle> Students middle name
                   7606: 
                   7607: =item B<$last> Students last name
                   7608: 
                   7609: =item B<$gene> Students generation
                   7610: 
                   7611: =item B<$usec> Students section in course
                   7612: 
                   7613: =item B<$end> Unix time of the roles expiration
                   7614: 
                   7615: =item B<$start> Unix time of the roles start date
                   7616: 
                   7617: =item B<$forceid> If defined, allow $uid to be changed
                   7618: 
                   7619: =item B<$desiredhome> server to use as home server for student
                   7620: 
                   7621: =back
1.297     matthew  7622: 
                   7623: =item *
                   7624: 
                   7625: modify_student_enrollment
                   7626: 
                   7627: Change a students enrollment status in a class.  The environment variable
                   7628: 'role.request.course' must be defined for this function to proceed.
                   7629: 
                   7630: Inputs:
                   7631: 
                   7632: =over 4
                   7633: 
                   7634: =item $udom, students domain
                   7635: 
                   7636: =item $uname, students name
                   7637: 
                   7638: =item $uid, students user id
                   7639: 
                   7640: =item $first, students first name
                   7641: 
                   7642: =item $middle
                   7643: 
                   7644: =item $last
                   7645: 
                   7646: =item $gene
                   7647: 
                   7648: =item $usec
                   7649: 
                   7650: =item $end
                   7651: 
                   7652: =item $start
                   7653: 
                   7654: =back
                   7655: 
1.191     harris41 7656: 
                   7657: =item *
                   7658: 
1.243     albertel 7659: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7660: custom role; give a custom role to a user for the level given by URL.  Specify
                   7661: name and domain of role author, and role name
1.191     harris41 7662: 
                   7663: =item *
                   7664: 
1.243     albertel 7665: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7666: 
                   7667: =item *
                   7668: 
1.243     albertel 7669: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7670: 
                   7671: =back
                   7672: 
                   7673: =head2 Course Infomation
                   7674: 
                   7675: =over 4
1.191     harris41 7676: 
                   7677: =item *
                   7678: 
1.631     albertel 7679: coursedescription($courseid) : returns a hash of information about the
                   7680: specified course id, including all environment settings for the
                   7681: course, the description of the course will be in the hash under the
                   7682: key 'description'
1.191     harris41 7683: 
                   7684: =item *
                   7685: 
1.624     albertel 7686: resdata($name,$domain,$type,@which) : request for current parameter
                   7687: setting for a specific $type, where $type is either 'course' or 'user',
                   7688: @what should be a list of parameters to ask about. This routine caches
                   7689: answers for 5 minutes.
1.243     albertel 7690: 
                   7691: =back
                   7692: 
                   7693: =head2 Course Modification
                   7694: 
                   7695: =over 4
1.191     harris41 7696: 
                   7697: =item *
                   7698: 
1.243     albertel 7699: writecoursepref($courseid,%prefs) : write preferences (environment
                   7700: database) for a course
1.191     harris41 7701: 
                   7702: =item *
                   7703: 
1.243     albertel 7704: createcourse($udom,$description,$url) : make/modify course
                   7705: 
                   7706: =back
                   7707: 
                   7708: =head2 Resource Subroutines
                   7709: 
                   7710: =over 4
1.191     harris41 7711: 
                   7712: =item *
                   7713: 
1.243     albertel 7714: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7715: 
                   7716: =item *
                   7717: 
1.243     albertel 7718: repcopy($filename) : subscribes to the requested file, and attempts to
                   7719: replicate from the owning library server, Might return
1.607     raeburn  7720: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7721: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7722: resource. Expects the local filesystem pathname
                   7723: (/home/httpd/html/res/....)
                   7724: 
                   7725: =back
                   7726: 
                   7727: =head2 Resource Information
                   7728: 
                   7729: =over 4
1.191     harris41 7730: 
                   7731: =item *
                   7732: 
1.243     albertel 7733: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7734: a vairety of different possible values, $varname should be a request
                   7735: string, and the other parameters can be used to specify who and what
                   7736: one is asking about.
                   7737: 
                   7738: Possible values for $varname are environment.lastname (or other item
                   7739: from the envirnment hash), user.name (or someother aspect about the
                   7740: user), resource.0.maxtries (or some other part and parameter of a
                   7741: resource)
1.204     albertel 7742: 
                   7743: =item *
                   7744: 
1.243     albertel 7745: directcondval($number) : get current value of a condition; reads from a state
                   7746: string
1.204     albertel 7747: 
                   7748: =item *
                   7749: 
1.243     albertel 7750: condval($condidx) : value of condition index based on state
1.204     albertel 7751: 
                   7752: =item *
                   7753: 
1.243     albertel 7754: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7755: resource's metadata, $what should be either a specific key, or either
                   7756: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7757: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7758: 
                   7759: this function automatically caches all requests
1.191     harris41 7760: 
                   7761: =item *
                   7762: 
1.243     albertel 7763: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7764: network of library servers; returns file handle of where SQL and regex results
                   7765: will be stored for query
1.191     harris41 7766: 
                   7767: =item *
                   7768: 
1.243     albertel 7769: symbread($filename) : return symbolic list entry (filename argument optional);
                   7770: returns the data handle
1.191     harris41 7771: 
                   7772: =item *
                   7773: 
1.243     albertel 7774: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7775: a possible symb for the URL in $thisfn, and if is an encryypted
                   7776: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7777: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7778: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7779: 
1.191     harris41 7780: 
                   7781: =item *
                   7782: 
1.243     albertel 7783: symbclean($symb) : removes versions numbers from a symb, returns the
                   7784: cleaned symb
1.191     harris41 7785: 
                   7786: =item *
                   7787: 
1.243     albertel 7788: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7789: course map, user must be in a course for it to work.
1.191     harris41 7790: 
                   7791: =item *
                   7792: 
1.243     albertel 7793: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7794: 
                   7795: =item *
                   7796: 
1.243     albertel 7797: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7798: a random seed, all arguments are optional, if they aren't sent it uses the
                   7799: environment to derive them. Note: if symb isn't sent and it can't get one
                   7800: from &symbread it will use the current time as its return value
1.191     harris41 7801: 
                   7802: =item *
                   7803: 
1.243     albertel 7804: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7805: unfakeable, receipt
1.191     harris41 7806: 
                   7807: =item *
                   7808: 
1.620     albertel 7809: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7810: 
                   7811: =item *
                   7812: 
1.243     albertel 7813: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7814: 
                   7815: =item *
                   7816: 
1.243     albertel 7817: 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 7818: 
                   7819: =item *
                   7820: 
1.243     albertel 7821: 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 7822: 
                   7823: =item *
                   7824: 
1.243     albertel 7825: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7826: 
                   7827: =item *
                   7828: 
1.243     albertel 7829: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7830: forcing spreadsheet to reevaluate the resource scores next time.
                   7831: 
                   7832: =back
                   7833: 
                   7834: =head2 Storing/Retreiving Data
                   7835: 
                   7836: =over 4
1.191     harris41 7837: 
                   7838: =item *
                   7839: 
1.243     albertel 7840: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7841: for this url; hashref needs to be given and should be a \%hashname; the
                   7842: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7843: be derived from the env
1.191     harris41 7844: 
                   7845: =item *
                   7846: 
1.243     albertel 7847: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7848: uses critical subroutine
1.191     harris41 7849: 
                   7850: =item *
                   7851: 
1.243     albertel 7852: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7853: all args are optional
1.191     harris41 7854: 
                   7855: =item *
                   7856: 
1.717     albertel 7857: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7858: dumps the complete (or key matching regexp) namespace into a hash
                   7859: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7860: normally &store()ed into
                   7861: 
                   7862: $range should be either an integer '100' (give me the first 100
                   7863:                                            matching records)
                   7864:               or be  two integers sperated by a - with no spaces
                   7865:                  '30-50' (give me the 30th through the 50th matching
                   7866:                           records)
                   7867: 
                   7868: 
                   7869: =item *
                   7870: 
                   7871: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7872: replaces a &store() version of data with a replacement set of data
                   7873: for a particular resource in a namespace passed in the $storehash hash 
                   7874: reference
                   7875: 
                   7876: =item *
                   7877: 
1.243     albertel 7878: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7879: works very similar to store/cstore, but all data is stored in a
                   7880: temporary location and can be reset using tmpreset, $storehash should
                   7881: be a hash reference, returns nothing on success
1.191     harris41 7882: 
                   7883: =item *
                   7884: 
1.243     albertel 7885: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7886: similar to restore, but all data is stored in a temporary location and
                   7887: can be reset using tmpreset. Returns a hash of values on success,
                   7888: error string otherwise.
1.191     harris41 7889: 
                   7890: =item *
                   7891: 
1.243     albertel 7892: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7893: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7894: 
                   7895: =item *
                   7896: 
1.243     albertel 7897: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7898: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7899: 
                   7900: =item *
                   7901: 
1.243     albertel 7902: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7903: namesp ($udom and $uname are optional)
1.191     harris41 7904: 
                   7905: =item *
                   7906: 
1.702     albertel 7907: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7908: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7909: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7910: 
1.702     albertel 7911: $range should be either an integer '100' (give me the first 100
                   7912:                                            matching records)
                   7913:               or be  two integers sperated by a - with no spaces
                   7914:                  '30-50' (give me the 30th through the 50th matching
                   7915:                           records)
1.449     matthew  7916: =item *
                   7917: 
                   7918: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7919: $store can be a scalar, an array reference, or if the amount to be 
                   7920: incremented is > 1, a hash reference.
                   7921: 
                   7922: ($udom and $uname are optional)
1.191     harris41 7923: 
                   7924: =item *
                   7925: 
1.243     albertel 7926: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7927: ($udom and $uname are optional)
1.191     harris41 7928: 
                   7929: =item *
                   7930: 
1.243     albertel 7931: cput($namespace,$storehash,$udom,$uname) : critical put
                   7932: ($udom and $uname are optional)
1.191     harris41 7933: 
                   7934: =item *
                   7935: 
1.748     albertel 7936: newput($namespace,$storehash,$udom,$uname) :
                   7937: 
                   7938: Attempts to store the items in the $storehash, but only if they don't
                   7939: currently exist, if this succeeds you can be certain that you have 
                   7940: successfully created a new key value pair in the $namespace db.
                   7941: 
                   7942: 
                   7943: Args:
                   7944:  $namespace: name of database to store values to
                   7945:  $storehash: hashref to store to the db
                   7946:  $udom: (optional) domain of user containing the db
                   7947:  $uname: (optional) name of user caontaining the db
                   7948: 
                   7949: Returns:
                   7950:  'ok' -> succeeded in storing all keys of $storehash
                   7951:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7952:                         least <key> already existed in the db (other
                   7953:                         requested keys may also already exist)
                   7954:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7955:  'con_lost' -> unable to contact request server
                   7956:  'refused' -> action was not allowed by remote machine
                   7957: 
                   7958: 
                   7959: =item *
                   7960: 
1.243     albertel 7961: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7962: reference filled in from namesp (encrypts the return communication)
                   7963: ($udom and $uname are optional)
1.191     harris41 7964: 
                   7965: =item *
                   7966: 
1.243     albertel 7967: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7968: critical subroutine
                   7969: 
                   7970: =back
                   7971: 
                   7972: =head2 Network Status Functions
                   7973: 
                   7974: =over 4
1.191     harris41 7975: 
                   7976: =item *
                   7977: 
                   7978: dirlist($uri) : return directory list based on URI
                   7979: 
                   7980: =item *
                   7981: 
1.243     albertel 7982: spareserver() : find server with least workload from spare.tab
                   7983: 
                   7984: =back
                   7985: 
                   7986: =head2 Apache Request
                   7987: 
                   7988: =over 4
1.191     harris41 7989: 
                   7990: =item *
                   7991: 
1.243     albertel 7992: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7993: localhost, posts hash
                   7994: 
                   7995: =back
                   7996: 
                   7997: =head2 Data to String to Data
                   7998: 
                   7999: =over 4
1.191     harris41 8000: 
                   8001: =item *
                   8002: 
1.243     albertel 8003: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8004: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8005: 
                   8006: =item *
                   8007: 
1.243     albertel 8008: hashref2str($hashref) : convert a hashref into a string complete with
                   8009: escaping and '=' and '&' separators, supports elements that are
                   8010: arrayrefs and hashrefs
1.191     harris41 8011: 
                   8012: =item *
                   8013: 
1.243     albertel 8014: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8015: with escaping and '&' separators, supports elements that are arrayrefs
                   8016: and hashrefs
1.191     harris41 8017: 
                   8018: =item *
                   8019: 
1.243     albertel 8020: str2hash($string) : convert string to hash using unescaping and
                   8021: splitting on '=' and '&', supports elements that are arrayrefs and
                   8022: hashrefs
1.191     harris41 8023: 
                   8024: =item *
                   8025: 
1.243     albertel 8026: str2array($string) : convert string to hash using unescaping and
                   8027: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8028: 
                   8029: =back
                   8030: 
                   8031: =head2 Logging Routines
                   8032: 
                   8033: =over 4
                   8034: 
                   8035: These routines allow one to make log messages in the lonnet.log and
                   8036: lonnet.perm logfiles.
1.191     harris41 8037: 
                   8038: =item *
                   8039: 
1.243     albertel 8040: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8041: 
                   8042: =item *
                   8043: 
1.243     albertel 8044: logthis() : append message to the normal lonnet.log file, it gets
                   8045: preiodically rolled over and deleted.
1.191     harris41 8046: 
                   8047: =item *
                   8048: 
1.243     albertel 8049: logperm() : append a permanent message to lonnet.perm.log, this log
                   8050: file never gets deleted by any automated portion of the system, only
                   8051: messages of critical importance should go in here.
                   8052: 
                   8053: =back
                   8054: 
                   8055: =head2 General File Helper Routines
                   8056: 
                   8057: =over 4
1.191     harris41 8058: 
                   8059: =item *
                   8060: 
1.481     raeburn  8061: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8062: (a) files in /uploaded
                   8063:   (i) If a local copy of the file exists - 
                   8064:       compares modification date of local copy with last-modified date for 
                   8065:       definitive version stored on home server for course. If local copy is 
                   8066:       stale, requests a new version from the home server and stores it. 
                   8067:       If the original has been removed from the home server, then local copy 
                   8068:       is unlinked.
                   8069:   (ii) If local copy does not exist -
                   8070:       requests the file from the home server and stores it. 
                   8071:   
                   8072:   If $caller is 'uploadrep':  
                   8073:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8074:     for request for files originally uploaded via DOCS. 
                   8075:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8076:   
                   8077:   Otherwise:
                   8078:      This indicates a call from the content generation phase of the request.
                   8079:      -  returns the entire contents of the file or -1.
                   8080:      
                   8081: (b) files in /res
                   8082:    - returns the entire contents of a file or -1; 
                   8083:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8084: 
1.712     albertel 8085: 
                   8086: =item *
                   8087: 
                   8088: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8089:                   reference
                   8090: 
                   8091: returns either a stat() list of data about the file or an empty list
                   8092: if the file doesn't exist or couldn't find out about it (connection
                   8093: problems or user unknown)
                   8094: 
1.191     harris41 8095: =item *
                   8096: 
1.243     albertel 8097: filelocation($dir,$file) : returns file system location of a file
                   8098: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8099: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8100: and a file of ../bob will become /a/bob)
1.191     harris41 8101: 
                   8102: =item *
                   8103: 
                   8104: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8105: filelocation except for hrefs
                   8106: 
                   8107: =item *
                   8108: 
                   8109: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8110: 
1.243     albertel 8111: =back
                   8112: 
1.608     albertel 8113: =head2 Usererfile file routines (/uploaded*)
                   8114: 
                   8115: =over 4
                   8116: 
                   8117: =item *
                   8118: 
                   8119: userfileupload(): main rotine for putting a file in a user or course's
                   8120:                   filespace, arguments are,
                   8121: 
1.620     albertel 8122:  formname - required - this is the name of the element in $env where the
1.608     albertel 8123:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8124:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8125:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8126:  coursedoc - if true, store the file in the course of the active role
                   8127:              of the current user
                   8128:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8129:          if undefined, it will be placed in "unknown"
                   8130: 
                   8131:  (This routine calls clean_filename() to remove any dangerous
                   8132:  characters from the filename, and then calls finuserfileupload() to
                   8133:  complete the transaction)
                   8134: 
                   8135:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8136:  and /adm/notfound.html if unsuccessful
                   8137: 
                   8138: =item *
                   8139: 
                   8140: clean_filename(): routine for cleaing a filename up for storage in
                   8141:                  userfile space, argument is:
                   8142: 
                   8143:  filename - proposed filename
                   8144: 
                   8145: returns: the new clean filename
                   8146: 
                   8147: =item *
                   8148: 
                   8149: finishuserfileupload(): routine that creaes and sends the file to
                   8150: userspace, probably shouldn't be called directly
                   8151: 
                   8152:   docuname: username or courseid of destination for the file
                   8153:   docudom: domain of user/course of destination for the file
                   8154:   formname: same as for userfileupload()
                   8155:   fname: filename (inculding subdirectories) for the file
                   8156: 
                   8157:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8158:  and /adm/notfound.html if unsuccessful
                   8159: 
                   8160: =item *
                   8161: 
                   8162: renameuserfile(): renames an existing userfile to a new name
                   8163: 
                   8164:   Args:
                   8165:    docuname: username or courseid of destination for the file
                   8166:    docudom: domain of user/course of destination for the file
                   8167:    old: current file name (including any subdirs under userfiles)
                   8168:    new: desired file name (including any subdirs under userfiles)
                   8169: 
                   8170: =item *
                   8171: 
                   8172: mkdiruserfile(): creates a directory is a userfiles dir
                   8173: 
                   8174:   Args:
                   8175:    docuname: username or courseid of destination for the file
                   8176:    docudom: domain of user/course of destination for the file
                   8177:    dir: dir to create (including any subdirs under userfiles)
                   8178: 
                   8179: =item *
                   8180: 
                   8181: removeuserfile(): removes a file that exists in userfiles
                   8182: 
                   8183:   Args:
                   8184:    docuname: username or courseid of destination for the file
                   8185:    docudom: domain of user/course of destination for the file
                   8186:    fname: filname to delete (including any subdirs under userfiles)
                   8187: 
                   8188: =item *
                   8189: 
                   8190: removeuploadedurl(): convience function for removeuserfile()
                   8191: 
                   8192:   Args:
                   8193:    url:  a full /uploaded/... url to delete
                   8194: 
1.747     albertel 8195: =item * 
                   8196: 
                   8197: get_portfile_permissions():
                   8198:   Args:
                   8199:     domain: domain of user or course contain the portfolio files
                   8200:     user: name of user or num of course contain the portfolio files
                   8201:   Returns:
                   8202:     hashref of a dump of the proper file_permissions.db
                   8203:    
                   8204: 
                   8205: =item * 
                   8206: 
                   8207: get_access_controls():
                   8208: 
                   8209: Args:
                   8210:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8211:   group: (optional) the group you want the files associated with
                   8212:   file: (optional) the file you want access info on
                   8213: 
                   8214: Returns:
1.749     raeburn  8215:     a hash (keys are file names) of hashes containing
                   8216:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8217:         values are XML containing access control settings (see below) 
1.747     albertel 8218: 
                   8219: Internal notes:
                   8220: 
1.749     raeburn  8221:  access controls are stored in file_permissions.db as key=value pairs.
                   8222:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8223:         where scope -> public,guest,course,group,domains or users.
                   8224:               end -> UNIX time for end of access (0 -> no end date)
                   8225:               start -> UNIX time for start of access
                   8226: 
                   8227:     value -> XML description of access control
                   8228:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8229:             <start></start>
                   8230:             <end></end>
                   8231: 
                   8232:             <password></password>  for scope type = guest
                   8233: 
                   8234:             <domain></domain>     for scope type = course or group
                   8235:             <number></number>
                   8236:             <roles id="">
                   8237:              <role></role>
                   8238:              <access></access>
                   8239:              <section></section>
                   8240:              <group></group>
                   8241:             </roles>
                   8242: 
                   8243:             <dom></dom>         for scope type = domains
                   8244: 
                   8245:             <users>             for scope type = users
                   8246:              <user>
                   8247:               <uname></uname>
                   8248:               <udom></udom>
                   8249:              </user>
                   8250:             </users>
                   8251:            </scope> 
                   8252:               
                   8253:  Access data is also aggregated for each file in an additional key=value pair:
                   8254:  key -> path to file/file_name\0accesscontrol 
                   8255:  value -> reference to hash
                   8256:           hash contains key = value pairs
                   8257:           where key = uniqueID:scope_end_start
                   8258:                 value = UNIX time record was last updated
                   8259: 
                   8260:           Used to improve speed of look-ups of access controls for each file.  
                   8261:  
                   8262:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8263: 
                   8264: modify_access_controls():
                   8265: 
                   8266: Modifies access controls for a portfolio file
                   8267: Args
                   8268: 1. file name
                   8269: 2. reference to hash of required changes,
                   8270: 3. domain
                   8271: 4. username
                   8272:   where domain,username are the domain of the portfolio owner 
                   8273:   (either a user or a course) 
                   8274: 
                   8275: Returns:
                   8276: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8277: 2. result of deletions ('ok' or 'error', with error message).
                   8278: 3. reference to hash of any new or updated access controls.
                   8279: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8280:    key = integer (inbound ID)
                   8281:    value = uniqueID  
1.747     albertel 8282: 
1.608     albertel 8283: =back
                   8284: 
1.243     albertel 8285: =head2 HTTP Helper Routines
                   8286: 
                   8287: =over 4
                   8288: 
1.191     harris41 8289: =item *
                   8290: 
                   8291: escape() : unpack non-word characters into CGI-compatible hex codes
                   8292: 
                   8293: =item *
                   8294: 
                   8295: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8296: 
1.243     albertel 8297: =back
                   8298: 
                   8299: =head1 PRIVATE SUBROUTINES
                   8300: 
                   8301: =head2 Underlying communication routines (Shouldn't call)
                   8302: 
                   8303: =over 4
                   8304: 
                   8305: =item *
                   8306: 
                   8307: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8308: 
                   8309: =item *
                   8310: 
                   8311: reply() : uses subreply to send a message to remote machine, logs all failures
                   8312: 
                   8313: =item *
                   8314: 
                   8315: critical() : passes a critical message to another server; if cannot
                   8316: get through then place message in connection buffer directory and
                   8317: returns con_delayed, if incapable of saving message, returns
                   8318: con_failed
                   8319: 
                   8320: =item *
                   8321: 
                   8322: reconlonc() : tries to reconnect lonc client processes.
                   8323: 
                   8324: =back
                   8325: 
                   8326: =head2 Resource Access Logging
                   8327: 
                   8328: =over 4
                   8329: 
                   8330: =item *
                   8331: 
                   8332: flushcourselogs() : flush (save) buffer logs and access logs
                   8333: 
                   8334: =item *
                   8335: 
                   8336: courselog($what) : save message for course in hash
                   8337: 
                   8338: =item *
                   8339: 
                   8340: courseacclog($what) : save message for course using &courselog().  Perform
                   8341: special processing for specific resource types (problems, exams, quizzes, etc).
                   8342: 
1.191     harris41 8343: =item *
                   8344: 
                   8345: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8346: as a PerlChildExitHandler
1.243     albertel 8347: 
                   8348: =back
                   8349: 
                   8350: =head2 Other
                   8351: 
                   8352: =over 4
                   8353: 
                   8354: =item *
                   8355: 
                   8356: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8357: 
                   8358: =back
                   8359: 
                   8360: =cut

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