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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.790   ! albertel    4: # $Id: lonnet.pm,v 1.789 2006/10/04 21:02:41 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790   ! albertel   55: use Math::Random;
1.740     www        56: use lib '/home/httpd/lib/perl';
                     57: use LONCAPA;
                     58: use LONCAPA::Configuration;
1.676     albertel   59: 
1.195     www        60: my $readit;
1.550     foxr       61: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   62: 
1.619     albertel   63: require Exporter;
                     64: 
                     65: our @ISA = qw (Exporter);
                     66: our @EXPORT = qw(%env);
                     67: 
1.449     matthew    68: =pod
                     69: 
                     70: =head1 Package Variables
                     71: 
                     72: These are largely undocumented, so if you decipher one please note it here.
                     73: 
                     74: =over 4
                     75: 
                     76: =item $processmarker
                     77: 
                     78: Contains the time this process was started and this servers host id.
                     79: 
                     80: =item $dumpcount
                     81: 
                     82: Counts the number of times a message log flush has been attempted (regardless
                     83: of success) by this process.  Used as part of the filename when messages are
                     84: delayed.
                     85: 
                     86: =back
                     87: 
                     88: =cut
                     89: 
                     90: 
1.1       albertel   91: # --------------------------------------------------------------------- Logging
1.729     www        92: {
                     93:     my $logid;
                     94:     sub instructor_log {
                     95: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     96: 	$logid++;
                     97: 	my $id=time().'00000'.$$.'00000'.$logid;
                     98: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        99: 				    { $id => {
                    100: 					'exe_uname' => $env{'user.name'},
                    101: 					'exe_udom'  => $env{'user.domain'},
                    102: 					'exe_time'  => time(),
                    103: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    104: 					'delflag'   => $delflag,
                    105: 					'logentry'  => $storehash,
                    106: 					'uname'     => $uname,
                    107: 					'udom'      => $udom,
                    108: 				    }
                    109: 				  },
1.729     www       110: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    111: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    112: 				    );
                    113:     }
                    114: }
1.1       albertel  115: 
1.163     harris41  116: sub logtouch {
                    117:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  118:     unless (-e "$execdir/logs/lonnet.log") {	
                    119: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  120: 	close $fh;
                    121:     }
                    122:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    123:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    124: }
                    125: 
1.1       albertel  126: sub logthis {
                    127:     my $message=shift;
                    128:     my $execdir=$perlvar{'lonDaemons'};
                    129:     my $now=time;
                    130:     my $local=localtime($now);
1.448     albertel  131:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    132: 	print $fh "$local ($$): $message\n";
                    133: 	close($fh);
                    134:     }
1.1       albertel  135:     return 1;
                    136: }
                    137: 
                    138: sub logperm {
                    139:     my $message=shift;
                    140:     my $execdir=$perlvar{'lonDaemons'};
                    141:     my $now=time;
                    142:     my $local=localtime($now);
1.448     albertel  143:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    144: 	print $fh "$now:$message:$local\n";
                    145: 	close($fh);
                    146:     }
1.1       albertel  147:     return 1;
                    148: }
                    149: 
                    150: # -------------------------------------------------- Non-critical communication
                    151: sub subreply {
                    152:     my ($cmd,$server)=@_;
1.704     albertel  153:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      154:     #
                    155:     #  With loncnew process trimming, there's a timing hole between lonc server
                    156:     #  process exit and the master server picking up the listen on the AF_UNIX
                    157:     #  socket.  In that time interval, a lock file will exist:
                    158: 
                    159:     my $lockfile=$peerfile.".lock";
                    160:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    161: 	sleep(1);
                    162:     }
                    163:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      164:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      165:     #
1.550     foxr      166:     #   We'll give the connection a few tries before abandoning it.  If
                    167:     #   connection is not possible, we'll con_lost back to the client.
                    168:     #   
                    169:     my $client;
                    170:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    171: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    172: 				      Type    => SOCK_STREAM,
                    173: 				      Timeout => 10);
                    174: 	if($client) {
                    175: 	    last;		# Connected!
                    176: 	}
                    177: 	sleep(1);		# Try again later if failed connection.
                    178:     }
                    179:     my $answer;
                    180:     if ($client) {
1.704     albertel  181: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      182: 	$answer=<$client>;
                    183: 	if (!$answer) { $answer="con_lost"; }
                    184: 	chomp($answer);
                    185:     } else {
                    186: 	$answer = 'con_lost';	# Failed connection.
                    187:     }
1.1       albertel  188:     return $answer;
                    189: }
                    190: 
                    191: sub reply {
                    192:     my ($cmd,$server)=@_;
1.205     www       193:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  194:     my $answer=subreply($cmd,$server);
1.65      www       195:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  196:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       197:                 " $cmd to $server returned $answer</font>");
                    198:     }
1.1       albertel  199:     return $answer;
                    200: }
                    201: 
                    202: # ----------------------------------------------------------- Send USR1 to lonc
                    203: 
                    204: sub reconlonc {
                    205:     my $peerfile=shift;
                    206:     &logthis("Trying to reconnect for $peerfile");
                    207:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  208:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  209: 	my $loncpid=<$fh>;
                    210:         chomp($loncpid);
                    211:         if (kill 0 => $loncpid) {
                    212: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    213:             kill USR1 => $loncpid;
                    214:             sleep 1;
                    215:             if (-e "$peerfile") { return; }
                    216:             &logthis("$peerfile still not there, give it another try");
                    217:             sleep 5;
                    218:             if (-e "$peerfile") { return; }
1.12      www       219:             &logthis(
1.672     albertel  220:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  221:         } else {
1.12      www       222: 	    &logthis(
1.672     albertel  223:                "<font color=\"blue\">WARNING:".
1.12      www       224:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  225:         }
                    226:     } else {
1.672     albertel  227:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  228:     }
                    229: }
                    230: 
                    231: # ------------------------------------------------------ Critical communication
1.12      www       232: 
1.1       albertel  233: sub critical {
                    234:     my ($cmd,$server)=@_;
1.89      www       235:     unless ($hostname{$server}) {
1.672     albertel  236:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       237:                " Critical message to unknown server ($server)</font>");
                    238:         return 'no_such_host';
                    239:     }
1.1       albertel  240:     my $answer=reply($cmd,$server);
                    241:     if ($answer eq 'con_lost') {
                    242: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  243: 	my $answer=reply($cmd,$server);
1.1       albertel  244:         if ($answer eq 'con_lost') {
                    245:             my $now=time;
                    246:             my $middlename=$cmd;
1.5       www       247:             $middlename=substr($middlename,0,16);
1.1       albertel  248:             $middlename=~s/\W//g;
                    249:             my $dfilename=
1.305     www       250:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    251:             $dumpcount++;
1.1       albertel  252:             {
1.448     albertel  253: 		my $dfh;
                    254: 		if (open($dfh,">$dfilename")) {
                    255: 		    print $dfh "$cmd\n"; 
                    256: 		    close($dfh);
                    257: 		}
1.1       albertel  258:             }
                    259:             sleep 2;
                    260:             my $wcmd='';
                    261:             {
1.448     albertel  262: 		my $dfh;
                    263: 		if (open($dfh,"<$dfilename")) {
                    264: 		    $wcmd=<$dfh>; 
                    265: 		    close($dfh);
                    266: 		}
1.1       albertel  267:             }
                    268:             chomp($wcmd);
1.7       www       269:             if ($wcmd eq $cmd) {
1.672     albertel  270: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       271:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  272:                 &logperm("D:$server:$cmd");
                    273: 	        return 'con_delayed';
                    274:             } else {
1.672     albertel  275:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       276:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  277:                 &logperm("F:$server:$cmd");
                    278:                 return 'con_failed';
                    279:             }
                    280:         }
                    281:     }
                    282:     return $answer;
1.405     albertel  283: }
                    284: 
1.755     albertel  285: # ------------------------------------------- check if return value is an error
                    286: 
                    287: sub error {
                    288:     my ($result) = @_;
1.756     albertel  289:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  290: 	if ($2 == 2) { return undef; }
                    291: 	return $1;
                    292:     }
                    293:     return undef;
                    294: }
                    295: 
1.783     albertel  296: sub convert_and_load_session_env {
                    297:     my ($lonidsdir,$handle)=@_;
                    298:     my @profile;
                    299:     {
                    300: 	open(my $idf,"$lonidsdir/$handle.id");
                    301: 	flock($idf,LOCK_SH);
                    302: 	@profile=<$idf>;
                    303: 	close($idf);
                    304:     }
                    305:     my %temp_env;
                    306:     foreach my $line (@profile) {
1.786     albertel  307: 	if ($line !~ m/=/) {
                    308: 	    return 0;
                    309: 	}
1.783     albertel  310: 	chomp($line);
                    311: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    312: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    313:     }
                    314:     unlink("$lonidsdir/$handle.id");
                    315:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    316: 	    0640)) {
                    317: 	%disk_env = %temp_env;
                    318: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    319: 	untie(%disk_env);
                    320:     }
1.786     albertel  321:     return 1;
1.783     albertel  322: }
                    323: 
1.374     www       324: # ------------------------------------------- Transfer profile into environment
1.780     albertel  325: my $env_loaded;
                    326: sub transfer_profile_to_env {
1.788     albertel  327:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    328:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       329: 
1.720     albertel  330:     if (!defined($lonidsdir)) {
                    331: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    332:     }
                    333:     if (!defined($handle)) {
                    334:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    335:     }
                    336: 
1.786     albertel  337:     my $convert;
                    338:     {
                    339:     	open(my $idf,"$lonidsdir/$handle.id");
                    340: 	flock($idf,LOCK_SH);
                    341: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    342: 		&GDBM_READER(),0640)) {
                    343: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    344: 	    untie(%disk_env);
                    345: 	} else {
                    346: 	    $convert = 1;
                    347: 	}
                    348:     }
                    349:     if ($convert) {
                    350: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    351: 	    &logthis("Failed to load session, or convert session.");
                    352: 	}
1.374     www       353:     }
1.783     albertel  354: 
1.786     albertel  355:     my %remove;
1.783     albertel  356:     while ( my $envname = each(%env) ) {
1.433     matthew   357:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    358:             if ($time < time-300) {
1.783     albertel  359:                 $remove{$key}++;
1.433     matthew   360:             }
                    361:         }
                    362:     }
1.783     albertel  363: 
1.619     albertel  364:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  365:     $env_loaded=1;
1.783     albertel  366:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   367:         &delenv($expired_key);
1.374     www       368:     }
1.1       albertel  369: }
                    370: 
1.5       www       371: # ---------------------------------------------------------- Append Environment
                    372: 
                    373: sub appenv {
1.6       www       374:     my %newenv=@_;
1.692     albertel  375:     foreach my $key (keys(%newenv)) {
                    376: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  377:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  378:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       379:                 .'</font>');
1.692     albertel  380: 	    delete($newenv{$key});
1.35      www       381:         } else {
1.692     albertel  382:             $env{$key}=$newenv{$key};
1.35      www       383:         }
1.191     harris41  384:     }
1.783     albertel  385:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    386: 	    0640)) {
                    387: 	while (my ($key,$value) = each(%newenv)) {
                    388: 	    $disk_env{$key} = $value;
1.448     albertel  389: 	}
1.783     albertel  390: 	untie(%disk_env);
1.56      www       391:     }
                    392:     return 'ok';
                    393: }
                    394: # ----------------------------------------------------- Delete from Environment
                    395: 
                    396: sub delenv {
                    397:     my $delthis=shift;
                    398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  399:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       400:                 "Attempt to delete from environment ".$delthis);
                    401:         return 'error';
                    402:     }
1.783     albertel  403:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    404: 	    0640)) {
                    405: 	foreach my $key (keys(%disk_env)) {
                    406: 	    if ($key=~/^$delthis/) { 
1.619     albertel  407:                 delete($env{$key});
1.783     albertel  408:                 delete($disk_env{$key});
1.473     matthew   409:             }
1.448     albertel  410: 	}
1.783     albertel  411: 	untie(%disk_env);
1.5       www       412:     }
                    413:     return 'ok';
1.369     albertel  414: }
                    415: 
1.790   ! albertel  416: =pod
        !           417: 
        !           418: =item * get_env_multiple($name) 
        !           419: 
        !           420: gets $name from the %env hash, it seemlessly handles the cases where multiple
        !           421: values may be defined and end up as an array ref.
        !           422: 
        !           423: returns an array of values
        !           424: 
        !           425: =cut
        !           426: 
        !           427: sub get_env_multiple {
        !           428:     my ($name) = @_;
        !           429:     my @values;
        !           430:     if (defined($env{$name})) {
        !           431:         # exists is it an array
        !           432:         if (ref($env{$name})) {
        !           433:             @values=@{ $env{$name} };
        !           434:         } else {
        !           435:             $values[0]=$env{$name};
        !           436:         }
        !           437:     }
        !           438:     return(@values);
        !           439: }
        !           440: 
1.369     albertel  441: # ------------------------------------------ Find out current server userload
                    442: # there is a copy in lond
                    443: sub userload {
                    444:     my $numusers=0;
                    445:     {
                    446: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    447: 	my $filename;
                    448: 	my $curtime=time;
                    449: 	while ($filename=readdir(LONIDS)) {
                    450: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  451: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  452: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  453: 	}
                    454: 	closedir(LONIDS);
                    455:     }
                    456:     my $userloadpercent=0;
                    457:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    458:     if ($maxuserload) {
1.371     albertel  459: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  460:     }
1.372     albertel  461:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  462:     return $userloadpercent;
1.283     www       463: }
                    464: 
                    465: # ------------------------------------------ Fight off request when overloaded
                    466: 
                    467: sub overloaderror {
                    468:     my ($r,$checkserver)=@_;
                    469:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    470:     my $loadavg;
                    471:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  472:        open(my $loadfile,'/proc/loadavg');
1.283     www       473:        $loadavg=<$loadfile>;
                    474:        $loadavg =~ s/\s.*//g;
1.285     matthew   475:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  476:        close($loadfile);
1.283     www       477:     } else {
                    478:        $loadavg=&reply('load',$checkserver);
                    479:     }
1.285     matthew   480:     my $overload=$loadavg-100;
1.283     www       481:     if ($overload>0) {
1.285     matthew   482: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       483:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       484:         return 413;
1.283     www       485:     }    
                    486:     return '';
1.5       www       487: }
1.1       albertel  488: 
                    489: # ------------------------------ Find server with least workload from spare.tab
1.11      www       490: 
1.1       albertel  491: sub spareserver {
1.670     albertel  492:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  493:     my $spare_server;
1.370     albertel  494:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  495:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    496:                                                      :  $userloadpercent;
                    497:     
                    498:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    499: 	($spare_server, $lowest_load) =
                    500: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    501:     }
                    502: 
                    503:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    504: 
                    505:     if (!$found_server) {
                    506: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    507: 	    ($spare_server, $lowest_load) =
                    508: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    509: 	}
                    510:     }
                    511: 
                    512:     if (!$want_server_name) {
                    513: 	$spare_server="http://$hostname{$spare_server}";
                    514:     }
                    515:     return $spare_server;
                    516: }
                    517: 
                    518: sub compare_server_load {
                    519:     my ($try_server, $spare_server, $lowest_load) = @_;
                    520: 
                    521:     my $loadans     = &reply('load',    $try_server);
                    522:     my $userloadans = &reply('userload',$try_server);
                    523: 
                    524:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    525: 	next; #didn't get a number from the server
                    526:     }
                    527: 
                    528:     my $load;
                    529:     if ($loadans =~ /\d/) {
                    530: 	if ($userloadans =~ /\d/) {
                    531: 	    #both are numbers, pick the bigger one
                    532: 	    $load = ($loadans > $userloadans) ? $loadans 
                    533: 		                              : $userloadans;
1.411     albertel  534: 	} else {
1.784     albertel  535: 	    $load = $loadans;
1.411     albertel  536: 	}
1.784     albertel  537:     } else {
                    538: 	$load = $userloadans;
                    539:     }
                    540: 
                    541:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    542: 	$spare_server = $try_server;
                    543: 	$lowest_load  = $load;
1.370     albertel  544:     }
1.784     albertel  545:     return ($spare_server,$lowest_load);
1.202     matthew   546: }
                    547: # --------------------------------------------- Try to change a user's password
                    548: 
                    549: sub changepass {
                    550:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    551:     $currentpass = &escape($currentpass);
                    552:     $newpass     = &escape($newpass);
                    553:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    554: 		       $server);
                    555:     if (! $answer) {
                    556: 	&logthis("No reply on password change request to $server ".
                    557: 		 "by $uname in domain $udom.");
                    558:     } elsif ($answer =~ "^ok") {
                    559:         &logthis("$uname in $udom successfully changed their password ".
                    560: 		 "on $server.");
                    561:     } elsif ($answer =~ "^pwchange_failure") {
                    562: 	&logthis("$uname in $udom was unable to change their password ".
                    563: 		 "on $server.  The action was blocked by either lcpasswd ".
                    564: 		 "or pwchange");
                    565:     } elsif ($answer =~ "^non_authorized") {
                    566:         &logthis("$uname in $udom did not get their password correct when ".
                    567: 		 "attempting to change it on $server.");
                    568:     } elsif ($answer =~ "^auth_mode_error") {
                    569:         &logthis("$uname in $udom attempted to change their password despite ".
                    570: 		 "not being locally or internally authenticated on $server.");
                    571:     } elsif ($answer =~ "^unknown_user") {
                    572:         &logthis("$uname in $udom attempted to change their password ".
                    573: 		 "on $server but were unable to because $server is not ".
                    574: 		 "their home server.");
                    575:     } elsif ($answer =~ "^refused") {
                    576: 	&logthis("$server refused to change $uname in $udom password because ".
                    577: 		 "it was sent an unencrypted request to change the password.");
                    578:     }
                    579:     return $answer;
1.1       albertel  580: }
                    581: 
1.169     harris41  582: # ----------------------- Try to determine user's current authentication scheme
                    583: 
                    584: sub queryauthenticate {
                    585:     my ($uname,$udom)=@_;
1.456     albertel  586:     my $uhome=&homeserver($uname,$udom);
                    587:     if (!$uhome) {
                    588: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    589: 	return 'no_host';
                    590:     }
                    591:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    592:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    593: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  594:     }
1.456     albertel  595:     return $answer;
1.169     harris41  596: }
                    597: 
1.1       albertel  598: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       599: 
1.1       albertel  600: sub authenticate {
                    601:     my ($uname,$upass,$udom)=@_;
1.12      www       602:     $upass=escape($upass);
1.199     www       603:     $uname=~s/\W//g;
1.471     albertel  604:     my $uhome=&homeserver($uname,$udom);
                    605:     if (!$uhome) {
                    606: 	&logthis("User $uname at $udom is unknown in authenticate");
                    607: 	return 'no_host';
1.1       albertel  608:     }
1.471     albertel  609:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    610:     if ($answer eq 'authorized') {
                    611: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    612: 	return $uhome; 
                    613:     }
                    614:     if ($answer eq 'non_authorized') {
                    615: 	&logthis("User $uname at $udom rejected by $uhome");
                    616: 	return 'no_host'; 
1.9       www       617:     }
1.471     albertel  618:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  619:     return 'no_host';
                    620: }
                    621: 
                    622: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       623: 
1.599     albertel  624: my %homecache;
1.1       albertel  625: sub homeserver {
1.230     stredwic  626:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  627:     my $index="$uname:$udom";
1.426     albertel  628: 
1.599     albertel  629:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  630:     my $tryserver;
                    631:     foreach $tryserver (keys %libserv) {
1.230     stredwic  632:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  633: 		 exists($badServerCache{$tryserver}));
1.1       albertel  634: 	if ($hostdom{$tryserver} eq $udom) {
                    635:            my $answer=reply("home:$udom:$uname",$tryserver);
                    636:            if ($answer eq 'found') { 
1.599     albertel  637: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  638:            } elsif ($answer eq 'no_host') {
                    639: 	       $badServerCache{$tryserver}=1;
1.221     matthew   640:            }
1.1       albertel  641:        }
                    642:     }    
                    643:     return 'no_host';
1.70      www       644: }
                    645: 
                    646: # ------------------------------------- Find the usernames behind a list of IDs
                    647: 
                    648: sub idget {
                    649:     my ($udom,@ids)=@_;
                    650:     my %returnhash=();
                    651:     
                    652:     my $tryserver;
                    653:     foreach $tryserver (keys %libserv) {
                    654:        if ($hostdom{$tryserver} eq $udom) {
                    655: 	  my $idlist=join('&',@ids);
                    656:           $idlist=~tr/A-Z/a-z/; 
                    657: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    658:           my @answer=();
1.76      www       659:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       660: 	      @answer=split(/\&/,$reply);
                    661:           }                    ;
                    662:           my $i;
                    663:           for ($i=0;$i<=$#ids;$i++) {
                    664:               if ($answer[$i]) {
                    665: 		  $returnhash{$ids[$i]}=$answer[$i];
                    666:               } 
                    667:           }
                    668:        }
                    669:     }    
                    670:     return %returnhash;
                    671: }
                    672: 
                    673: # ------------------------------------- Find the IDs behind a list of usernames
                    674: 
                    675: sub idrget {
                    676:     my ($udom,@unames)=@_;
                    677:     my %returnhash=();
1.191     harris41  678:     foreach (@unames) {
1.70      www       679:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  680:     }
1.70      www       681:     return %returnhash;
                    682: }
                    683: 
                    684: # ------------------------------- Store away a list of names and associated IDs
                    685: 
                    686: sub idput {
                    687:     my ($udom,%ids)=@_;
                    688:     my %servers=();
1.191     harris41  689:     foreach (keys %ids) {
1.487     albertel  690: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       691:         my $uhom=&homeserver($_,$udom);
                    692:         if ($uhom ne 'no_host') {
                    693:             my $id=&escape($ids{$_});
                    694:             $id=~tr/A-Z/a-z/;
                    695:             my $unam=&escape($_);
                    696: 	    if ($servers{$uhom}) {
                    697: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    698:             } else {
                    699:                 $servers{$uhom}=$id.'='.$unam;
                    700:             }
                    701:         }
1.191     harris41  702:     }
                    703:     foreach (keys %servers) {
1.70      www       704:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  705:     }
1.344     www       706: }
                    707: 
                    708: # --------------------------------------------------- Assign a key to a student
                    709: 
                    710: sub assign_access_key {
1.364     www       711: #
                    712: # a valid key looks like uname:udom#comments
                    713: # comments are being appended
                    714: #
1.498     www       715:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    716:     $kdom=
1.620     albertel  717:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       718:     $knum=
1.620     albertel  719:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       720:     $cdom=
1.620     albertel  721:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       722:     $cnum=
1.620     albertel  723:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    724:     $udom=$env{'user.name'} unless (defined($udom));
                    725:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       726:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       727:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  728:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       729:                                                   # assigned to this person
                    730:                                                   # - this should not happen,
1.345     www       731:                                                   # unless something went wrong
                    732:                                                   # the first time around
                    733: # ready to assign
1.364     www       734:         $logentry=$1.'; '.$logentry;
1.496     www       735:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       736:                                                  $kdom,$knum) eq 'ok') {
1.345     www       737: # key now belongs to user
1.346     www       738: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       739:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    740:                 &appenv('environment.'.$envkey => $ckey);
                    741:                 return 'ok';
                    742:             } else {
                    743:                 return 
                    744:   'error: Count not permanently assign key, will need to be re-entered later.';
                    745: 	    }
                    746:         } else {
                    747:             return 'error: Could not assign key, try again later.';
                    748:         }
1.364     www       749:     } elsif (!$existing{$ckey}) {
1.345     www       750: # the key does not exist
                    751: 	return 'error: The key does not exist';
                    752:     } else {
                    753: # the key is somebody else's
                    754: 	return 'error: The key is already in use';
                    755:     }
1.344     www       756: }
                    757: 
1.364     www       758: # ------------------------------------------ put an additional comment on a key
                    759: 
                    760: sub comment_access_key {
                    761: #
                    762: # a valid key looks like uname:udom#comments
                    763: # comments are being appended
                    764: #
                    765:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    766:     $cdom=
1.620     albertel  767:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       768:     $cnum=
1.620     albertel  769:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       770:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    771:     if ($existing{$ckey}) {
                    772:         $existing{$ckey}.='; '.$logentry;
                    773: # ready to assign
1.367     www       774:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       775:                                                  $cdom,$cnum) eq 'ok') {
                    776: 	    return 'ok';
                    777:         } else {
                    778: 	    return 'error: Count not store comment.';
                    779:         }
                    780:     } else {
                    781: # the key does not exist
                    782: 	return 'error: The key does not exist';
                    783:     }
                    784: }
                    785: 
1.344     www       786: # ------------------------------------------------------ Generate a set of keys
                    787: 
                    788: sub generate_access_keys {
1.364     www       789:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       790:     $cdom=
1.620     albertel  791:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       792:     $cnum=
1.620     albertel  793:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       794:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       795:     unless (($cdom) && ($cnum)) { return 0; }
                    796:     if ($number>10000) { return 0; }
                    797:     sleep(2); # make sure don't get same seed twice
                    798:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    799:     my $total=0;
                    800:     for (my $i=1;$i<=$number;$i++) {
                    801:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    802:                   sprintf("%lx",int(100000*rand)).'-'.
                    803:                   sprintf("%lx",int(100000*rand));
                    804:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    805:        $newkey=~s/0/h/g; # and also 0 and O
                    806:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    807:        if ($existing{$newkey}) {
                    808:            $i--;
                    809:        } else {
1.364     www       810: 	  if (&put('accesskeys',
                    811:               { $newkey => '# generated '.localtime().
1.620     albertel  812:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       813:                            '; '.$logentry },
                    814: 		   $cdom,$cnum) eq 'ok') {
1.344     www       815:               $total++;
                    816: 	  }
                    817:        }
                    818:     }
1.620     albertel  819:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       820:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    821:     return $total;
                    822: }
                    823: 
                    824: # ------------------------------------------------------- Validate an accesskey
                    825: 
                    826: sub validate_access_key {
                    827:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    828:     $cdom=
1.620     albertel  829:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       830:     $cnum=
1.620     albertel  831:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    832:     $udom=$env{'user.domain'} unless (defined($udom));
                    833:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       834:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  835:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       836: }
                    837: 
                    838: # ------------------------------------- Find the section of student in a course
1.652     albertel  839: sub devalidate_getsection_cache {
                    840:     my ($udom,$unam,$courseid)=@_;
                    841:     $courseid=~s/\_/\//g;
                    842:     $courseid=~s/^(\w)/\/$1/;
                    843:     my $hashid="$udom:$unam:$courseid";
                    844:     &devalidate_cache_new('getsection',$hashid);
                    845: }
1.298     matthew   846: 
                    847: sub getsection {
                    848:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  849:     my $cachetime=1800;
1.298     matthew   850:     $courseid=~s/\_/\//g;
                    851:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  852: 
                    853:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  854:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  855:     if (defined($cached)) { return $result; }
                    856: 
1.298     matthew   857:     my %Pending; 
                    858:     my %Expired;
                    859:     #
                    860:     # Each role can either have not started yet (pending), be active, 
                    861:     #    or have expired.
                    862:     #
                    863:     # If there is an active role, we are done.
                    864:     #
                    865:     # If there is more than one role which has not started yet, 
                    866:     #     choose the one which will start sooner
                    867:     # If there is one role which has not started yet, return it.
                    868:     #
                    869:     # If there is more than one expired role, choose the one which ended last.
                    870:     # If there is a role which has expired, return it.
                    871:     #
                    872:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    873:                         &homeserver($unam,$udom)))) {
                    874:         my ($key,$value)=split(/\=/,$_);
                    875:         $key=&unescape($key);
1.479     albertel  876:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   877:         my $section=$1;
                    878:         if ($key eq $courseid.'_st') { $section=''; }
                    879:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    880:         my $now=time;
1.548     albertel  881:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   882:             $Expired{$end}=$section;
                    883:             next;
                    884:         }
1.548     albertel  885:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   886:             $Pending{$start}=$section;
                    887:             next;
                    888:         }
1.599     albertel  889:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   890:     }
                    891:     #
                    892:     # Presumedly there will be few matching roles from the above
                    893:     # loop and the sorting time will be negligible.
                    894:     if (scalar(keys(%Pending))) {
                    895:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  896:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   897:     } 
                    898:     if (scalar(keys(%Expired))) {
                    899:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    900:         my $time = pop(@sorted);
1.599     albertel  901:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   902:     }
1.599     albertel  903:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   904: }
1.70      www       905: 
1.599     albertel  906: sub save_cache {
                    907:     &purge_remembered();
1.722     albertel  908:     #&Apache::loncommon::validate_page();
1.620     albertel  909:     undef(%env);
1.780     albertel  910:     undef($env_loaded);
1.599     albertel  911: }
1.452     albertel  912: 
1.599     albertel  913: my $to_remember=-1;
                    914: my %remembered;
                    915: my %accessed;
                    916: my $kicks=0;
                    917: my $hits=0;
                    918: sub devalidate_cache_new {
                    919:     my ($name,$id,$debug) = @_;
                    920:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    921:     $id=&escape($name.':'.$id);
                    922:     $memcache->delete($id);
                    923:     delete($remembered{$id});
                    924:     delete($accessed{$id});
                    925: }
                    926: 
                    927: sub is_cached_new {
                    928:     my ($name,$id,$debug) = @_;
                    929:     $id=&escape($name.':'.$id);
                    930:     if (exists($remembered{$id})) {
                    931: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    932: 	$accessed{$id}=[&gettimeofday()];
                    933: 	$hits++;
                    934: 	return ($remembered{$id},1);
                    935:     }
                    936:     my $value = $memcache->get($id);
                    937:     if (!(defined($value))) {
                    938: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  939: 	return (undef,undef);
1.416     albertel  940:     }
1.599     albertel  941:     if ($value eq '__undef__') {
                    942: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    943: 	$value=undef;
                    944:     }
                    945:     &make_room($id,$value,$debug);
                    946:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    947:     return ($value,1);
                    948: }
                    949: 
                    950: sub do_cache_new {
                    951:     my ($name,$id,$value,$time,$debug) = @_;
                    952:     $id=&escape($name.':'.$id);
                    953:     my $setvalue=$value;
                    954:     if (!defined($setvalue)) {
                    955: 	$setvalue='__undef__';
                    956:     }
1.623     albertel  957:     if (!defined($time) ) {
                    958: 	$time=600;
                    959:     }
1.599     albertel  960:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  961:     $memcache->set($id,$setvalue,$time);
                    962:     # need to make a copy of $value
                    963:     #&make_room($id,$value,$debug);
1.599     albertel  964:     return $value;
                    965: }
                    966: 
                    967: sub make_room {
                    968:     my ($id,$value,$debug)=@_;
                    969:     $remembered{$id}=$value;
                    970:     if ($to_remember<0) { return; }
                    971:     $accessed{$id}=[&gettimeofday()];
                    972:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    973:     my $to_kick;
                    974:     my $max_time=0;
                    975:     foreach my $other (keys(%accessed)) {
                    976: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    977: 	    $to_kick=$other;
                    978: 	    $max_time=&tv_interval($accessed{$other});
                    979: 	}
                    980:     }
                    981:     delete($remembered{$to_kick});
                    982:     delete($accessed{$to_kick});
                    983:     $kicks++;
                    984:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  985:     return;
                    986: }
                    987: 
1.599     albertel  988: sub purge_remembered {
1.604     albertel  989:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    990:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  991:     undef(%remembered);
                    992:     undef(%accessed);
1.428     albertel  993: }
1.70      www       994: # ------------------------------------- Read an entry from a user's environment
                    995: 
                    996: sub userenvironment {
                    997:     my ($udom,$unam,@what)=@_;
                    998:     my %returnhash=();
                    999:     my @answer=split(/\&/,
                   1000:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1001:                       &homeserver($unam,$udom)));
                   1002:     my $i;
                   1003:     for ($i=0;$i<=$#what;$i++) {
                   1004: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1005:     }
                   1006:     return %returnhash;
1.1       albertel 1007: }
                   1008: 
1.617     albertel 1009: # ---------------------------------------------------------- Get a studentphoto
                   1010: sub studentphoto {
                   1011:     my ($udom,$unam,$ext) = @_;
                   1012:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1013:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1014:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1015:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1016:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1017:             } else {
                   1018:                 my ($result,$perm_reqd)=
1.707     albertel 1019: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1020:                 if ($result eq 'ok') {
                   1021:                     if (!($perm_reqd eq 'yes')) {
                   1022:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1023:                     }
                   1024:                 }
                   1025:             }
                   1026:         }
                   1027:     } else {
                   1028:         my ($result,$perm_reqd) = 
1.707     albertel 1029: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1030:         if ($result eq 'ok') {
                   1031:             if (!($perm_reqd eq 'yes')) {
                   1032:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1033:             }
                   1034:         }
                   1035:     }
                   1036:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1037: }
                   1038: 
                   1039: sub retrievestudentphoto {
                   1040:     my ($udom,$unam,$ext,$type) = @_;
                   1041:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1042:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1043:     if ($ret eq 'ok') {
                   1044:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1045:         if ($type eq 'thumbnail') {
                   1046:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1047:         }
                   1048:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1049:         return $tokenurl;
                   1050:     } else {
                   1051:         if ($type eq 'thumbnail') {
                   1052:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1053:         } else { 
                   1054:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1055:         }
1.617     albertel 1056:     }
                   1057: }
                   1058: 
1.263     www      1059: # -------------------------------------------------------------------- New chat
                   1060: 
                   1061: sub chatsend {
1.724     raeburn  1062:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1063:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1064:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1065:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1066:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1067: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1068: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1069: }
                   1070: 
                   1071: # ------------------------------------------ Find current version of a resource
                   1072: 
                   1073: sub getversion {
                   1074:     my $fname=&clutter(shift);
                   1075:     unless ($fname=~/^\/res\//) { return -1; }
                   1076:     return &currentversion(&filelocation('',$fname));
                   1077: }
                   1078: 
                   1079: sub currentversion {
                   1080:     my $fname=shift;
1.599     albertel 1081:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1082:     if (defined($cached)) { return $result; }
1.292     www      1083:     my $author=$fname;
                   1084:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1085:     my ($udom,$uname)=split(/\//,$author);
                   1086:     my $home=homeserver($uname,$udom);
                   1087:     if ($home eq 'no_host') { 
                   1088:         return -1; 
                   1089:     }
                   1090:     my $answer=reply("currentversion:$fname",$home);
                   1091:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1092: 	return -1;
                   1093:     }
1.599     albertel 1094:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1095: }
                   1096: 
1.1       albertel 1097: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1098: 
1.1       albertel 1099: sub subscribe {
                   1100:     my $fname=shift;
1.761     raeburn  1101:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1102:     $fname=~s/[\n\r]//g;
1.1       albertel 1103:     my $author=$fname;
                   1104:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1105:     my ($udom,$uname)=split(/\//,$author);
                   1106:     my $home=homeserver($uname,$udom);
1.335     albertel 1107:     if ($home eq 'no_host') {
                   1108:         return 'not_found';
1.1       albertel 1109:     }
                   1110:     my $answer=reply("sub:$fname",$home);
1.64      www      1111:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1112: 	$answer.=' by '.$home;
                   1113:     }
1.1       albertel 1114:     return $answer;
                   1115: }
                   1116:     
1.8       www      1117: # -------------------------------------------------------------- Replicate file
                   1118: 
                   1119: sub repcopy {
                   1120:     my $filename=shift;
1.23      www      1121:     $filename=~s/\/+/\//g;
1.607     raeburn  1122:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1123:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1124:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1125: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1126: 	return &repcopy_userfile($filename);
                   1127:     }
1.532     albertel 1128:     $filename=~s/[\n\r]//g;
1.8       www      1129:     my $transname="$filename.in.transfer";
1.607     raeburn  1130:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1131:     my $remoteurl=subscribe($filename);
1.64      www      1132:     if ($remoteurl =~ /^con_lost by/) {
                   1133: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1134:            return 'unavailable';
1.8       www      1135:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1136: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1137: 	   return 'not_found';
1.64      www      1138:     } elsif ($remoteurl =~ /^rejected by/) {
                   1139: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1140:            return 'forbidden';
1.20      www      1141:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1142:            return 'ok';
1.8       www      1143:     } else {
1.290     www      1144:         my $author=$filename;
                   1145:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1146:         my ($udom,$uname)=split(/\//,$author);
                   1147:         my $home=homeserver($uname,$udom);
                   1148:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1149:            my @parts=split(/\//,$filename);
                   1150:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1151:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1152:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1153: 	       return 'bad_request';
1.8       www      1154:            }
                   1155:            my $count;
                   1156:            for ($count=5;$count<$#parts;$count++) {
                   1157:                $path.="/$parts[$count]";
                   1158:                if ((-e $path)!=1) {
                   1159: 		   mkdir($path,0777);
                   1160:                }
                   1161:            }
                   1162:            my $ua=new LWP::UserAgent;
                   1163:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1164:            my $response=$ua->request($request,$transname);
                   1165:            if ($response->is_error()) {
                   1166: 	       unlink($transname);
                   1167:                my $message=$response->status_line;
1.672     albertel 1168:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1169:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1170:                return 'unavailable';
1.8       www      1171:            } else {
1.16      www      1172: 	       if ($remoteurl!~/\.meta$/) {
                   1173:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1174:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1175:                   if ($mresponse->is_error()) {
                   1176: 		      unlink($filename.'.meta');
                   1177:                       &logthis(
1.672     albertel 1178:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1179:                   }
                   1180: 	       }
1.8       www      1181:                rename($transname,$filename);
1.607     raeburn  1182:                return 'ok';
1.8       www      1183:            }
1.290     www      1184:        }
1.8       www      1185:     }
1.330     www      1186: }
                   1187: 
                   1188: # ------------------------------------------------ Get server side include body
                   1189: sub ssi_body {
1.381     albertel 1190:     my ($filelink,%form)=@_;
1.606     matthew  1191:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1192:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1193:     }
1.330     www      1194:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1195:                                      &ssi($filelink,%form));
1.778     albertel 1196:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1197:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1198:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1199:     return $output;
1.8       www      1200: }
                   1201: 
1.15      www      1202: # --------------------------------------------------------- Server Side Include
                   1203: 
1.782     albertel 1204: sub absolute_url {
                   1205:     my ($host_name) = @_;
                   1206:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1207:     if ($host_name eq '') {
                   1208: 	$host_name = $ENV{'SERVER_NAME'};
                   1209:     }
                   1210:     return $protocol.$host_name;
                   1211: }
                   1212: 
1.15      www      1213: sub ssi {
                   1214: 
1.23      www      1215:     my ($fn,%form)=@_;
1.15      www      1216: 
                   1217:     my $ua=new LWP::UserAgent;
1.23      www      1218:     
                   1219:     my $request;
1.711     albertel 1220: 
                   1221:     $form{'no_update_last_known'}=1;
                   1222: 
1.23      www      1223:     if (%form) {
1.782     albertel 1224:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1225:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1226:     } else {
1.782     albertel 1227:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1228:     }
                   1229: 
1.15      www      1230:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1231:     my $response=$ua->request($request);
                   1232: 
1.324     www      1233:     return $response->content;
                   1234: }
                   1235: 
                   1236: sub externalssi {
                   1237:     my ($url)=@_;
                   1238:     my $ua=new LWP::UserAgent;
                   1239:     my $request=new HTTP::Request('GET',$url);
                   1240:     my $response=$ua->request($request);
1.15      www      1241:     return $response->content;
                   1242: }
1.254     www      1243: 
1.492     albertel 1244: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1245: 
                   1246: sub allowuploaded {
                   1247:     my ($srcurl,$url)=@_;
                   1248:     $url=&clutter(&declutter($url));
                   1249:     my $dir=$url;
                   1250:     $dir=~s/\/[^\/]+$//;
                   1251:     my %httpref=();
                   1252:     my $httpurl=&hreflocation('',$url);
                   1253:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1254:     &Apache::lonnet::appenv(%httpref);
1.254     www      1255: }
1.477     raeburn  1256: 
1.478     albertel 1257: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1258: # input: action, courseID, current domain, intended
1.637     raeburn  1259: #        path to file, source of file, instruction to parse file for objects,
                   1260: #        ref to hash for embedded objects,
                   1261: #        ref to hash for codebase of java objects.
                   1262: #
1.485     raeburn  1263: # output: url to file (if action was uploaddoc), 
                   1264: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1265: #
1.478     albertel 1266: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1267: # course.
1.477     raeburn  1268: #
1.478     albertel 1269: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1270: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1271: #          course's home server.
1.477     raeburn  1272: #
1.478     albertel 1273: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1274: #          be copied from $source (current location) to 
                   1275: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1276: #         and will then be copied to
                   1277: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1278: #         course's home server.
1.485     raeburn  1279: #
1.481     raeburn  1280: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1281: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1282: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1283: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1284: #         in course's home server.
1.637     raeburn  1285: #
1.477     raeburn  1286: 
                   1287: sub process_coursefile {
1.638     albertel 1288:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1289:     my $fetchresult;
1.638     albertel 1290:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1291:     if ($action eq 'propagate') {
1.638     albertel 1292:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1293: 			     $home);
1.481     raeburn  1294:     } else {
1.477     raeburn  1295:         my $fpath = '';
                   1296:         my $fname = $file;
1.478     albertel 1297:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1298:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1299:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1300:         if ($action eq 'copy') {
                   1301:             if ($source eq '') {
                   1302:                 $fetchresult = 'no source file';
                   1303:                 return $fetchresult;
                   1304:             } else {
                   1305:                 my $destination = $filepath.'/'.$fname;
                   1306:                 rename($source,$destination);
                   1307:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1308:                                  $home);
1.481     raeburn  1309:             }
                   1310:         } elsif ($action eq 'uploaddoc') {
                   1311:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1312:             print $fh $env{'form.'.$source};
1.481     raeburn  1313:             close($fh);
1.637     raeburn  1314:             if ($parser eq 'parse') {
                   1315:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1316:                 unless ($parse_result eq 'ok') {
                   1317:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1318:                 }
                   1319:             }
1.477     raeburn  1320:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1321:                                  $home);
1.481     raeburn  1322:             if ($fetchresult eq 'ok') {
                   1323:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1324:             } else {
                   1325:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1326:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1327:                 return '/adm/notfound.html';
                   1328:             }
1.477     raeburn  1329:         }
                   1330:     }
1.485     raeburn  1331:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1332:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1333:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1334:     }
                   1335:     return $fetchresult;
                   1336: }
                   1337: 
1.637     raeburn  1338: sub build_filepath {
                   1339:     my ($fpath) = @_;
                   1340:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1341:     unless ($fpath eq '') {
                   1342:         my @parts=split('/',$fpath);
                   1343:         foreach my $part (@parts) {
                   1344:             $filepath.= '/'.$part;
                   1345:             if ((-e $filepath)!=1) {
                   1346:                 mkdir($filepath,0777);
                   1347:             }
                   1348:         }
                   1349:     }
                   1350:     return $filepath;
                   1351: }
                   1352: 
                   1353: sub store_edited_file {
1.638     albertel 1354:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1355:     my $file = $primary_url;
                   1356:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1357:     my $fpath = '';
                   1358:     my $fname = $file;
                   1359:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1360:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1361:     my $filepath = &build_filepath($fpath);
                   1362:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1363:     print $fh $content;
                   1364:     close($fh);
1.638     albertel 1365:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1366:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1367: 			  $home);
1.637     raeburn  1368:     if ($$fetchresult eq 'ok') {
                   1369:         return '/uploaded/'.$fpath.'/'.$fname;
                   1370:     } else {
1.638     albertel 1371:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1372: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1373:         return '/adm/notfound.html';
                   1374:     }
                   1375: }
                   1376: 
1.531     albertel 1377: sub clean_filename {
                   1378:     my ($fname)=@_;
1.315     www      1379: # Replace Windows backslashes by forward slashes
1.257     www      1380:     $fname=~s/\\/\//g;
1.315     www      1381: # Get rid of everything but the actual filename
1.257     www      1382:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1383: # Replace spaces by underscores
                   1384:     $fname=~s/\s+/\_/g;
                   1385: # Replace all other weird characters by nothing
1.317     www      1386:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1387: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1388: # numbers
                   1389:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1390:     return $fname;
                   1391: }
                   1392: 
1.608     albertel 1393: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1394: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1395: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1396: #        $coursedoc - if true up to the current course
                   1397: #                     if false
                   1398: #        $subdir - directory in userfile to store the file into
                   1399: #        $parser, $allfiles, $codebase - unknown
                   1400: #
                   1401: # output: url of file in userspace, or error: <message> 
                   1402: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1403: 
                   1404: 
1.531     albertel 1405: sub userfileupload {
1.719     banghart 1406:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1407:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1408:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1409:     $fname=&clean_filename($fname);
1.315     www      1410: # See if there is anything left
1.257     www      1411:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1412:     chop($env{'form.'.$formname});
1.523     raeburn  1413:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1414:         my $now = time;
                   1415:         my $filepath = 'tmp/helprequests/'.$now;
                   1416:         my @parts=split(/\//,$filepath);
                   1417:         my $fullpath = $perlvar{'lonDaemons'};
                   1418:         for (my $i=0;$i<@parts;$i++) {
                   1419:             $fullpath .= '/'.$parts[$i];
                   1420:             if ((-e $fullpath)!=1) {
                   1421:                 mkdir($fullpath,0777);
                   1422:             }
                   1423:         }
                   1424:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1425:         print $fh $env{'form.'.$formname};
1.523     raeburn  1426:         close($fh);
1.741     raeburn  1427:         return $fullpath.'/'.$fname;
                   1428:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1429:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1430:                        '_'.$env{'user.domain'}.'/pending';
                   1431:         my @parts=split(/\//,$filepath);
                   1432:         my $fullpath = $perlvar{'lonDaemons'};
                   1433:         for (my $i=0;$i<@parts;$i++) {
                   1434:             $fullpath .= '/'.$parts[$i];
                   1435:             if ((-e $fullpath)!=1) {
                   1436:                 mkdir($fullpath,0777);
                   1437:             }
                   1438:         }
                   1439:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1440:         print $fh $env{'form.'.$formname};
                   1441:         close($fh);
                   1442:         return $fullpath.'/'.$fname;
1.523     raeburn  1443:     }
1.719     banghart 1444:     
1.258     www      1445: # Create the directory if not present
1.493     albertel 1446:     $fname="$subdir/$fname";
1.259     www      1447:     if ($coursedoc) {
1.638     albertel 1448: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1449: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1450:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1451:             return &finishuserfileupload($docuname,$docudom,
                   1452: 					 $formname,$fname,$parser,$allfiles,
                   1453: 					 $codebase);
1.481     raeburn  1454:         } else {
1.620     albertel 1455:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1456:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1457: 				       $fname,$formname,$parser,
                   1458: 				       $allfiles,$codebase);
1.481     raeburn  1459:         }
1.719     banghart 1460:     } elsif (defined($destuname)) {
                   1461:         my $docuname=$destuname;
                   1462:         my $docudom=$destudom;
                   1463: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1464: 				     $fname,$parser,$allfiles,$codebase);
                   1465:         
1.259     www      1466:     } else {
1.638     albertel 1467:         my $docuname=$env{'user.name'};
                   1468:         my $docudom=$env{'user.domain'};
1.714     raeburn  1469:         if (exists($env{'form.group'})) {
                   1470:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1471:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1472:         }
1.638     albertel 1473: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1474: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1475:     }
1.271     www      1476: }
                   1477: 
                   1478: sub finishuserfileupload {
1.638     albertel 1479:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1480:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1481:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1482:     my ($fnamepath,$file);
                   1483:     $file=$fname;
                   1484:     if ($fname=~m|/|) {
                   1485:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1486: 	$path.=$fnamepath.'/';
                   1487:     }
1.259     www      1488:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1489:     my $count;
                   1490:     for ($count=4;$count<=$#parts;$count++) {
                   1491:         $filepath.="/$parts[$count]";
                   1492:         if ((-e $filepath)!=1) {
                   1493: 	    mkdir($filepath,0777);
                   1494:         }
                   1495:     }
                   1496: # Save the file
                   1497:     {
1.701     albertel 1498: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1499: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1500: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1501: 	    return '/adm/notfound.html';
                   1502: 	}
                   1503: 	if (!print FH ($env{'form.'.$formname})) {
                   1504: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1505: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1506: 	    return '/adm/notfound.html';
                   1507: 	}
1.570     albertel 1508: 	close(FH);
1.258     www      1509:     }
1.637     raeburn  1510:     if ($parser eq 'parse') {
1.638     albertel 1511:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1512: 						   $codebase);
1.637     raeburn  1513:         unless ($parse_result eq 'ok') {
1.638     albertel 1514:             &logthis('Failed to parse '.$filepath.$file.
                   1515: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1516:         }
                   1517:     }
1.259     www      1518: # Notify homeserver to grep it
                   1519: #
1.638     albertel 1520:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1521:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1522:     if ($fetchresult eq 'ok') {
1.259     www      1523: #
1.258     www      1524: # Return the URL to it
1.494     albertel 1525:         return '/uploaded/'.$path.$file;
1.263     www      1526:     } else {
1.494     albertel 1527:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1528: 		 ': '.$fetchresult);
1.263     www      1529:         return '/adm/notfound.html';
                   1530:     }    
1.493     albertel 1531: }
                   1532: 
1.637     raeburn  1533: sub extract_embedded_items {
1.648     raeburn  1534:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1535:     my @state = ();
                   1536:     my %javafiles = (
                   1537:                       codebase => '',
                   1538:                       code => '',
                   1539:                       archive => ''
                   1540:                     );
                   1541:     my %mediafiles = (
                   1542:                       src => '',
                   1543:                       movie => '',
                   1544:                      );
1.648     raeburn  1545:     my $p;
                   1546:     if ($content) {
                   1547:         $p = HTML::LCParser->new($content);
                   1548:     } else {
                   1549:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1550:     }
1.641     albertel 1551:     while (my $t=$p->get_token()) {
1.640     albertel 1552: 	if ($t->[0] eq 'S') {
                   1553: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1554: 	    push (@state, $tagname);
1.648     raeburn  1555:             if (lc($tagname) eq 'allow') {
                   1556:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1557:             }
1.640     albertel 1558: 	    if (lc($tagname) eq 'img') {
                   1559: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1560: 	    }
1.645     raeburn  1561:             if (lc($tagname) eq 'script') {
                   1562:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1563:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1564:                 } else {
                   1565:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1566:                 }
                   1567:             }
                   1568:             if (lc($tagname) eq 'link') {
                   1569:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1570:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1571:                 }
                   1572:             }
1.640     albertel 1573: 	    if (lc($tagname) eq 'object' ||
                   1574: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1575: 		foreach my $item (keys(%javafiles)) {
                   1576: 		    $javafiles{$item} = '';
                   1577: 		}
                   1578: 	    }
                   1579: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1580: 		my $name = lc($attr->{'name'});
                   1581: 		foreach my $item (keys(%javafiles)) {
                   1582: 		    if ($name eq $item) {
                   1583: 			$javafiles{$item} = $attr->{'value'};
                   1584: 			last;
                   1585: 		    }
                   1586: 		}
                   1587: 		foreach my $item (keys(%mediafiles)) {
                   1588: 		    if ($name eq $item) {
                   1589: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1590: 			last;
                   1591: 		    }
                   1592: 		}
                   1593: 	    }
                   1594: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1595: 		foreach my $item (keys(%javafiles)) {
                   1596: 		    if ($attr->{$item}) {
                   1597: 			$javafiles{$item} = $attr->{$item};
                   1598: 			last;
                   1599: 		    }
                   1600: 		}
                   1601: 		foreach my $item (keys(%mediafiles)) {
                   1602: 		    if ($attr->{$item}) {
                   1603: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1604: 			last;
                   1605: 		    }
                   1606: 		}
                   1607: 	    }
                   1608: 	} elsif ($t->[0] eq 'E') {
                   1609: 	    my ($tagname) = ($t->[1]);
                   1610: 	    if ($javafiles{'codebase'} ne '') {
                   1611: 		$javafiles{'codebase'} .= '/';
                   1612: 	    }  
                   1613: 	    if (lc($tagname) eq 'applet' ||
                   1614: 		lc($tagname) eq 'object' ||
                   1615: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1616: 		) {
                   1617: 		foreach my $item (keys(%javafiles)) {
                   1618: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1619: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1620: 			&add_filetype($allfiles,$file,$item);
                   1621: 		    }
                   1622: 		}
                   1623: 	    } 
                   1624: 	    pop @state;
                   1625: 	}
                   1626:     }
1.637     raeburn  1627:     return 'ok';
                   1628: }
                   1629: 
1.639     albertel 1630: sub add_filetype {
                   1631:     my ($allfiles,$file,$type)=@_;
                   1632:     if (exists($allfiles->{$file})) {
                   1633: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1634: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1635: 	}
                   1636:     } else {
                   1637: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1638:     }
                   1639: }
                   1640: 
1.493     albertel 1641: sub removeuploadedurl {
                   1642:     my ($url)=@_;
                   1643:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1644:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1645: }
                   1646: 
                   1647: sub removeuserfile {
                   1648:     my ($docuname,$docudom,$fname)=@_;
                   1649:     my $home=&homeserver($docuname,$docudom);
                   1650:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1651: }
1.15      www      1652: 
1.530     albertel 1653: sub mkdiruserfile {
                   1654:     my ($docuname,$docudom,$dir)=@_;
                   1655:     my $home=&homeserver($docuname,$docudom);
                   1656:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1657: }
                   1658: 
1.531     albertel 1659: sub renameuserfile {
                   1660:     my ($docuname,$docudom,$old,$new)=@_;
                   1661:     my $home=&homeserver($docuname,$docudom);
                   1662:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1663: 		  &escape("$new"),$home);
                   1664: }
                   1665: 
1.14      www      1666: # ------------------------------------------------------------------------- Log
                   1667: 
                   1668: sub log {
                   1669:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1670:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1671: }
                   1672: 
                   1673: # ------------------------------------------------------------------ Course Log
1.352     www      1674: #
                   1675: # This routine flushes several buffers of non-mission-critical nature
                   1676: #
1.157     www      1677: 
                   1678: sub flushcourselogs {
1.352     www      1679:     &logthis('Flushing log buffers');
                   1680: #
                   1681: # course logs
                   1682: # This is a log of all transactions in a course, which can be used
                   1683: # for data mining purposes
                   1684: #
                   1685: # It also collects the courseid database, which lists last transaction
                   1686: # times and course titles for all courseids
                   1687: #
                   1688:     my %courseidbuffer=();
1.191     harris41 1689:     foreach (keys %courselogs) {
1.157     www      1690:         my $crsid=$_;
1.352     www      1691:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1692: 		          &escape($courselogs{$crsid}),
                   1693: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1694: 	    delete $courselogs{$crsid};
                   1695:         } else {
                   1696:             &logthis('Failed to flush log buffer for '.$crsid);
                   1697:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1698:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1699:                         " exceeded maximum size, deleting.</font>");
                   1700:                delete $courselogs{$crsid};
                   1701:             }
1.352     www      1702:         }
                   1703:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1704:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1705: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1706:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1707:         } else {
                   1708:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1709: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1710:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1711:         }
1.191     harris41 1712:     }
1.352     www      1713: #
                   1714: # Write course id database (reverse lookup) to homeserver of courses 
                   1715: # Is used in pickcourse
                   1716: #
                   1717:     foreach (keys %courseidbuffer) {
1.353     www      1718:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1719:     }
                   1720: #
                   1721: # File accesses
                   1722: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1723: #
1.449     matthew  1724:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1725:         if ($entry =~ /___count$/) {
                   1726:             my ($dom,$name);
                   1727:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1728:             if (! defined($dom) || $dom eq '' || 
                   1729:                 ! defined($name) || $name eq '') {
1.620     albertel 1730:                 my $cid = $env{'request.course.id'};
                   1731:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1732:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1733:             }
1.450     matthew  1734:             my $value = $accesshash{$entry};
                   1735:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1736:             my %temphash=($url => $value);
1.449     matthew  1737:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1738:             if ($result eq 'ok') {
                   1739:                 delete $accesshash{$entry};
                   1740:             } elsif ($result eq 'unknown_cmd') {
                   1741:                 # Target server has old code running on it.
1.450     matthew  1742:                 my %temphash=($entry => $value);
1.449     matthew  1743:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1744:                     delete $accesshash{$entry};
                   1745:                 }
                   1746:             }
                   1747:         } else {
1.458     matthew  1748:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1749:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1750:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1751:                 delete $accesshash{$entry};
                   1752:             }
1.185     www      1753:         }
1.191     harris41 1754:     }
1.352     www      1755: #
                   1756: # Roles
                   1757: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1758: #
1.349     www      1759:     foreach (keys %userrolehash) {
                   1760:         my $entry=$_;
1.351     www      1761:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1762: 	    split(/\:/,$entry);
                   1763:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1764:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1765:                 $rudom,$runame) eq 'ok') {
                   1766: 	    delete $userrolehash{$entry};
                   1767:         }
                   1768:     }
1.662     raeburn  1769: #
                   1770: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1771: #
                   1772:     my %domrolebuffer = ();
                   1773:     foreach my $entry (keys %domainrolehash) {
                   1774:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1775:         if ($domrolebuffer{$rudom}) {
                   1776:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1777:                       '='.&escape($domainrolehash{$entry});
                   1778:         } else {
                   1779:             $domrolebuffer{$rudom}.=&escape($entry).
                   1780:                       '='.&escape($domainrolehash{$entry});
                   1781:         }
                   1782:         delete $domainrolehash{$entry};
                   1783:     }
                   1784:     foreach my $dom (keys(%domrolebuffer)) {
                   1785:         foreach my $tryserver (keys %libserv) {
                   1786:             if ($hostdom{$tryserver} eq $dom) {
                   1787:                 unless (&reply('domroleput:'.$dom.':'.
                   1788:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1789:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1790:                 }
                   1791:             }
                   1792:         }
                   1793:     }
1.186     www      1794:     $dumpcount++;
1.157     www      1795: }
                   1796: 
                   1797: sub courselog {
                   1798:     my $what=shift;
1.158     www      1799:     $what=time.':'.$what;
1.620     albertel 1800:     unless ($env{'request.course.id'}) { return ''; }
                   1801:     $coursedombuf{$env{'request.course.id'}}=
                   1802:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1803:     $coursenumbuf{$env{'request.course.id'}}=
                   1804:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1805:     $coursehombuf{$env{'request.course.id'}}=
                   1806:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1807:     $coursedescrbuf{$env{'request.course.id'}}=
                   1808:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1809:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1810:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1811:     $courseownerbuf{$env{'request.course.id'}}=
                   1812:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1813:     $coursetypebuf{$env{'request.course.id'}}=
                   1814:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1815:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1816: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1817:     } else {
1.620     albertel 1818: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1819:     }
1.620     albertel 1820:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1821: 	&flushcourselogs();
                   1822:     }
1.158     www      1823: }
                   1824: 
                   1825: sub courseacclog {
                   1826:     my $fnsymb=shift;
1.620     albertel 1827:     unless ($env{'request.course.id'}) { return ''; }
                   1828:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1829:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1830:         $what.=':POST';
1.583     matthew  1831:         # FIXME: Probably ought to escape things....
1.620     albertel 1832: 	foreach (keys %env) {
1.158     www      1833:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1834: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1835:             }
1.191     harris41 1836:         }
1.583     matthew  1837:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1838:         # FIXME: We should not be depending on a form parameter that someone
                   1839:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1840:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1841:             $what.= ':POST';
                   1842:             # FIXME: Probably ought to escape things....
                   1843:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1844:                                  'crsdiscuss') {
1.620     albertel 1845:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1846:             }
                   1847:         }
1.158     www      1848:     }
                   1849:     &courselog($what);
1.149     www      1850: }
                   1851: 
1.185     www      1852: sub countacc {
                   1853:     my $url=&declutter(shift);
1.458     matthew  1854:     return if (! defined($url) || $url eq '');
1.620     albertel 1855:     unless ($env{'request.course.id'}) { return ''; }
                   1856:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1857:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1858:     $accesshash{$key}++;
1.185     www      1859: }
1.349     www      1860: 
1.361     www      1861: sub linklog {
                   1862:     my ($from,$to)=@_;
                   1863:     $from=&declutter($from);
                   1864:     $to=&declutter($to);
                   1865:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1866:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1867: }
                   1868:   
1.349     www      1869: sub userrolelog {
                   1870:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1871:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1872:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1873:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1874:         ($trole=~/^ta/)) {
1.350     www      1875:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1876:        $userrolehash
                   1877:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1878:                     =$tend.':'.$tstart;
1.662     raeburn  1879:     }
                   1880:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1881:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1882:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1883:         ($trole=~/^sc/)) {
                   1884:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1885:        $domainrolehash
                   1886:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1887:                     = $tend.':'.$tstart;
                   1888:     }
1.351     www      1889: }
                   1890: 
                   1891: sub get_course_adv_roles {
                   1892:     my $cid=shift;
1.620     albertel 1893:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1894:     my %coursehash=&coursedescription($cid);
1.470     www      1895:     my %nothide=();
                   1896:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1897: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1898:     }
1.351     www      1899:     my %returnhash=();
                   1900:     my %dumphash=
                   1901:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1902:     my $now=time;
                   1903:     foreach (keys %dumphash) {
                   1904: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1905:         if (($tstart) && ($tstart<0)) { next; }
                   1906:         if (($tend) && ($tend<$now)) { next; }
                   1907:         if (($tstart) && ($now<$tstart)) { next; }
                   1908:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1909: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1910: 	if ((&privileged($username,$domain)) && 
                   1911: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1912: 	if ($role eq 'cr') { next; }
1.351     www      1913:         my $key=&plaintext($role);
                   1914:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1915:         if ($returnhash{$key}) {
                   1916: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1917:         } else {
                   1918:             $returnhash{$key}=$username.':'.$domain;
                   1919:         }
1.400     www      1920:      }
                   1921:     return %returnhash;
                   1922: }
                   1923: 
                   1924: sub get_my_roles {
                   1925:     my ($uname,$udom)=@_;
1.620     albertel 1926:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1927:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1928:     my %dumphash=
                   1929:             &dump('nohist_userroles',$udom,$uname);
                   1930:     my %returnhash=();
                   1931:     my $now=time;
                   1932:     foreach (keys %dumphash) {
                   1933: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1934:         if (($tstart) && ($tstart<0)) { next; }
                   1935:         if (($tend) && ($tend<$now)) { next; }
                   1936:         if (($tstart) && ($now<$tstart)) { next; }
                   1937:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1938: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1939:      }
                   1940:     return %returnhash;
1.399     www      1941: }
                   1942: 
                   1943: # ----------------------------------------------------- Frontpage Announcements
                   1944: #
                   1945: #
                   1946: 
                   1947: sub postannounce {
                   1948:     my ($server,$text)=@_;
                   1949:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1950:     unless ($text=~/\w/) { $text=''; }
                   1951:     return &reply('setannounce:'.&escape($text),$server);
                   1952: }
                   1953: 
                   1954: sub getannounce {
1.448     albertel 1955: 
                   1956:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1957: 	my $announcement='';
                   1958: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1959: 	close($fh);
1.399     www      1960: 	if ($announcement=~/\w/) { 
                   1961: 	    return 
                   1962:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1963:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1964: 	} else {
                   1965: 	    return '';
                   1966: 	}
                   1967:     } else {
                   1968: 	return '';
                   1969:     }
1.351     www      1970: }
1.353     www      1971: 
                   1972: # ---------------------------------------------------------- Course ID routines
                   1973: # Deal with domain's nohist_courseid.db files
                   1974: #
                   1975: 
                   1976: sub courseidput {
                   1977:     my ($domain,$what,$coursehome)=@_;
                   1978:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1979: }
                   1980: 
                   1981: sub courseiddump {
1.741     raeburn  1982:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1983:     my %returnhash=();
1.355     www      1984:     unless ($domfilter) { $domfilter=''; }
1.353     www      1985:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1986:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1987: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1988: 	        foreach (
                   1989:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1990: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1991:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1992:                                $tryserver))) {
1.506     raeburn  1993: 		    my ($key,$value)=split(/\=/,$_);
                   1994:                     if (($key) && ($value)) {
1.516     raeburn  1995: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1996:                     }
1.353     www      1997:                 }
                   1998:             }
                   1999:         }
                   2000:     }
                   2001:     return %returnhash;
                   2002: }
                   2003: 
1.658     raeburn  2004: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2005: 
                   2006: sub dcmailput {
1.685     raeburn  2007:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2008:     my $status = &Apache::lonnet::critical(
1.740     www      2009:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2010:        &escape($message),$server);
1.662     raeburn  2011:     return $status;
                   2012: }
                   2013: 
1.658     raeburn  2014: sub dcmaildump {
                   2015:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2016:     my %returnhash=();
                   2017:     if (exists($domain_primary{$dom})) {
                   2018:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2019:                                                          &escape($enddate).':';
                   2020: 	my @esc_senders=map { &escape($_)} @$senders;
                   2021: 	$cmd.=&escape(join('&',@esc_senders));
                   2022: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2023:             my ($key,$value) = split(/\=/,$_);
                   2024:             if (($key) && ($value)) {
                   2025:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2026:             }
                   2027:         }
                   2028:     }
                   2029:     return %returnhash;
                   2030: }
1.662     raeburn  2031: # ---------------------------------------------------------- Domain roles
                   2032: 
                   2033: sub get_domain_roles {
                   2034:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2035:     if (undef($startdate) || $startdate eq '') {
                   2036:         $startdate = '.';
                   2037:     }
                   2038:     if (undef($enddate) || $enddate eq '') {
                   2039:         $enddate = '.';
                   2040:     }
                   2041:     my $rolelist = join(':',@{$roles});
                   2042:     my %personnel = ();
                   2043:     foreach my $tryserver (keys(%libserv)) {
                   2044:         if ($hostdom{$tryserver} eq $dom) {
                   2045:             %{$personnel{$tryserver}}=();
                   2046:             foreach (
                   2047:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2048:                    &escape($startdate).':'.&escape($enddate).':'.
                   2049:                    &escape($rolelist), $tryserver))) {
                   2050:                 my($key,$value) = split(/\=/,$_);
                   2051:                 if (($key) && ($value)) {
                   2052:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2053:                 }
                   2054:             }
                   2055:         }
                   2056:     }
                   2057:     return %personnel;
                   2058: }
1.658     raeburn  2059: 
1.149     www      2060: # ----------------------------------------------------------- Check out an item
                   2061: 
1.504     albertel 2062: sub get_first_access {
                   2063:     my ($type,$argsymb)=@_;
1.790   ! albertel 2064:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2065:     if ($argsymb) { $symb=$argsymb; }
                   2066:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2067:     if ($type eq 'map') {
                   2068: 	$res=&symbread($map);
                   2069:     } else {
                   2070: 	$res=$symb;
                   2071:     }
                   2072:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2073:     return $times{"$courseid\0$res"};
1.504     albertel 2074: }
                   2075: 
                   2076: sub set_first_access {
                   2077:     my ($type)=@_;
1.790   ! albertel 2078:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2079:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2080:     if ($type eq 'map') {
                   2081: 	$res=&symbread($map);
                   2082:     } else {
                   2083: 	$res=$symb;
                   2084:     }
                   2085:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2086:     if (!$firstaccess) {
1.588     albertel 2087: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2088:     }
                   2089:     return 'already_set';
1.504     albertel 2090: }
                   2091: 
1.149     www      2092: sub checkout {
                   2093:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2094:     my $now=time;
                   2095:     my $lonhost=$perlvar{'lonHostID'};
                   2096:     my $infostr=&escape(
1.234     www      2097:                  'CHECKOUTTOKEN&'.
1.149     www      2098:                  $tuname.'&'.
                   2099:                  $tudom.'&'.
                   2100:                  $tcrsid.'&'.
                   2101:                  $symb.'&'.
                   2102: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2103:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2104:     if ($token=~/^error\:/) { 
1.672     albertel 2105:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2106:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2107:                  "</font>");
                   2108:         return ''; 
                   2109:     }
                   2110: 
1.149     www      2111:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2112:     $token=~tr/a-z/A-Z/;
                   2113: 
1.153     www      2114:     my %infohash=('resource.0.outtoken' => $token,
                   2115:                   'resource.0.checkouttime' => $now,
                   2116:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2117: 
                   2118:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2119:        return '';
1.151     www      2120:     } else {
1.672     albertel 2121:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2122:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2123:                  "</font>");
1.149     www      2124:     }    
                   2125: 
                   2126:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2127:                          &escape('Checkout '.$infostr.' - '.
                   2128:                                                  $token)) ne 'ok') {
                   2129: 	return '';
1.151     www      2130:     } else {
1.672     albertel 2131:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2132:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2133:                  "</font>");
1.149     www      2134:     }
1.151     www      2135:     return $token;
1.149     www      2136: }
                   2137: 
                   2138: # ------------------------------------------------------------ Check in an item
                   2139: 
                   2140: sub checkin {
                   2141:     my $token=shift;
1.150     www      2142:     my $now=time;
                   2143:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2144:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2145:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2146:     $dtoken=~s/\W/\_/g;
1.234     www      2147:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2148:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2149: 
1.154     www      2150:     unless (($tuname) && ($tudom)) {
                   2151:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2152:         return '';
                   2153:     }
                   2154:     
                   2155:     unless (&allowed('mgr',$tcrsid)) {
                   2156:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2157:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2158:         return '';
                   2159:     }
                   2160: 
1.153     www      2161:     my %infohash=('resource.0.intoken' => $token,
                   2162:                   'resource.0.checkintime' => $now,
                   2163:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2164: 
                   2165:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2166:        return '';
                   2167:     }    
                   2168: 
                   2169:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2170:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2171: 	return '';
                   2172:     }
                   2173: 
                   2174:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2175: }
                   2176: 
                   2177: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2178: 
                   2179: sub expirespread {
                   2180:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2181:     my $cid=$env{'request.course.id'}; 
1.110     www      2182:     if ($cid) {
                   2183:        my $now=time;
                   2184:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2185:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2186:                             $env{'course.'.$cid.'.num'}.
1.110     www      2187: 	        	    ':nohist_expirationdates:'.
                   2188:                             &escape($key).'='.$now,
1.620     albertel 2189:                             $env{'course.'.$cid.'.home'})
1.110     www      2190:     }
                   2191:     return 'ok';
1.14      www      2192: }
                   2193: 
1.109     www      2194: # ----------------------------------------------------- Devalidate Spreadsheets
                   2195: 
                   2196: sub devalidate {
1.325     www      2197:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2198:     my $cid=$env{'request.course.id'}; 
1.109     www      2199:     if ($cid) {
1.391     matthew  2200:         # delete the stored spreadsheets for
                   2201:         # - the student level sheet of this user in course's homespace
                   2202:         # - the assessment level sheet for this resource 
                   2203:         #   for this user in user's homespace
1.553     albertel 2204: 	# - current conditional state info
1.325     www      2205: 	my $key=$uname.':'.$udom.':';
1.109     www      2206:         my $status=
1.299     matthew  2207: 	    &del('nohist_calculatedsheets',
1.391     matthew  2208: 		 [$key.'studentcalc:'],
1.620     albertel 2209: 		 $env{'course.'.$cid.'.domain'},
                   2210: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2211: 		.' '.
                   2212: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2213: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2214:         unless ($status eq 'ok ok') {
                   2215:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2216:                     $uname.' at '.$udom.' for '.
1.109     www      2217: 		    $symb.': '.$status);
1.133     albertel 2218:         }
1.553     albertel 2219: 	&delenv('user.state.'.$cid);
1.109     www      2220:     }
                   2221: }
                   2222: 
1.265     albertel 2223: sub get_scalar {
                   2224:     my ($string,$end) = @_;
                   2225:     my $value;
                   2226:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2227: 	$value = $1;
                   2228:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2229: 	$value = $1;
                   2230:     }
                   2231:     return &unescape($value);
                   2232: }
                   2233: 
                   2234: sub array2str {
                   2235:   my (@array) = @_;
                   2236:   my $result=&arrayref2str(\@array);
                   2237:   $result=~s/^__ARRAY_REF__//;
                   2238:   $result=~s/__END_ARRAY_REF__$//;
                   2239:   return $result;
                   2240: }
                   2241: 
1.204     albertel 2242: sub arrayref2str {
                   2243:   my ($arrayref) = @_;
1.265     albertel 2244:   my $result='__ARRAY_REF__';
1.204     albertel 2245:   foreach my $elem (@$arrayref) {
1.265     albertel 2246:     if(ref($elem) eq 'ARRAY') {
                   2247:       $result.=&arrayref2str($elem).'&';
                   2248:     } elsif(ref($elem) eq 'HASH') {
                   2249:       $result.=&hashref2str($elem).'&';
                   2250:     } elsif(ref($elem)) {
                   2251:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2252:     } else {
                   2253:       $result.=&escape($elem).'&';
                   2254:     }
                   2255:   }
                   2256:   $result=~s/\&$//;
1.265     albertel 2257:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2258:   return $result;
                   2259: }
                   2260: 
1.168     albertel 2261: sub hash2str {
1.204     albertel 2262:   my (%hash) = @_;
                   2263:   my $result=&hashref2str(\%hash);
1.265     albertel 2264:   $result=~s/^__HASH_REF__//;
                   2265:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2266:   return $result;
                   2267: }
                   2268: 
                   2269: sub hashref2str {
                   2270:   my ($hashref)=@_;
1.265     albertel 2271:   my $result='__HASH_REF__';
1.495     albertel 2272:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2273:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2274:       $result.=&arrayref2str($_).'=';
1.204     albertel 2275:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2276:       $result.=&hashref2str($_).'=';
1.204     albertel 2277:     } elsif (ref($_)) {
1.265     albertel 2278:       $result.='=';
                   2279:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2280:     } else {
1.265     albertel 2281: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2282:     }
                   2283: 
1.265     albertel 2284:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2285:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2286:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2287:       $result.=&hashref2str($hashref->{$_}).'&';
                   2288:     } elsif(ref($hashref->{$_})) {
                   2289:        $result.='&';
                   2290:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2291:     } else {
1.265     albertel 2292:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2293:     }
                   2294:   }
1.168     albertel 2295:   $result=~s/\&$//;
1.265     albertel 2296:   $result .= '__END_HASH_REF__';
1.168     albertel 2297:   return $result;
                   2298: }
                   2299: 
                   2300: sub str2hash {
1.265     albertel 2301:     my ($string)=@_;
                   2302:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2303:     return %$hash;
                   2304: }
                   2305: 
                   2306: sub str2hashref {
1.168     albertel 2307:   my ($string) = @_;
1.265     albertel 2308: 
                   2309:   my %hash;
                   2310: 
                   2311:   if($string !~ /^__HASH_REF__/) {
                   2312:       if (! ($string eq '' || !defined($string))) {
                   2313: 	  $hash{'error'}='Not hash reference';
                   2314:       }
                   2315:       return (\%hash, $string);
                   2316:   }
                   2317: 
                   2318:   $string =~ s/^__HASH_REF__//;
                   2319: 
                   2320:   while($string !~ /^__END_HASH_REF__/) {
                   2321:       #key
                   2322:       my $key='';
                   2323:       if($string =~ /^__HASH_REF__/) {
                   2324:           ($key, $string)=&str2hashref($string);
                   2325:           if(defined($key->{'error'})) {
                   2326:               $hash{'error'}='Bad data';
                   2327:               return (\%hash, $string);
                   2328:           }
                   2329:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2330:           ($key, $string)=&str2arrayref($string);
                   2331:           if($key->[0] eq 'Array reference error') {
                   2332:               $hash{'error'}='Bad data';
                   2333:               return (\%hash, $string);
                   2334:           }
                   2335:       } else {
                   2336:           $string =~ s/^(.*?)=//;
1.267     albertel 2337: 	  $key=&unescape($1);
1.265     albertel 2338:       }
                   2339:       $string =~ s/^=//;
                   2340: 
                   2341:       #value
                   2342:       my $value='';
                   2343:       if($string =~ /^__HASH_REF__/) {
                   2344:           ($value, $string)=&str2hashref($string);
                   2345:           if(defined($value->{'error'})) {
                   2346:               $hash{'error'}='Bad data';
                   2347:               return (\%hash, $string);
                   2348:           }
                   2349:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2350:           ($value, $string)=&str2arrayref($string);
                   2351:           if($value->[0] eq 'Array reference error') {
                   2352:               $hash{'error'}='Bad data';
                   2353:               return (\%hash, $string);
                   2354:           }
                   2355:       } else {
                   2356: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2357:       }
                   2358:       $string =~ s/^&//;
                   2359: 
                   2360:       $hash{$key}=$value;
1.204     albertel 2361:   }
1.265     albertel 2362: 
                   2363:   $string =~ s/^__END_HASH_REF__//;
                   2364: 
                   2365:   return (\%hash, $string);
1.204     albertel 2366: }
                   2367: 
                   2368: sub str2array {
1.265     albertel 2369:     my ($string)=@_;
                   2370:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2371:     return @$array;
                   2372: }
                   2373: 
                   2374: sub str2arrayref {
1.204     albertel 2375:   my ($string) = @_;
1.265     albertel 2376:   my @array;
                   2377: 
                   2378:   if($string !~ /^__ARRAY_REF__/) {
                   2379:       if (! ($string eq '' || !defined($string))) {
                   2380: 	  $array[0]='Array reference error';
                   2381:       }
                   2382:       return (\@array, $string);
                   2383:   }
                   2384: 
                   2385:   $string =~ s/^__ARRAY_REF__//;
                   2386: 
                   2387:   while($string !~ /^__END_ARRAY_REF__/) {
                   2388:       my $value='';
                   2389:       if($string =~ /^__HASH_REF__/) {
                   2390:           ($value, $string)=&str2hashref($string);
                   2391:           if(defined($value->{'error'})) {
                   2392:               $array[0] ='Array reference error';
                   2393:               return (\@array, $string);
                   2394:           }
                   2395:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2396:           ($value, $string)=&str2arrayref($string);
                   2397:           if($value->[0] eq 'Array reference error') {
                   2398:               $array[0] ='Array reference error';
                   2399:               return (\@array, $string);
                   2400:           }
                   2401:       } else {
                   2402: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2403:       }
                   2404:       $string =~ s/^&//;
                   2405: 
                   2406:       push(@array, $value);
1.191     harris41 2407:   }
1.265     albertel 2408: 
                   2409:   $string =~ s/^__END_ARRAY_REF__//;
                   2410: 
                   2411:   return (\@array, $string);
1.168     albertel 2412: }
                   2413: 
1.167     albertel 2414: # -------------------------------------------------------------------Temp Store
                   2415: 
1.168     albertel 2416: sub tmpreset {
                   2417:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2418:   if (!$symb) {
                   2419:     $symb=&symbread();
1.620     albertel 2420:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2421:   }
                   2422:   $symb=escape($symb);
                   2423: 
1.620     albertel 2424:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2425:   $namespace=~s/\//\_/g;
                   2426:   $namespace=~s/\W//g;
                   2427: 
1.620     albertel 2428:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2429:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2430:   if ($domain eq 'public' && $stuname eq 'public') {
                   2431:       $stuname=$ENV{'REMOTE_ADDR'};
                   2432:   }
1.168     albertel 2433:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2434:   my %hash;
                   2435:   if (tie(%hash,'GDBM_File',
                   2436: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2437: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2438:     foreach my $key (keys %hash) {
1.180     albertel 2439:       if ($key=~ /:$symb/) {
1.168     albertel 2440: 	delete($hash{$key});
                   2441:       }
                   2442:     }
                   2443:   }
                   2444: }
                   2445: 
1.167     albertel 2446: sub tmpstore {
1.168     albertel 2447:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2448: 
                   2449:   if (!$symb) {
                   2450:     $symb=&symbread();
1.620     albertel 2451:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2452:   }
                   2453:   $symb=escape($symb);
                   2454: 
                   2455:   if (!$namespace) {
                   2456:     # I don't think we would ever want to store this for a course.
                   2457:     # it seems this will only be used if we don't have a course.
1.620     albertel 2458:     #$namespace=$env{'request.course.id'};
1.168     albertel 2459:     #if (!$namespace) {
1.620     albertel 2460:       $namespace=$env{'request.state'};
1.168     albertel 2461:     #}
                   2462:   }
                   2463:   $namespace=~s/\//\_/g;
                   2464:   $namespace=~s/\W//g;
1.620     albertel 2465:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2466:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2467:   if ($domain eq 'public' && $stuname eq 'public') {
                   2468:       $stuname=$ENV{'REMOTE_ADDR'};
                   2469:   }
1.168     albertel 2470:   my $now=time;
                   2471:   my %hash;
                   2472:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2473:   if (tie(%hash,'GDBM_File',
                   2474: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2475: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2476:     $hash{"version:$symb"}++;
                   2477:     my $version=$hash{"version:$symb"};
                   2478:     my $allkeys=''; 
                   2479:     foreach my $key (keys(%$storehash)) {
                   2480:       $allkeys.=$key.':';
1.591     albertel 2481:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2482:     }
                   2483:     $hash{"$version:$symb:timestamp"}=$now;
                   2484:     $allkeys.='timestamp';
                   2485:     $hash{"$version:keys:$symb"}=$allkeys;
                   2486:     if (untie(%hash)) {
                   2487:       return 'ok';
                   2488:     } else {
                   2489:       return "error:$!";
                   2490:     }
                   2491:   } else {
                   2492:     return "error:$!";
                   2493:   }
                   2494: }
1.167     albertel 2495: 
1.168     albertel 2496: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2497: 
1.168     albertel 2498: sub tmprestore {
                   2499:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2500: 
1.168     albertel 2501:   if (!$symb) {
                   2502:     $symb=&symbread();
1.620     albertel 2503:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2504:   }
                   2505:   $symb=escape($symb);
                   2506: 
1.620     albertel 2507:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2508: 
1.620     albertel 2509:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2510:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2511:   if ($domain eq 'public' && $stuname eq 'public') {
                   2512:       $stuname=$ENV{'REMOTE_ADDR'};
                   2513:   }
1.168     albertel 2514:   my %returnhash;
                   2515:   $namespace=~s/\//\_/g;
                   2516:   $namespace=~s/\W//g;
                   2517:   my %hash;
                   2518:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2519:   if (tie(%hash,'GDBM_File',
                   2520: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2521: 	  &GDBM_READER(),0640)) {
1.168     albertel 2522:     my $version=$hash{"version:$symb"};
                   2523:     $returnhash{'version'}=$version;
                   2524:     my $scope;
                   2525:     for ($scope=1;$scope<=$version;$scope++) {
                   2526:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2527:       my @keys=split(/:/,$vkeys);
                   2528:       my $key;
                   2529:       $returnhash{"$scope:keys"}=$vkeys;
                   2530:       foreach $key (@keys) {
1.591     albertel 2531: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2532: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2533:       }
                   2534:     }
1.168     albertel 2535:     if (!(untie(%hash))) {
                   2536:       return "error:$!";
                   2537:     }
                   2538:   } else {
                   2539:     return "error:$!";
                   2540:   }
                   2541:   return %returnhash;
1.167     albertel 2542: }
                   2543: 
1.9       www      2544: # ----------------------------------------------------------------------- Store
                   2545: 
                   2546: sub store {
1.124     www      2547:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2548:     my $home='';
                   2549: 
1.168     albertel 2550:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2551: 
1.213     www      2552:     $symb=&symbclean($symb);
1.122     albertel 2553:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2554: 
1.620     albertel 2555:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2556:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2557: 
                   2558:     &devalidate($symb,$stuname,$domain);
1.109     www      2559: 
                   2560:     $symb=escape($symb);
1.187     www      2561:     if (!$namespace) { 
1.620     albertel 2562:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2563:           return ''; 
                   2564:        } 
                   2565:     }
1.620     albertel 2566:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2567: 
                   2568:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2569:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2570: 
1.12      www      2571:     my $namevalue='';
1.191     harris41 2572:     foreach (keys %$storehash) {
1.591     albertel 2573:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2574:     }
1.12      www      2575:     $namevalue=~s/\&$//;
1.187     www      2576:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2577:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2578: }
                   2579: 
1.47      www      2580: # -------------------------------------------------------------- Critical Store
                   2581: 
                   2582: sub cstore {
1.124     www      2583:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2584:     my $home='';
                   2585: 
1.168     albertel 2586:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2587: 
1.213     www      2588:     $symb=&symbclean($symb);
1.122     albertel 2589:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2590: 
1.620     albertel 2591:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2592:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2593: 
                   2594:     &devalidate($symb,$stuname,$domain);
1.109     www      2595: 
                   2596:     $symb=escape($symb);
1.187     www      2597:     if (!$namespace) { 
1.620     albertel 2598:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2599:           return ''; 
                   2600:        } 
                   2601:     }
1.620     albertel 2602:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2603: 
                   2604:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2605:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2606: 
1.47      www      2607:     my $namevalue='';
1.191     harris41 2608:     foreach (keys %$storehash) {
1.591     albertel 2609:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2610:     }
1.47      www      2611:     $namevalue=~s/\&$//;
1.187     www      2612:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2613:     return critical
                   2614:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2615: }
                   2616: 
1.9       www      2617: # --------------------------------------------------------------------- Restore
                   2618: 
                   2619: sub restore {
1.124     www      2620:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2621:     my $home='';
                   2622: 
1.168     albertel 2623:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2624: 
1.122     albertel 2625:     if (!$symb) {
                   2626:       unless ($symb=escape(&symbread())) { return ''; }
                   2627:     } else {
1.213     www      2628:       $symb=&escape(&symbclean($symb));
1.122     albertel 2629:     }
1.188     www      2630:     if (!$namespace) { 
1.620     albertel 2631:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2632:           return ''; 
                   2633:        } 
                   2634:     }
1.620     albertel 2635:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2636:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2637:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2638:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2639: 
1.12      www      2640:     my %returnhash=();
1.191     harris41 2641:     foreach (split(/\&/,$answer)) {
1.12      www      2642: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2643:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2644:     }
1.75      www      2645:     my $version;
                   2646:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2647:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2648:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2649:        }
1.75      www      2650:     }
1.13      www      2651:     return %returnhash;
1.34      www      2652: }
                   2653: 
                   2654: # ---------------------------------------------------------- Course Description
                   2655: 
                   2656: sub coursedescription {
1.731     albertel 2657:     my ($courseid,$args)=@_;
1.34      www      2658:     $courseid=~s/^\///;
1.49      www      2659:     $courseid=~s/\_/\//g;
1.34      www      2660:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2661:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2662:     my $normalid=$cdomain.'_'.$cnum;
                   2663:     # need to always cache even if we get errors otherwise we keep 
                   2664:     # trying and trying and trying to get the course description.
                   2665:     my %envhash=();
                   2666:     my %returnhash=();
1.731     albertel 2667:     
                   2668:     my $expiretime=600;
                   2669:     if ($env{'request.course.id'} eq $normalid) {
                   2670: 	$expiretime=120;
                   2671:     }
                   2672: 
                   2673:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2674:     if (!$args->{'freshen_cache'}
                   2675: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2676: 	foreach my $key (keys(%env)) {
                   2677: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2678: 	    my ($setting) = $1;
                   2679: 	    $returnhash{$setting} = $env{$key};
                   2680: 	}
                   2681: 	return %returnhash;
                   2682:     }
                   2683: 
                   2684:     # get the data agin
                   2685:     if (!$args->{'one_time'}) {
                   2686: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2687:     }
1.34      www      2688:     if ($chome ne 'no_host') {
1.302     albertel 2689:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2690:        if (!exists($returnhash{'con_lost'})) {
                   2691:            $returnhash{'home'}= $chome;
                   2692: 	   $returnhash{'domain'} = $cdomain;
                   2693: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2694:            if (!defined($returnhash{'type'})) {
                   2695:                $returnhash{'type'} = 'Course';
                   2696:            }
1.130     albertel 2697:            while (my ($name,$value) = each %returnhash) {
1.53      www      2698:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2699:            }
1.270     www      2700:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2701:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2702: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2703:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2704:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2705:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2706:        }
                   2707:     }
1.731     albertel 2708:     if (!$args->{'one_time'}) {
                   2709: 	&appenv(%envhash);
                   2710:     }
1.302     albertel 2711:     return %returnhash;
1.461     www      2712: }
                   2713: 
                   2714: # -------------------------------------------------See if a user is privileged
                   2715: 
                   2716: sub privileged {
                   2717:     my ($username,$domain)=@_;
                   2718:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2719: 			&homeserver($username,$domain));
                   2720:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2721:     my $now=time;
                   2722:     if ($rolesdump ne '') {
                   2723:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2724: 	    if ($_!~/^rolesdef_/) {
1.461     www      2725: 		my ($area,$role)=split(/=/,$_);
                   2726: 		$area=~s/\_\w\w$//;
                   2727: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2728: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2729: 		    my $active=1;
                   2730: 		    if ($tend) {
                   2731: 			if ($tend<$now) { $active=0; }
                   2732: 		    }
                   2733: 		    if ($tstart) {
                   2734: 			if ($tstart>$now) { $active=0; }
                   2735: 		    }
                   2736: 		    if ($active) { return 1; }
                   2737: 		}
                   2738: 	    }
                   2739: 	}
                   2740:     }
                   2741:     return 0;
1.9       www      2742: }
1.1       albertel 2743: 
1.103     harris41 2744: # -------------------------------------------------------- Get user privileges
1.11      www      2745: 
                   2746: sub rolesinit {
                   2747:     my ($domain,$username,$authhost)=@_;
                   2748:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2749:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2750:     my %allroles=();
1.678     raeburn  2751:     my %allgroups=();   
1.11      www      2752:     my $now=time;
1.743     albertel 2753:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2754:     my $group_privs;
1.11      www      2755: 
                   2756:     if ($rolesdump ne '') {
1.191     harris41 2757:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2758: 	  if ($_!~/^rolesdef_/) {
1.11      www      2759:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2760: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2761:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2762: 	    if ($role=~/^cr/) { 
1.655     albertel 2763: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2764: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2765: 		    ($tend,$tstart)=split('_',$trest);
                   2766: 		} else {
                   2767: 		    $trole=$role;
                   2768: 		}
1.678     raeburn  2769:             } elsif ($role =~ m|^gr/|) {
                   2770:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2771:                 ($trole,$group_privs) = split(/\//,$trole);
                   2772:                 $group_privs = &unescape($group_privs);
1.587     albertel 2773: 	    } else {
                   2774: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2775: 	    }
1.743     albertel 2776: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2777: 					 $username);
                   2778: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2779:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2780:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2781:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2782: 		my $spec=$trole.'.'.$area;
                   2783: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2784: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2785:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2786:                 } elsif ($trole eq 'gr') {
                   2787:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2788: 		} else {
1.567     raeburn  2789:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2790: 		}
1.12      www      2791:             }
1.662     raeburn  2792:           }
1.191     harris41 2793:         }
1.743     albertel 2794:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2795:         $userroles{'user.adv'}    = $adv;
                   2796: 	$userroles{'user.author'} = $author;
1.620     albertel 2797:         $env{'user.adv'}=$adv;
1.11      www      2798:     }
1.743     albertel 2799:     return \%userroles;  
1.11      www      2800: }
                   2801: 
1.567     raeburn  2802: sub set_arearole {
                   2803:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2804: # log the associated role with the area
                   2805:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2806:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2807: }
                   2808: 
                   2809: sub custom_roleprivs {
                   2810:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2811:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2812:     my $homsvr=homeserver($rauthor,$rdomain);
                   2813:     if ($hostname{$homsvr} ne '') {
                   2814:         my ($rdummy,$roledef)=
                   2815:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2816:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2817:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2818:             if (defined($syspriv)) {
                   2819:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2820:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2821:             }
                   2822:             if ($tdomain ne '') {
                   2823:                 if (defined($dompriv)) {
                   2824:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2825:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2826:                 }
                   2827:                 if (($trest ne '') && (defined($coursepriv))) {
                   2828:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2829:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2830:                 }
                   2831:             }
                   2832:         }
                   2833:     }
                   2834: }
                   2835: 
1.678     raeburn  2836: sub group_roleprivs {
                   2837:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2838:     my $access = 1;
                   2839:     my $now = time;
                   2840:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2841:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2842:     if ($access) {
                   2843:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2844:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2845:     }
                   2846: }
1.567     raeburn  2847: 
                   2848: sub standard_roleprivs {
                   2849:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2850:     if (defined($pr{$trole.':s'})) {
                   2851:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2852:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2853:     }
                   2854:     if ($tdomain ne '') {
                   2855:         if (defined($pr{$trole.':d'})) {
                   2856:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2857:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2858:         }
                   2859:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2860:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2861:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2862:         }
                   2863:     }
                   2864: }
                   2865: 
                   2866: sub set_userprivs {
1.678     raeburn  2867:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2868:     my $author=0;
                   2869:     my $adv=0;
1.678     raeburn  2870:     my %grouproles = ();
                   2871:     if (keys(%{$allgroups}) > 0) {
                   2872:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2873:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2874:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2875:                 $trole = $1;
                   2876:                 $area = $2;
1.681     raeburn  2877:                 $sec = $3;
                   2878:                 $extendedarea = $area.$sec;
                   2879:                 if (exists($$allgroups{$area})) {
                   2880:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2881:                         my $spec = $trole.'.'.$extendedarea;
                   2882:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2883:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2884:                     }
                   2885:                 }
                   2886:             }
                   2887:         }
                   2888:     }
                   2889:     foreach (keys(%grouproles)) {
                   2890:         $$allroles{$_} = $grouproles{$_};
                   2891:     }
1.567     raeburn  2892:     foreach (keys %{$allroles}) {
                   2893:         my %thesepriv=();
                   2894:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2895:         foreach (split(/:/,$$allroles{$_})) {
                   2896:             if ($_ ne '') {
                   2897:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2898:                 if ($restrictions eq '') {
                   2899:                     $thesepriv{$privilege}='F';
                   2900:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2901:                     $thesepriv{$privilege}.=$restrictions;
                   2902:                 }
                   2903:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2904:             }
                   2905:         }
                   2906:         my $thesestr='';
                   2907:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2908:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2909:     }
                   2910:     return ($author,$adv);
                   2911: }
                   2912: 
1.12      www      2913: # --------------------------------------------------------------- get interface
                   2914: 
                   2915: sub get {
1.131     albertel 2916:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2917:    my $items='';
1.191     harris41 2918:    foreach (@$storearr) {
1.12      www      2919:        $items.=escape($_).'&';
1.191     harris41 2920:    }
1.12      www      2921:    $items=~s/\&$//;
1.620     albertel 2922:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2923:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2924:    my $uhome=&homeserver($uname,$udomain);
                   2925: 
1.133     albertel 2926:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2927:    my @pairs=split(/\&/,$rep);
1.273     albertel 2928:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2929:      return @pairs;
                   2930:    }
1.15      www      2931:    my %returnhash=();
1.42      www      2932:    my $i=0;
1.191     harris41 2933:    foreach (@$storearr) {
1.557     albertel 2934:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2935:       $i++;
1.191     harris41 2936:    }
1.15      www      2937:    return %returnhash;
1.27      www      2938: }
                   2939: 
                   2940: # --------------------------------------------------------------- del interface
                   2941: 
                   2942: sub del {
1.133     albertel 2943:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2944:    my $items='';
1.191     harris41 2945:    foreach (@$storearr) {
1.27      www      2946:        $items.=escape($_).'&';
1.191     harris41 2947:    }
1.27      www      2948:    $items=~s/\&$//;
1.620     albertel 2949:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2950:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2951:    my $uhome=&homeserver($uname,$udomain);
                   2952: 
                   2953:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2954: }
                   2955: 
                   2956: # -------------------------------------------------------------- dump interface
                   2957: 
                   2958: sub dump {
1.755     albertel 2959:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2960:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2961:     if (!$uname) { $uname=$env{'user.name'}; }
                   2962:     my $uhome=&homeserver($uname,$udomain);
                   2963:     if ($regexp) {
                   2964: 	$regexp=&escape($regexp);
                   2965:     } else {
                   2966: 	$regexp='.';
                   2967:     }
                   2968:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2969:     my @pairs=split(/\&/,$rep);
                   2970:     my %returnhash=();
                   2971:     foreach my $item (@pairs) {
                   2972: 	my ($key,$value)=split(/=/,$item,2);
                   2973: 	$key = &unescape($key);
                   2974: 	next if ($key =~ /^error: 2 /);
                   2975: 	$returnhash{$key}=&thaw_unescape($value);
                   2976:     }
                   2977:     return %returnhash;
1.407     www      2978: }
                   2979: 
1.717     albertel 2980: # --------------------------------------------------------- dumpstore interface
                   2981: 
                   2982: sub dumpstore {
                   2983:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2984:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2985: }
                   2986: 
1.407     www      2987: # -------------------------------------------------------------- keys interface
                   2988: 
                   2989: sub getkeys {
                   2990:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2991:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2992:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2993:    my $uhome=&homeserver($uname,$udomain);
                   2994:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2995:    my @keyarray=();
                   2996:    foreach (split(/\&/,$rep)) {
                   2997:       push (@keyarray,&unescape($_));
                   2998:    }
                   2999:    return @keyarray;
1.318     matthew  3000: }
                   3001: 
1.319     matthew  3002: # --------------------------------------------------------------- currentdump
                   3003: sub currentdump {
1.328     matthew  3004:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3005:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3006:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3007:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3008:    my $uhome = &homeserver($sname,$sdom);
                   3009:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3010:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3011:    #
1.318     matthew  3012:    my %returnhash=();
1.319     matthew  3013:    #
                   3014:    if ($rep eq "unknown_cmd") { 
                   3015:        # an old lond will not know currentdump
                   3016:        # Do a dump and make it look like a currentdump
1.326     matthew  3017:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3018:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3019:        my %hash = @tmp;
                   3020:        @tmp=();
1.424     matthew  3021:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3022:    } else {
                   3023:        my @pairs=split(/\&/,$rep);
                   3024:        foreach (@pairs) {
                   3025:            my ($key,$value)=split(/=/,$_);
                   3026:            my ($symb,$param) = split(/:/,$key);
                   3027:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3028:                                                         &thaw_unescape($value);
1.319     matthew  3029:        }
1.191     harris41 3030:    }
1.12      www      3031:    return %returnhash;
1.424     matthew  3032: }
                   3033: 
                   3034: sub convert_dump_to_currentdump{
                   3035:     my %hash = %{shift()};
                   3036:     my %returnhash;
                   3037:     # Code ripped from lond, essentially.  The only difference
                   3038:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3039:     # we might run in to problems with parameter names =~ /^v\./
                   3040:     while (my ($key,$value) = each(%hash)) {
                   3041:         my ($v,$symb,$param) = split(/:/,$key);
                   3042:         next if ($v eq 'version' || $symb eq 'keys');
                   3043:         next if (exists($returnhash{$symb}) &&
                   3044:                  exists($returnhash{$symb}->{$param}) &&
                   3045:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3046:         $returnhash{$symb}->{$param}=$value;
                   3047:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3048:     }
                   3049:     #
                   3050:     # Remove all of the keys in the hashes which keep track of
                   3051:     # the version of the parameter.
                   3052:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3053:         # use a foreach because we are going to delete from the hash.
                   3054:         foreach my $key (keys(%$param_hash)) {
                   3055:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3056:         }
                   3057:     }
                   3058:     return \%returnhash;
1.12      www      3059: }
                   3060: 
1.627     albertel 3061: # ------------------------------------------------------ critical inc interface
                   3062: 
                   3063: sub cinc {
                   3064:     return &inc(@_,'critical');
                   3065: }
                   3066: 
1.449     matthew  3067: # --------------------------------------------------------------- inc interface
                   3068: 
                   3069: sub inc {
1.627     albertel 3070:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3071:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3072:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3073:     my $uhome=&homeserver($uname,$udomain);
                   3074:     my $items='';
                   3075:     if (! ref($store)) {
                   3076:         # got a single value, so use that instead
                   3077:         $items = &escape($store).'=&';
                   3078:     } elsif (ref($store) eq 'SCALAR') {
                   3079:         $items = &escape($$store).'=&';        
                   3080:     } elsif (ref($store) eq 'ARRAY') {
                   3081:         $items = join('=&',map {&escape($_);} @{$store});
                   3082:     } elsif (ref($store) eq 'HASH') {
                   3083:         while (my($key,$value) = each(%{$store})) {
                   3084:             $items.= &escape($key).'='.&escape($value).'&';
                   3085:         }
                   3086:     }
                   3087:     $items=~s/\&$//;
1.627     albertel 3088:     if ($critical) {
                   3089: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3090:     } else {
                   3091: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3092:     }
1.449     matthew  3093: }
                   3094: 
1.12      www      3095: # --------------------------------------------------------------- put interface
                   3096: 
                   3097: sub put {
1.134     albertel 3098:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3099:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3100:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3101:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3102:    my $items='';
1.191     harris41 3103:    foreach (keys %$storehash) {
1.557     albertel 3104:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3105:    }
1.12      www      3106:    $items=~s/\&$//;
1.134     albertel 3107:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3108: }
                   3109: 
1.631     albertel 3110: # ------------------------------------------------------------ newput interface
                   3111: 
                   3112: sub newput {
                   3113:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3114:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3115:    if (!$uname) { $uname=$env{'user.name'}; }
                   3116:    my $uhome=&homeserver($uname,$udomain);
                   3117:    my $items='';
                   3118:    foreach my $key (keys(%$storehash)) {
                   3119:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3120:    }
                   3121:    $items=~s/\&$//;
                   3122:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3123: }
                   3124: 
                   3125: # ---------------------------------------------------------  putstore interface
                   3126: 
1.524     raeburn  3127: sub putstore {
1.715     albertel 3128:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3129:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3130:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3131:    my $uhome=&homeserver($uname,$udomain);
                   3132:    my $items='';
1.715     albertel 3133:    foreach my $key (keys(%$storehash)) {
                   3134:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3135:    }
1.715     albertel 3136:    $items=~s/\&$//;
1.716     albertel 3137:    my $esc_symb=&escape($symb);
                   3138:    my $esc_v=&escape($version);
1.715     albertel 3139:    my $reply =
1.716     albertel 3140:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3141: 	      $uhome);
                   3142:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3143:        # gfall back to way things use to be done
1.715     albertel 3144:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3145: 			    $uname);
1.524     raeburn  3146:    }
1.715     albertel 3147:    return $reply;
                   3148: }
                   3149: 
                   3150: sub old_putstore {
1.716     albertel 3151:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3152:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3153:     if (!$uname) { $uname=$env{'user.name'}; }
                   3154:     my $uhome=&homeserver($uname,$udomain);
                   3155:     my %newstorehash;
                   3156:     foreach (keys %$storehash) {
                   3157: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3158: 	$newstorehash{$key} = $storehash->{$_};
                   3159:     }
                   3160:     my $items='';
                   3161:     my %allitems = ();
                   3162:     foreach (keys %newstorehash) {
                   3163: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3164: 	    my $key = $1.':keys:'.$2;
                   3165: 	    $allitems{$key} .= $3.':';
                   3166: 	}
                   3167: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3168:     }
                   3169:     foreach (keys %allitems) {
                   3170: 	$allitems{$_} =~ s/\:$//;
                   3171: 	$items.= $_.'='.$allitems{$_}.'&';
                   3172:     }
                   3173:     $items=~s/\&$//;
                   3174:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3175: }
                   3176: 
1.47      www      3177: # ------------------------------------------------------ critical put interface
                   3178: 
                   3179: sub cput {
1.134     albertel 3180:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3181:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3182:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3183:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3184:    my $items='';
1.191     harris41 3185:    foreach (keys %$storehash) {
1.715     albertel 3186:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3187:    }
1.47      www      3188:    $items=~s/\&$//;
1.134     albertel 3189:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3190: }
                   3191: 
                   3192: # -------------------------------------------------------------- eget interface
                   3193: 
                   3194: sub eget {
1.133     albertel 3195:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3196:    my $items='';
1.191     harris41 3197:    foreach (@$storearr) {
1.12      www      3198:        $items.=escape($_).'&';
1.191     harris41 3199:    }
1.12      www      3200:    $items=~s/\&$//;
1.620     albertel 3201:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3202:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3203:    my $uhome=&homeserver($uname,$udomain);
                   3204:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3205:    my @pairs=split(/\&/,$rep);
                   3206:    my %returnhash=();
1.42      www      3207:    my $i=0;
1.191     harris41 3208:    foreach (@$storearr) {
1.557     albertel 3209:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3210:       $i++;
1.191     harris41 3211:    }
1.12      www      3212:    return %returnhash;
                   3213: }
                   3214: 
1.667     albertel 3215: # ------------------------------------------------------------ tmpput interface
                   3216: sub tmpput {
                   3217:     my ($storehash,$server)=@_;
                   3218:     my $items='';
                   3219:     foreach (keys(%$storehash)) {
                   3220: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3221:     }
                   3222:     $items=~s/\&$//;
                   3223:     return &reply("tmpput:$items",$server);
                   3224: }
                   3225: 
                   3226: # ------------------------------------------------------------ tmpget interface
                   3227: sub tmpget {
1.688     albertel 3228:     my ($token,$server)=@_;
                   3229:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3230:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3231:     my %returnhash;
                   3232:     foreach my $item (split(/\&/,$rep)) {
                   3233: 	my ($key,$value)=split(/=/,$item);
                   3234: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3235:     }
                   3236:     return %returnhash;
                   3237: }
                   3238: 
1.688     albertel 3239: # ------------------------------------------------------------ tmpget interface
                   3240: sub tmpdel {
                   3241:     my ($token,$server)=@_;
                   3242:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3243:     return &reply("tmpdel:$token",$server);
                   3244: }
                   3245: 
1.765     albertel 3246: # -------------------------------------------------- portfolio access checking
                   3247: 
                   3248: sub portfolio_access {
1.766     albertel 3249:     my ($requrl) = @_;
1.765     albertel 3250:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3251:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3252:     if ($result eq 'ok') {
1.766     albertel 3253:        return 'F';
1.765     albertel 3254:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3255:        return 'A';
1.765     albertel 3256:     }
1.766     albertel 3257:     return '';
1.765     albertel 3258: }
                   3259: 
                   3260: sub get_portfolio_access {
1.767     albertel 3261:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3262: 
                   3263:     if (!ref($access_hash)) {
                   3264: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3265: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3266: 						   $file_name);
                   3267: 	$access_hash = $access_controls{$file_name};
                   3268:     }
                   3269: 
1.765     albertel 3270:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3271:     my $now = time;
                   3272:     if (ref($access_hash) eq 'HASH') {
                   3273:         foreach my $key (keys(%{$access_hash})) {
                   3274:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3275:             if ($start > $now) {
                   3276:                 next;
                   3277:             }
                   3278:             if ($end && $end<$now) {
                   3279:                 next;
                   3280:             }
                   3281:             if ($scope eq 'public') {
                   3282:                 $public = $key;
                   3283:                 last;
                   3284:             } elsif ($scope eq 'guest') {
                   3285:                 $guest = $key;
                   3286:             } elsif ($scope eq 'domains') {
                   3287:                 push(@domains,$key);
                   3288:             } elsif ($scope eq 'users') {
                   3289:                 push(@users,$key);
                   3290:             } elsif ($scope eq 'course') {
                   3291:                 push(@courses,$key);
                   3292:             } elsif ($scope eq 'group') {
                   3293:                 push(@groups,$key);
                   3294:             }
                   3295:         }
                   3296:         if ($public) {
                   3297:             return 'ok';
                   3298:         }
                   3299:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3300:             if ($guest) {
                   3301:                 return $guest;
                   3302:             }
                   3303:         } else {
                   3304:             if (@domains > 0) {
                   3305:                 foreach my $domkey (@domains) {
                   3306:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3307:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3308:                             return 'ok';
                   3309:                         }
                   3310:                     }
                   3311:                 }
                   3312:             }
                   3313:             if (@users > 0) {
                   3314:                 foreach my $userkey (@users) {
                   3315:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3316:                         return 'ok';
                   3317:                     }
                   3318:                 }
                   3319:             }
                   3320:             my %roleshash;
                   3321:             my @courses_and_groups = @courses;
                   3322:             push(@courses_and_groups,@groups); 
                   3323:             if (@courses_and_groups > 0) {
                   3324:                 my (%allgroups,%allroles); 
                   3325:                 my ($start,$end,$role,$sec,$group);
                   3326:                 foreach my $envkey (%env) {
                   3327:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3328:                         my $cid = $2.'_'.$3; 
                   3329:                         if ($1 eq 'gr') {
                   3330:                             $group = $4;
                   3331:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3332:                         } else {
                   3333:                             if ($4 eq '') {
                   3334:                                 $sec = 'none';
                   3335:                             } else {
                   3336:                                 $sec = $4;
                   3337:                             }
                   3338:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3339:                         }
                   3340:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3341:                         my $cid = $2.'_'.$3;
                   3342:                         if ($4 eq '') {
                   3343:                             $sec = 'none';
                   3344:                         } else {
                   3345:                             $sec = $4;
                   3346:                         }
                   3347:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3348:                     }
                   3349:                 }
                   3350:                 if (keys(%allroles) == 0) {
                   3351:                     return;
                   3352:                 }
                   3353:                 foreach my $key (@courses_and_groups) {
                   3354:                     my %content = %{$$access_hash{$key}};
                   3355:                     my $cnum = $content{'number'};
                   3356:                     my $cdom = $content{'domain'};
                   3357:                     my $cid = $cdom.'_'.$cnum;
                   3358:                     if (!exists($allroles{$cid})) {
                   3359:                         next;
                   3360:                     }    
                   3361:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3362:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3363:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3364:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3365:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3366:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3367:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3368:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3369:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3370:                                         if (grep/^all$/,@sections) {
                   3371:                                             return 'ok';
                   3372:                                         } else {
                   3373:                                             if (grep/^$sec$/,@sections) {
                   3374:                                                 return 'ok';
                   3375:                                             }
                   3376:                                         }
                   3377:                                     }
                   3378:                                 }
                   3379:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3380:                                     if (grep/^none$/,@groups) {
                   3381:                                         return 'ok';
                   3382:                                     }
                   3383:                                 } else {
                   3384:                                     if (grep/^all$/,@groups) {
                   3385:                                         return 'ok';
                   3386:                                     } 
                   3387:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3388:                                         if (grep/^$group$/,@groups) {
                   3389:                                             return 'ok';
                   3390:                                         }
                   3391:                                     }
                   3392:                                 } 
                   3393:                             }
                   3394:                         }
                   3395:                     }
                   3396:                 }
                   3397:             }
                   3398:             if ($guest) {
                   3399:                 return $guest;
                   3400:             }
                   3401:         }
                   3402:     }
                   3403:     return;
                   3404: }
                   3405: 
                   3406: sub course_group_datechecker {
                   3407:     my ($dates,$now,$status) = @_;
                   3408:     my ($start,$end) = split(/\./,$dates);
                   3409:     if (!$start && !$end) {
                   3410:         return 'ok';
                   3411:     }
                   3412:     if (grep/^active$/,@{$status}) {
                   3413:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3414:             return 'ok';
                   3415:         }
                   3416:     }
                   3417:     if (grep/^previous$/,@{$status}) {
                   3418:         if ($end > $now ) {
                   3419:             return 'ok';
                   3420:         }
                   3421:     }
                   3422:     if (grep/^future$/,@{$status}) {
                   3423:         if ($start > $now) {
                   3424:             return 'ok';
                   3425:         }
                   3426:     }
                   3427:     return; 
                   3428: }
                   3429: 
                   3430: sub parse_portfolio_url {
                   3431:     my ($url) = @_;
                   3432: 
                   3433:     my ($type,$udom,$unum,$group,$file_name);
                   3434:     
                   3435:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3436: 	$type = 1;
                   3437:         $udom = $1;
                   3438:         $unum = $2;
                   3439:         $file_name = $3;
                   3440:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3441: 	$type = 2;
                   3442:         $udom = $1;
                   3443:         $unum = $2;
                   3444:         $group = $3;
                   3445:         $file_name = $3.'/'.$4;
                   3446:     }
                   3447:     if (wantarray) {
                   3448: 	return ($type,$udom,$unum,$file_name,$group);
                   3449:     }
                   3450:     return $type;
                   3451: }
                   3452: 
                   3453: sub is_portfolio_url {
                   3454:     my ($url) = @_;
                   3455:     return scalar(&parse_portfolio_url($url));
                   3456: }
                   3457: 
1.341     www      3458: # ---------------------------------------------- Custom access rule evaluation
                   3459: 
                   3460: sub customaccess {
                   3461:     my ($priv,$uri)=@_;
1.620     albertel 3462:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3463:     $urealm=~s/^\W//;
                   3464:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3465:     my $access=0;
                   3466:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3467: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3468:         if ($role) {
                   3469: 	   if ($role ne $urole) { next; }
                   3470:         }
                   3471:         foreach (split(/\s*\,\s*/,$realm)) {
                   3472:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3473:             if ($tdom) {
                   3474: 		if ($tdom ne $udom) { next; }
                   3475:             }
                   3476:             if ($tcrs) {
                   3477: 		if ($tcrs ne $ucrs) { next; }
                   3478:             }
                   3479:             if ($tsec) {
                   3480: 		if ($tsec ne $usec) { next; }
                   3481:             }
                   3482:             $access=($effect eq 'allow');
                   3483:             last;
1.342     www      3484:         }
1.402     bowersj2 3485: 	if ($realm eq '' && $role eq '') {
                   3486:             $access=($effect eq 'allow');
                   3487: 	}
1.341     www      3488:     }
                   3489:     return $access;
                   3490: }
                   3491: 
1.103     harris41 3492: # ------------------------------------------------- Check for a user privilege
1.12      www      3493: 
                   3494: sub allowed {
1.579     albertel 3495:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3496:     my $ver_orguri=$uri;
1.439     www      3497:     $uri=&deversion($uri);
1.152     www      3498:     my $orguri=$uri;
1.52      www      3499:     $uri=&declutter($uri);
1.545     banghart 3500:     
1.620     albertel 3501:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3502: # Free bre access to adm and meta resources
1.775     albertel 3503:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3504: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3505: 	&& ($priv eq 'bre')) {
1.14      www      3506: 	return 'F';
1.159     www      3507:     }
                   3508: 
1.545     banghart 3509: # Free bre access to user's own portfolio contents
1.714     raeburn  3510:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3511:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3512: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3513:         return 'F';
                   3514:     }
                   3515: 
1.762     raeburn  3516: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3517:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3518:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3519:         if (exists($env{'request.course.id'})) {
                   3520:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3521:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3522:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3523:                 my $courseprivid=$env{'request.course.id'};
                   3524:                 $courseprivid=~s/\_/\//;
                   3525:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3526:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3527:                     return $1; 
1.762     raeburn  3528:                 } else {
                   3529:                     if ($env{'request.course.sec'}) {
                   3530:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3531:                     }
                   3532:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3533:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3534:                         return $2;
                   3535:                     }
1.714     raeburn  3536:                 }
                   3537:             }
                   3538:         }
                   3539:     }
                   3540: 
1.159     www      3541: # Free bre to public access
                   3542: 
                   3543:     if ($priv eq 'bre') {
1.238     www      3544:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3545: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3546:            return 'F'; 
                   3547:         }
1.238     www      3548:         if ($copyright eq 'priv') {
                   3549:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3550: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3551: 		return '';
                   3552:             }
                   3553:         }
                   3554:         if ($copyright eq 'domain') {
                   3555:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3556: 	    unless (($env{'user.domain'} eq $1) ||
                   3557:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3558: 		return '';
                   3559:             }
1.262     matthew  3560:         }
1.620     albertel 3561:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3562:             # Library role, so allow browsing of resources in this domain.
                   3563:             return 'F';
1.238     www      3564:         }
1.341     www      3565:         if ($copyright eq 'custom') {
                   3566: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3567:         }
1.14      www      3568:     }
1.264     matthew  3569:     # Domain coordinator is trying to create a course
1.620     albertel 3570:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3571:         # uri is the requested domain in this case.
                   3572:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3573:         # a role of dc for the domain in question.
1.620     albertel 3574:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3575:     }
1.29      www      3576: 
1.52      www      3577:     my $thisallowed='';
                   3578:     my $statecond=0;
                   3579:     my $courseprivid='';
                   3580: 
                   3581: # Course
                   3582: 
1.620     albertel 3583:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3584:        $thisallowed.=$1;
                   3585:     }
1.29      www      3586: 
1.52      www      3587: # Domain
                   3588: 
1.620     albertel 3589:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3590:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3591:        $thisallowed.=$1;
                   3592:     }
1.52      www      3593: 
                   3594: # Course: uri itself is a course
1.66      www      3595:     my $courseuri=$uri;
                   3596:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3597:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3598: 
1.620     albertel 3599:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3600:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3601:        $thisallowed.=$1;
                   3602:     }
1.29      www      3603: 
1.665     albertel 3604: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3605: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3606:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3607: 	$thisallowed='';
1.671     raeburn  3608:         my ($match)=&is_on_map($uri);
                   3609:         if ($match) {
                   3610:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3611:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3612:                 $thisallowed.=$1;
                   3613:             }
                   3614:         } else {
1.705     albertel 3615:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3616:             if ($refuri) {
                   3617:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3618:                     $thisallowed='F';
1.671     raeburn  3619:                 } else {
                   3620:                     $refuri=&declutter($refuri);
                   3621:                     my ($match) = &is_on_map($refuri);
                   3622:                     if ($match) {
                   3623:                         $thisallowed='F';
                   3624:                     }
1.669     raeburn  3625:                 }
1.671     raeburn  3626:             }
                   3627:         }
1.314     www      3628:     }
1.492     albertel 3629: 
1.766     albertel 3630:     if ($priv eq 'bre'
                   3631: 	&& $thisallowed ne 'F' 
                   3632: 	&& $thisallowed ne '2'
                   3633: 	&& &is_portfolio_url($uri)) {
                   3634: 	$thisallowed = &portfolio_access($uri);
                   3635:     }
                   3636:     
1.52      www      3637: # Full access at system, domain or course-wide level? Exit.
1.29      www      3638: 
                   3639:     if ($thisallowed=~/F/) {
                   3640: 	return 'F';
                   3641:     }
                   3642: 
1.52      www      3643: # If this is generating or modifying users, exit with special codes
1.29      www      3644: 
1.643     www      3645:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3646: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3647: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3648: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3649: 	    unless ($auname) { return $thisallowed; }
                   3650: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3651: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3652: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3653: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3654: 	}
1.52      www      3655: 	return $thisallowed;
                   3656:     }
                   3657: #
1.103     harris41 3658: # Gathered so far: system, domain and course wide privileges
1.52      www      3659: #
                   3660: # Course: See if uri or referer is an individual resource that is part of 
                   3661: # the course
                   3662: 
1.620     albertel 3663:     if ($env{'request.course.id'}) {
1.232     www      3664: 
1.620     albertel 3665:        $courseprivid=$env{'request.course.id'};
                   3666:        if ($env{'request.course.sec'}) {
                   3667:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3668:        }
                   3669:        $courseprivid=~s/\_/\//;
                   3670:        my $checkreferer=1;
1.232     www      3671:        my ($match,$cond)=&is_on_map($uri);
                   3672:        if ($match) {
                   3673:            $statecond=$cond;
1.620     albertel 3674:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3675:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3676:                $thisallowed.=$1;
                   3677:                $checkreferer=0;
                   3678:            }
1.29      www      3679:        }
1.83      www      3680:        
1.148     www      3681:        if ($checkreferer) {
1.620     albertel 3682: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3683:             unless ($refuri) {
1.620     albertel 3684:                 foreach (keys %env) {
1.148     www      3685: 		    if ($_=~/^httpref\..*\*/) {
                   3686: 			my $pattern=$_;
1.156     www      3687:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3688:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3689:                         $pattern=~s/\//\\\//g;
1.152     www      3690:                         if ($orguri=~/$pattern/) {
1.620     albertel 3691: 			    $refuri=$env{$_};
1.148     www      3692:                         }
                   3693:                     }
1.191     harris41 3694:                 }
1.148     www      3695:             }
1.232     www      3696: 
1.148     www      3697:          if ($refuri) { 
1.152     www      3698: 	  $refuri=&declutter($refuri);
1.232     www      3699:           my ($match,$cond)=&is_on_map($refuri);
                   3700:             if ($match) {
                   3701:               my $refstatecond=$cond;
1.620     albertel 3702:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3703:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3704:                   $thisallowed.=$1;
1.53      www      3705:                   $uri=$refuri;
                   3706:                   $statecond=$refstatecond;
1.52      www      3707:               }
                   3708:           }
1.148     www      3709:         }
1.29      www      3710:        }
1.52      www      3711:    }
1.29      www      3712: 
1.52      www      3713: #
1.103     harris41 3714: # Gathered now: all privileges that could apply, and condition number
1.52      www      3715: # 
                   3716: #
                   3717: # Full or no access?
                   3718: #
1.29      www      3719: 
1.52      www      3720:     if ($thisallowed=~/F/) {
                   3721: 	return 'F';
                   3722:     }
1.29      www      3723: 
1.52      www      3724:     unless ($thisallowed) {
                   3725:         return '';
                   3726:     }
1.29      www      3727: 
1.52      www      3728: # Restrictions exist, deal with them
                   3729: #
                   3730: #   C:according to course preferences
                   3731: #   R:according to resource settings
                   3732: #   L:unless locked
                   3733: #   X:according to user session state
                   3734: #
                   3735: 
                   3736: # Possibly locked functionality, check all courses
1.54      www      3737: # Locks might take effect only after 10 minutes cache expiration for other
                   3738: # courses, and 2 minutes for current course
1.52      www      3739: 
                   3740:     my $envkey;
                   3741:     if ($thisallowed=~/L/) {
1.620     albertel 3742:         foreach $envkey (keys %env) {
1.54      www      3743:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3744:                my $courseid=$2;
                   3745:                my $roleid=$1.'.'.$2;
1.92      www      3746:                $courseid=~s/^\///;
1.54      www      3747:                my $expiretime=600;
1.620     albertel 3748:                if ($env{'request.role'} eq $roleid) {
1.54      www      3749: 		  $expiretime=120;
                   3750:                }
                   3751: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3752:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3753:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3754: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3755:                }
1.620     albertel 3756:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3757:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3758: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3759:                        &log($env{'user.domain'},$env{'user.name'},
                   3760:                             $env{'user.home'},
1.57      www      3761:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3762:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3763:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3764: 		       return '';
                   3765:                    }
                   3766:                }
1.620     albertel 3767:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3768:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3769: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3770:                        &log($env{'user.domain'},$env{'user.name'},
                   3771:                             $env{'user.home'},
1.57      www      3772:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3773:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3774:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3775: 		       return '';
                   3776:                    }
                   3777:                }
                   3778: 	   }
1.29      www      3779:        }
1.52      www      3780:     }
                   3781:    
                   3782: #
                   3783: # Rest of the restrictions depend on selected course
                   3784: #
                   3785: 
1.620     albertel 3786:     unless ($env{'request.course.id'}) {
1.766     albertel 3787: 	if ($thisallowed eq 'A') {
                   3788: 	    return 'A';
                   3789: 	} else {
                   3790: 	    return '1';
                   3791: 	}
1.52      www      3792:     }
1.29      www      3793: 
1.52      www      3794: #
                   3795: # Now user is definitely in a course
                   3796: #
1.53      www      3797: 
                   3798: 
                   3799: # Course preferences
                   3800: 
                   3801:    if ($thisallowed=~/C/) {
1.620     albertel 3802:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3803:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3804:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3805: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3806: 	   if ($priv ne 'pch') { 
                   3807: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3808: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3809: 			$env{'request.course.id'});
                   3810: 	   }
1.237     www      3811:            return '';
                   3812:        }
                   3813: 
1.620     albertel 3814:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3815: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3816: 	   if ($priv ne 'pch') { 
                   3817: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3818: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3819: 			$env{'request.course.id'});
                   3820: 	   }
1.54      www      3821:            return '';
                   3822:        }
1.53      www      3823:    }
                   3824: 
                   3825: # Resource preferences
                   3826: 
                   3827:    if ($thisallowed=~/R/) {
1.620     albertel 3828:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3829:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3830: 	   if ($priv ne 'pch') { 
                   3831: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3832: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3833: 	   }
                   3834: 	   return '';
1.54      www      3835:        }
1.53      www      3836:    }
1.30      www      3837: 
1.246     www      3838: # Restricted by state or randomout?
1.30      www      3839: 
1.52      www      3840:    if ($thisallowed=~/X/) {
1.620     albertel 3841:       if ($env{'acc.randomout'}) {
1.579     albertel 3842: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3843:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3844:             return ''; 
                   3845:          }
1.247     www      3846:       }
                   3847:       if (&condval($statecond)) {
1.52      www      3848: 	 return '2';
                   3849:       } else {
                   3850:          return '';
                   3851:       }
                   3852:    }
1.30      www      3853: 
1.766     albertel 3854:     if ($thisallowed eq 'A') {
                   3855: 	return 'A';
                   3856:     }
1.52      www      3857:    return 'F';
1.232     www      3858: }
                   3859: 
1.710     albertel 3860: sub split_uri_for_cond {
                   3861:     my $uri=&deversion(&declutter(shift));
                   3862:     my @uriparts=split(/\//,$uri);
                   3863:     my $filename=pop(@uriparts);
                   3864:     my $pathname=join('/',@uriparts);
                   3865:     return ($pathname,$filename);
                   3866: }
1.232     www      3867: # --------------------------------------------------- Is a resource on the map?
                   3868: 
                   3869: sub is_on_map {
1.710     albertel 3870:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3871:     #Trying to find the conditional for the file
1.620     albertel 3872:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3873: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3874:     if ($match) {
1.289     bowersj2 3875: 	return (1,$1);
                   3876:     } else {
1.434     www      3877: 	return (0,0);
1.289     bowersj2 3878:     }
1.12      www      3879: }
                   3880: 
1.427     www      3881: # --------------------------------------------------------- Get symb from alias
                   3882: 
                   3883: sub get_symb_from_alias {
                   3884:     my $symb=shift;
                   3885:     my ($map,$resid,$url)=&decode_symb($symb);
                   3886: # Already is a symb
                   3887:     if ($url) { return $symb; }
                   3888: # Must be an alias
                   3889:     my $aliassymb='';
                   3890:     my %bighash;
1.620     albertel 3891:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3892:                             &GDBM_READER(),0640)) {
                   3893:         my $rid=$bighash{'mapalias_'.$symb};
                   3894: 	if ($rid) {
                   3895: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3896: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3897: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3898: 	}
                   3899:         untie %bighash;
                   3900:     }
                   3901:     return $aliassymb;
                   3902: }
                   3903: 
1.12      www      3904: # ----------------------------------------------------------------- Define Role
                   3905: 
                   3906: sub definerole {
                   3907:   if (allowed('mcr','/')) {
                   3908:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3909:     foreach (split(':',$sysrole)) {
1.21      www      3910: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3911:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3912:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3913: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3914:                return "refused:s:$crole&$cqual"; 
                   3915:             }
                   3916:         }
1.191     harris41 3917:     }
1.392     www      3918:     foreach (split(':',$domrole)) {
1.21      www      3919: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3920:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3921:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3922: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3923:                return "refused:d:$crole&$cqual"; 
                   3924:             }
                   3925:         }
1.191     harris41 3926:     }
1.392     www      3927:     foreach (split(':',$courole)) {
1.21      www      3928: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3929:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3930:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3931: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3932:                return "refused:c:$crole&$cqual"; 
                   3933:             }
                   3934:         }
1.191     harris41 3935:     }
1.620     albertel 3936:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3937:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3938: 	        "rolesdef_$rolename=".
                   3939:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3940:     return reply($command,$env{'user.home'});
1.12      www      3941:   } else {
                   3942:     return 'refused';
                   3943:   }
1.105     harris41 3944: }
                   3945: 
                   3946: # ---------------- Make a metadata query against the network of library servers
                   3947: 
                   3948: sub metadata_query {
1.244     matthew  3949:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3950:     my %rhash;
1.244     matthew  3951:     my @server_list = (defined($server_array) ? @$server_array
                   3952:                                               : keys(%libserv) );
                   3953:     for my $server (@server_list) {
1.118     harris41 3954: 	unless ($custom or $customshow) {
                   3955: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3956: 	    $rhash{$server}=$reply;
                   3957: 	}
                   3958: 	else {
                   3959: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3960: 			     &escape($custom).':'.&escape($customshow),
                   3961: 			     $server);
                   3962: 	    $rhash{$server}=$reply;
                   3963: 	}
1.112     harris41 3964:     }
1.118     harris41 3965:     return \%rhash;
1.240     www      3966: }
                   3967: 
                   3968: # ----------------------------------------- Send log queries and wait for reply
                   3969: 
                   3970: sub log_query {
                   3971:     my ($uname,$udom,$query,%filters)=@_;
                   3972:     my $uhome=&homeserver($uname,$udom);
                   3973:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3974:     my $uhost=$hostname{$uhome};
1.241     www      3975:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3976:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3977:                        $uhome);
1.479     albertel 3978:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3979:     return get_query_reply($queryid);
                   3980: }
                   3981: 
1.508     raeburn  3982: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3983: 
                   3984: sub fetch_enrollment_query {
1.511     raeburn  3985:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3986:     my $homeserver;
1.547     raeburn  3987:     my $maxtries = 1;
1.508     raeburn  3988:     if ($context eq 'automated') {
                   3989:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3990:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3991:     } else {
                   3992:         $homeserver = &homeserver($cnum,$dom);
                   3993:     }
1.506     raeburn  3994:     my $host=$hostname{$homeserver};
                   3995:     my $cmd = '';
                   3996:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3997:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3998:     }
                   3999:     $cmd =~ s/%%$//;
                   4000:     $cmd = &escape($cmd);
                   4001:     my $query = 'fetchenrollment';
1.620     albertel 4002:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4003:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4004:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4005:         return 'error: '.$queryid;
                   4006:     }
1.506     raeburn  4007:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4008:     my $tries = 1;
                   4009:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4010:         $reply = &get_query_reply($queryid);
                   4011:         $tries ++;
                   4012:     }
1.526     raeburn  4013:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4014:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4015:     } else {
1.515     raeburn  4016:         my @responses = split/:/,$reply;
                   4017:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   4018:             foreach (@responses) {
                   4019:                 my ($key,$value) = split/=/,$_;
                   4020:                 $$replyref{$key} = $value;
                   4021:             }
                   4022:         } else {
1.506     raeburn  4023:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   4024:             foreach (@responses) {
                   4025:                 my ($key,$value) = split/=/,$_;
                   4026:                 $$replyref{$key} = $value;
                   4027:                 if ($value > 0) {
                   4028:                     foreach (@{$$affiliatesref{$key}}) {
                   4029:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   4030:                         my $destname = $pathname.'/'.$filename;
                   4031:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4032:                         if ($xml_classlist =~ /^error/) {
                   4033:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4034:                         } else {
1.506     raeburn  4035:                             if ( open(FILE,">$destname") ) {
                   4036:                                 print FILE &unescape($xml_classlist);
                   4037:                                 close(FILE);
1.526     raeburn  4038:                             } else {
                   4039:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4040:                             }
                   4041:                         }
                   4042:                     }
                   4043:                 }
                   4044:             }
                   4045:         }
                   4046:         return 'ok';
                   4047:     }
                   4048:     return 'error';
                   4049: }
                   4050: 
1.242     www      4051: sub get_query_reply {
                   4052:     my $queryid=shift;
1.240     www      4053:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4054:     my $reply='';
                   4055:     for (1..100) {
                   4056: 	sleep 2;
                   4057:         if (-e $replyfile.'.end') {
1.448     albertel 4058: 	    if (open(my $fh,$replyfile)) {
1.240     www      4059:                $reply.=<$fh>;
1.448     albertel 4060:                close($fh);
1.240     www      4061: 	   } else { return 'error: reply_file_error'; }
1.242     www      4062:            return &unescape($reply);
                   4063: 	}
1.240     www      4064:     }
1.242     www      4065:     return 'timeout:'.$queryid;
1.240     www      4066: }
                   4067: 
                   4068: sub courselog_query {
1.241     www      4069: #
                   4070: # possible filters:
                   4071: # url: url or symb
                   4072: # username
                   4073: # domain
                   4074: # action: view, submit, grade
                   4075: # start: timestamp
                   4076: # end: timestamp
                   4077: #
1.240     www      4078:     my (%filters)=@_;
1.620     albertel 4079:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4080:     if ($filters{'url'}) {
                   4081: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4082:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4083:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4084:     }
1.620     albertel 4085:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4086:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4087:     return &log_query($cname,$cdom,'courselog',%filters);
                   4088: }
                   4089: 
                   4090: sub userlog_query {
                   4091:     my ($uname,$udom,%filters)=@_;
                   4092:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4093: }
                   4094: 
1.506     raeburn  4095: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4096: 
                   4097: sub auto_run {
1.508     raeburn  4098:     my ($cnum,$cdom) = @_;
                   4099:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4100:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4101:     return $response;
                   4102: }
1.776     albertel 4103: 
1.506     raeburn  4104: sub auto_get_sections {
1.508     raeburn  4105:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4106:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4107:     my @secs = ();
1.511     raeburn  4108:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4109:     unless ($response eq 'refused') {
                   4110:         @secs = split/:/,$response;
                   4111:     }
                   4112:     return @secs;
                   4113: }
1.776     albertel 4114: 
1.506     raeburn  4115: sub auto_new_course {
1.508     raeburn  4116:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4117:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4118:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4119:     return $response;
                   4120: }
1.776     albertel 4121: 
1.506     raeburn  4122: sub auto_validate_courseID {
1.508     raeburn  4123:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4124:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4125:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4126:     return $response;
                   4127: }
1.776     albertel 4128: 
1.506     raeburn  4129: sub auto_create_password {
1.508     raeburn  4130:     my ($cnum,$cdom,$authparam) = @_;
                   4131:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4132:     my $create_passwd = 0;
                   4133:     my $authchk = '';
1.511     raeburn  4134:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4135:     if ($response eq 'refused') {
                   4136:         $authchk = 'refused';
                   4137:     } else {
                   4138:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4139:     }
                   4140:     return ($authparam,$create_passwd,$authchk);
                   4141: }
                   4142: 
1.706     raeburn  4143: sub auto_photo_permission {
                   4144:     my ($cnum,$cdom,$students) = @_;
                   4145:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4146:     my ($outcome,$perm_reqd,$conditions) = 
                   4147: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4148:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4149: 	return (undef,undef);
                   4150:     }
1.706     raeburn  4151:     return ($outcome,$perm_reqd,$conditions);
                   4152: }
                   4153: 
                   4154: sub auto_checkphotos {
                   4155:     my ($uname,$udom,$pid) = @_;
                   4156:     my $homeserver = &homeserver($uname,$udom);
                   4157:     my ($result,$resulttype);
                   4158:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4159: 				   &escape($uname).':'.&escape($pid),
                   4160: 				   $homeserver));
1.709     albertel 4161:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4162: 	return (undef,undef);
                   4163:     }
1.706     raeburn  4164:     if ($outcome) {
                   4165:         ($result,$resulttype) = split(/:/,$outcome);
                   4166:     } 
                   4167:     return ($result,$resulttype);
                   4168: }
                   4169: 
                   4170: sub auto_photochoice {
                   4171:     my ($cnum,$cdom) = @_;
                   4172:     my $homeserver = &homeserver($cnum,$cdom);
                   4173:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4174: 						       &escape($cdom),
                   4175: 						       $homeserver)));
1.709     albertel 4176:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4177: 	return (undef,undef);
                   4178:     }
1.706     raeburn  4179:     return ($update,$comment);
                   4180: }
                   4181: 
                   4182: sub auto_photoupdate {
                   4183:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4184:     my $homeserver = &homeserver($cnum,$dom);
                   4185:     my $host=$hostname{$homeserver};
                   4186:     my $cmd = '';
                   4187:     my $maxtries = 1;
                   4188:     foreach (keys %{$affiliatesref}) {
                   4189:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4190:     }
                   4191:     $cmd =~ s/%%$//;
                   4192:     $cmd = &escape($cmd);
                   4193:     my $query = 'institutionalphotos';
                   4194:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4195:     unless ($queryid=~/^\Q$host\E\_/) {
                   4196:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4197:         return 'error: '.$queryid;
                   4198:     }
                   4199:     my $reply = &get_query_reply($queryid);
                   4200:     my $tries = 1;
                   4201:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4202:         $reply = &get_query_reply($queryid);
                   4203:         $tries ++;
                   4204:     }
                   4205:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4206:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4207:     } else {
                   4208:         my @responses = split(/:/,$reply);
                   4209:         my $outcome = shift(@responses); 
                   4210:         foreach my $item (@responses) {
                   4211:             my ($key,$value) = split(/=/,$item);
                   4212:             $$photo{$key} = $value;
                   4213:         }
                   4214:         return $outcome;
                   4215:     }
                   4216:     return 'error';
                   4217: }
                   4218: 
1.521     raeburn  4219: sub auto_instcode_format {
                   4220:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   4221:     my $courses = '';
1.772     raeburn  4222:     my @homeservers;
1.521     raeburn  4223:     if ($caller eq 'global') {
1.584     raeburn  4224:         foreach my $tryserver (keys %libserv) {
                   4225:             if ($hostdom{$tryserver} eq $codedom) {
1.772     raeburn  4226:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
                   4227:                     push(@homeservers,$tryserver);
                   4228:                 }
1.584     raeburn  4229:             }
                   4230:         }
1.521     raeburn  4231:     } else {
1.772     raeburn  4232:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4233:     }
                   4234:     foreach (keys %{$instcodes}) {
                   4235:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   4236:     }
                   4237:     chop($courses);
1.772     raeburn  4238:     my $ok_response = 0;
                   4239:     my $response;
                   4240:     while (@homeservers > 0 && $ok_response == 0) {
                   4241:         my $server = shift(@homeservers); 
                   4242:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4243:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4244:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
                   4245:                                                             split/:/,$response;
                   4246:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4247:             push(@{$codetitles},&str2array($codetitles_str));
                   4248:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4249:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4250:             $ok_response = 1;
                   4251:         }
                   4252:     }
                   4253:     if ($ok_response) {
1.521     raeburn  4254:         return 'ok';
1.772     raeburn  4255:     } else {
                   4256:         return $response;
1.521     raeburn  4257:     }
                   4258: }
                   4259: 
1.777     albertel 4260: sub auto_validate_class_sec {
1.773     raeburn  4261:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4262:     my $homeserver = &homeserver($cnum,$cdom);
                   4263:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4264:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4265:     return $response;
                   4266: }
                   4267: 
1.679     raeburn  4268: # ------------------------------------------------------- Course Group routines
                   4269: 
                   4270: sub get_coursegroups {
1.683     raeburn  4271:     my ($cdom,$cnum,$group) = @_;
                   4272:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4273: }
                   4274: 
                   4275: sub modify_coursegroup {
                   4276:     my ($cdom,$cnum,$groupsettings) = @_;
                   4277:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4278: }
                   4279: 
                   4280: sub modify_group_roles {
                   4281:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4282:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4283:     my $role = 'gr/'.&escape($userprivs);
                   4284:     my ($uname,$udom) = split(/:/,$user);
                   4285:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4286:     if ($result eq 'ok') {
                   4287:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4288:     }
1.679     raeburn  4289:     return $result;
                   4290: }
                   4291: 
                   4292: sub modify_coursegroup_membership {
                   4293:     my ($cdom,$cnum,$membership) = @_;
                   4294:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4295:     return $result;
                   4296: }
                   4297: 
1.682     raeburn  4298: sub get_active_groups {
                   4299:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4300:     my $now = time;
                   4301:     my %groups = ();
                   4302:     foreach my $key (keys(%env)) {
                   4303:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4304:             my ($start,$end) = split(/\./,$env{$key});
                   4305:             if (($end!=0) && ($end<$now)) { next; }
                   4306:             if (($start!=0) && ($start>$now)) { next; }
                   4307:             if ($1 eq $cdom && $2 eq $cnum) {
                   4308:                 $groups{$3} = $env{$key} ;
                   4309:             }
                   4310:         }
                   4311:     }
                   4312:     return %groups;
                   4313: }
                   4314: 
1.683     raeburn  4315: sub get_group_membership {
                   4316:     my ($cdom,$cnum,$group) = @_;
                   4317:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4318: }
                   4319: 
                   4320: sub get_users_groups {
                   4321:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4322:     my @usersgroups;
1.683     raeburn  4323:     my $cachetime=1800;
                   4324:     $courseid=~s/\_/\//g;
                   4325:     $courseid=~s/^(\w)/\/$1/;
                   4326: 
                   4327:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4328:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4329:     if (defined($cached)) {
1.734     albertel 4330:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4331:     } else {  
                   4332:         $grouplist = '';
                   4333:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4334:         my ($tmp) = keys(%roleshash);
                   4335:         if ($tmp=~/^error:/) {
                   4336:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4337:         } else {
                   4338:             my $access_end = $env{'course.'.$courseid.
                   4339:                                   '.default_enrollment_end_date'};
                   4340:             my $now = time;
1.734     albertel 4341:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4342:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4343:                     my $group = $1;
                   4344:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4345:                         my $start = $2;
                   4346:                         my $end = $1;
                   4347:                         if ($start == -1) { next; } # deleted from group
                   4348:                         if (($start!=0) && ($start>$now)) { next; }
                   4349:                         if (($end!=0) && ($end<$now)) {
                   4350:                             if ($access_end && $access_end < $now) {
                   4351:                                 if ($access_end - $end < 86400) {
                   4352:                                     push(@usersgroups,$group);
                   4353:                                 }
                   4354:                             }
                   4355:                             next;
                   4356:                         }
                   4357:                         push(@usersgroups,$group);
                   4358:                     }
1.683     raeburn  4359:                 }
                   4360:             }
1.733     raeburn  4361:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4362:             $grouplist = join(':',@usersgroups);
                   4363:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4364:         }
                   4365:     }
1.733     raeburn  4366:     return @usersgroups;
1.683     raeburn  4367: }
                   4368: 
                   4369: sub devalidate_getgroups_cache {
                   4370:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4371:     my $courseid = $cdom.'_'.$cnum;
                   4372:     $courseid=~s/\_/\//g;
                   4373:     $courseid=~s/^(\w)/\/$1/;
                   4374:     my $hashid="$udom:$uname:$courseid";
                   4375:     &devalidate_cache_new('getgroups',$hashid);
                   4376: }
                   4377: 
1.12      www      4378: # ------------------------------------------------------------------ Plain Text
                   4379: 
                   4380: sub plaintext {
1.742     raeburn  4381:     my ($short,$type,$cid) = @_;
1.758     albertel 4382:     if ($short =~ /^cr/) {
                   4383: 	return (split('/',$short))[-1];
                   4384:     }
1.742     raeburn  4385:     if (!defined($cid)) {
                   4386:         $cid = $env{'request.course.id'};
                   4387:     }
                   4388:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4389:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4390:                                           '.plaintext'});
                   4391:     }
                   4392:     my %rolenames = (
                   4393:                       Course => 'std',
                   4394:                       Group => 'alt1',
                   4395:                     );
                   4396:     if (defined($type) && 
                   4397:          defined($rolenames{$type}) && 
                   4398:          defined($prp{$short}{$rolenames{$type}})) {
                   4399:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4400:     } else {
                   4401:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4402:     }
1.12      www      4403: }
                   4404: 
                   4405: # ----------------------------------------------------------------- Assign Role
                   4406: 
                   4407: sub assignrole {
1.357     www      4408:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4409:     my $mrole;
                   4410:     if ($role =~ /^cr\//) {
1.393     www      4411:         my $cwosec=$url;
                   4412:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4413: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4414:            &logthis('Refused custom assignrole: '.
                   4415:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4416: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4417:            return 'refused'; 
                   4418:         }
1.21      www      4419:         $mrole='cr';
1.678     raeburn  4420:     } elsif ($role =~ /^gr\//) {
                   4421:         my $cwogrp=$url;
                   4422:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4423:         unless (&allowed('mdg',$cwogrp)) {
                   4424:             &logthis('Refused group assignrole: '.
                   4425:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4426:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4427:             return 'refused';
                   4428:         }
                   4429:         $mrole='gr';
1.21      www      4430:     } else {
1.82      www      4431:         my $cwosec=$url;
1.83      www      4432:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4433:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4434:            &logthis('Refused assignrole: '.
                   4435:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4436: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4437:            return 'refused'; 
                   4438:         }
1.21      www      4439:         $mrole=$role;
                   4440:     }
1.620     albertel 4441:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4442:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4443:     if ($end) { $command.='_'.$end; }
1.21      www      4444:     if ($start) {
                   4445: 	if ($end) { 
1.81      www      4446:            $command.='_'.$start; 
1.21      www      4447:         } else {
1.81      www      4448:            $command.='_0_'.$start;
1.21      www      4449:         }
                   4450:     }
1.739     raeburn  4451:     my $origstart = $start;
                   4452:     my $origend = $end;
1.357     www      4453: # actually delete
                   4454:     if ($deleteflag) {
1.373     www      4455: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4456: # modify command to delete the role
1.620     albertel 4457:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4458:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4459: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4460: # set start and finish to negative values for userrolelog
                   4461:            $start=-1;
                   4462:            $end=-1;
                   4463:         }
                   4464:     }
                   4465: # send command
1.349     www      4466:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4467: # log new user role if status is ok
1.349     www      4468:     if ($answer eq 'ok') {
1.663     raeburn  4469: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4470: # for course roles, perform group memberships changes triggered by role change.
                   4471:         unless ($role =~ /^gr/) {
                   4472:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4473:                                              $origstart);
                   4474:         }
1.349     www      4475:     }
                   4476:     return $answer;
1.169     harris41 4477: }
                   4478: 
                   4479: # -------------------------------------------------- Modify user authentication
1.197     www      4480: # Overrides without validation
                   4481: 
1.169     harris41 4482: sub modifyuserauth {
                   4483:     my ($udom,$uname,$umode,$upass)=@_;
                   4484:     my $uhome=&homeserver($uname,$udom);
1.197     www      4485:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4486:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4487:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4488:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4489:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4490: 		     &escape($upass),$uhome);
1.620     albertel 4491:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4492:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4493:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4494:     &log($udom,,$uname,$uhome,
1.620     albertel 4495:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4496:                                      $env{'user.name'}.', '.$umode.
1.197     www      4497:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4498:     unless ($reply eq 'ok') {
1.197     www      4499:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4500: 	return 'error: '.$reply;
                   4501:     }   
1.170     harris41 4502:     return 'ok';
1.80      www      4503: }
                   4504: 
1.81      www      4505: # --------------------------------------------------------------- Modify a user
1.80      www      4506: 
1.81      www      4507: sub modifyuser {
1.206     matthew  4508:     my ($udom,    $uname, $uid,
                   4509:         $umode,   $upass, $first,
                   4510:         $middle,  $last,  $gene,
1.387     www      4511:         $forceid, $desiredhome, $email)=@_;
1.198     www      4512:     $udom=~s/\W//g;
                   4513:     $uname=~s/\W//g;
1.81      www      4514:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4515:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4516: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4517:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4518:                                      ' desiredhome not specified'). 
1.620     albertel 4519:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4520:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4521:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4522: # ----------------------------------------------------------------- Create User
1.406     albertel 4523:     if (($uhome eq 'no_host') && 
                   4524: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4525:         my $unhome='';
1.209     matthew  4526:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4527:             $unhome = $desiredhome;
1.620     albertel 4528: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4529: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4530:         } else { # load balancing routine for determining $unhome
1.80      www      4531:             my $tryserver;
1.81      www      4532:             my $loadm=10000000;
1.80      www      4533:             foreach $tryserver (keys %libserv) {
                   4534: 	       if ($hostdom{$tryserver} eq $udom) {
                   4535:                   my $answer=reply('load',$tryserver);
                   4536:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4537: 		      $loadm=$answer;
                   4538:                       $unhome=$tryserver;
                   4539:                   }
                   4540: 	       }
                   4541: 	    }
                   4542:         }
                   4543:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4544: 	    return 'error: unable to find a home server for '.$uname.
                   4545:                    ' in domain '.$udom;
1.80      www      4546:         }
                   4547:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4548:                          &escape($upass),$unhome);
                   4549: 	unless ($reply eq 'ok') {
                   4550:             return 'error: '.$reply;
                   4551:         }   
1.230     stredwic 4552:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4553:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4554: 	    return 'error: unable verify users home machine.';
1.80      www      4555:         }
1.209     matthew  4556:     }   # End of creation of new user
1.80      www      4557: # ---------------------------------------------------------------------- Add ID
                   4558:     if ($uid) {
                   4559:        $uid=~tr/A-Z/a-z/;
                   4560:        my %uidhash=&idrget($udom,$uname);
1.196     www      4561:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4562:          && (!$forceid)) {
1.80      www      4563: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4564: 	      return 'error: user id "'.$uid.'" does not match '.
                   4565:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4566:           }
                   4567:        } else {
                   4568: 	  &idput($udom,($uname => $uid));
                   4569:        }
                   4570:     }
                   4571: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4572:     my @tmp=&get('environment',
1.134     albertel 4573: 		   ['firstname','middlename','lastname','generation'],
                   4574: 		   $udom,$uname);
1.313     matthew  4575:     my %names;
                   4576:     if ($tmp[0] =~ m/^error:.*/) { 
                   4577:         %names=(); 
                   4578:     } else {
                   4579:         %names = @tmp;
                   4580:     }
1.388     www      4581: #
                   4582: # Make sure to not trash student environment if instructor does not bother
                   4583: # to supply name and email information
                   4584: #
                   4585:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4586:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4587:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4588:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4589:     if ($email) {
                   4590:        $email=~s/[^\w\@\.\-\,]//gs;
                   4591:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4592: 			   $names{'critnotification'} = $email;
                   4593: 			   $names{'permanentemail'} = $email; }
                   4594:     }
1.134     albertel 4595:     my $reply = &put('environment', \%names, $udom,$uname);
                   4596:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4597:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4598:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4599:              $umode.', '.$first.', '.$middle.', '.
                   4600: 	     $last.', '.$gene.' by '.
1.620     albertel 4601:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4602:     return 'ok';
1.80      www      4603: }
                   4604: 
1.81      www      4605: # -------------------------------------------------------------- Modify student
1.80      www      4606: 
1.81      www      4607: sub modifystudent {
                   4608:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4609:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4610:     if (!$cid) {
1.620     albertel 4611: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4612: 	    return 'not_in_class';
                   4613: 	}
1.80      www      4614:     }
                   4615: # --------------------------------------------------------------- Make the user
1.81      www      4616:     my $reply=&modifyuser
1.209     matthew  4617: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4618:          $desiredhome,$email);
1.80      www      4619:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4620:     # This will cause &modify_student_enrollment to get the uid from the
                   4621:     # students environment
                   4622:     $uid = undef if (!$forceid);
1.455     albertel 4623:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4624: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4625:     return $reply;
                   4626: }
                   4627: 
                   4628: sub modify_student_enrollment {
1.515     raeburn  4629:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4630:     my ($cdom,$cnum,$chome);
                   4631:     if (!$cid) {
1.620     albertel 4632: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4633: 	    return 'not_in_class';
                   4634: 	}
1.620     albertel 4635: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4636: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4637:     } else {
                   4638: 	($cdom,$cnum)=split(/_/,$cid);
                   4639:     }
1.620     albertel 4640:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4641:     if (!$chome) {
1.457     raeburn  4642: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4643:     }
1.455     albertel 4644:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4645:     # Make sure the user exists
1.81      www      4646:     my $uhome=&homeserver($uname,$udom);
                   4647:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4648: 	return 'error: no such user';
                   4649:     }
1.297     matthew  4650:     # Get student data if we were not given enough information
                   4651:     if (!defined($first)  || $first  eq '' || 
                   4652:         !defined($last)   || $last   eq '' || 
                   4653:         !defined($uid)    || $uid    eq '' || 
                   4654:         !defined($middle) || $middle eq '' || 
                   4655:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4656:         # They did not supply us with enough data to enroll the student, so
                   4657:         # we need to pick up more information.
1.297     matthew  4658:         my %tmp = &get('environment',
1.294     matthew  4659:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4660:                        ,$udom,$uname);
                   4661: 
1.455     albertel 4662:         #foreach (keys(%tmp)) {
                   4663:         #    &logthis("key $_ = ".$tmp{$_});
                   4664:         #}
1.294     matthew  4665:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4666:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4667:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4668:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4669:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4670:     }
1.556     albertel 4671:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4672:     my $reply=cput('classlist',
                   4673: 		   {"$uname:$udom" => 
1.515     raeburn  4674: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4675: 		   $cdom,$cnum);
1.81      www      4676:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4677: 	return 'error: '.$reply;
1.652     albertel 4678:     } else {
                   4679: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4680:     }
1.297     matthew  4681:     # Add student role to user
1.83      www      4682:     my $uurl='/'.$cid;
1.81      www      4683:     $uurl=~s/\_/\//g;
                   4684:     if ($usec) {
                   4685: 	$uurl.='/'.$usec;
                   4686:     }
                   4687:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4688: }
                   4689: 
1.556     albertel 4690: sub format_name {
                   4691:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4692:     my $name;
                   4693:     if ($first ne 'lastname') {
                   4694: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4695:     } else {
                   4696: 	if ($lastname=~/\S/) {
                   4697: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4698: 	    $name=~s/\s+,/,/;
                   4699: 	} else {
                   4700: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4701: 	}
                   4702:     }
                   4703:     $name=~s/^\s+//;
                   4704:     $name=~s/\s+$//;
                   4705:     $name=~s/\s+/ /g;
                   4706:     return $name;
                   4707: }
                   4708: 
1.84      www      4709: # ------------------------------------------------- Write to course preferences
                   4710: 
                   4711: sub writecoursepref {
                   4712:     my ($courseid,%prefs)=@_;
                   4713:     $courseid=~s/^\///;
                   4714:     $courseid=~s/\_/\//g;
                   4715:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4716:     my $chome=homeserver($cnum,$cdomain);
                   4717:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4718: 	return 'error: no such course';
                   4719:     }
                   4720:     my $cstring='';
1.191     harris41 4721:     foreach (keys %prefs) {
1.84      www      4722: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4723:     }
1.84      www      4724:     $cstring=~s/\&$//;
                   4725:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4726: }
                   4727: 
                   4728: # ---------------------------------------------------------- Make/modify course
                   4729: 
                   4730: sub createcourse {
1.741     raeburn  4731:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4732:         $course_owner,$crstype)=@_;
1.84      www      4733:     $url=&declutter($url);
                   4734:     my $cid='';
1.264     matthew  4735:     unless (&allowed('ccc',$udom)) {
1.84      www      4736:         return 'refused';
                   4737:     }
                   4738: # ------------------------------------------------------------------- Create ID
1.674     www      4739:    my $uname=int(1+rand(9)).
                   4740:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4741:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4742:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4743: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4744:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4745:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4746:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4747:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4748:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4749:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4750:            return 'error: unable to generate unique course-ID';
                   4751:        } 
                   4752:    }
1.264     matthew  4753: # ------------------------------------------------ Check supplied server name
1.620     albertel 4754:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4755:     if (! exists($libserv{$course_server})) {
                   4756:         return 'error:bad server name '.$course_server;
                   4757:     }
1.84      www      4758: # ------------------------------------------------------------- Make the course
                   4759:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4760:                       $course_server);
1.84      www      4761:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4762:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4763:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4764: 	return 'error: no such course';
                   4765:     }
1.271     www      4766: # ----------------------------------------------------------------- Course made
1.516     raeburn  4767: # log existence
                   4768:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4769:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4770:                   &escape($crstype),$uhome);
1.358     www      4771:     &flushcourselogs();
                   4772: # set toplevel url
1.271     www      4773:     my $topurl=$url;
                   4774:     unless ($nonstandard) {
                   4775: # ------------------------------------------ For standard courses, make top url
                   4776:         my $mapurl=&clutter($url);
1.278     www      4777:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4778:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4779: <map>
                   4780: <resource id="1" type="start"></resource>
                   4781: <resource id="2" src="$mapurl"></resource>
                   4782: <resource id="3" type="finish"></resource>
                   4783: <link index="1" from="1" to="2"></link>
                   4784: <link index="2" from="2" to="3"></link>
                   4785: </map>
                   4786: ENDINITMAP
                   4787:         $topurl=&declutter(
1.638     albertel 4788:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4789:                           );
                   4790:     }
                   4791: # ----------------------------------------------------------- Write preferences
1.84      www      4792:     &writecoursepref($udom.'_'.$uname,
                   4793:                      ('description' => $description,
1.271     www      4794:                       'url'         => $topurl));
1.84      www      4795:     return '/'.$udom.'/'.$uname;
                   4796: }
                   4797: 
1.21      www      4798: # ---------------------------------------------------------- Assign Custom Role
                   4799: 
                   4800: sub assigncustomrole {
1.357     www      4801:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4802:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4803:                        $end,$start,$deleteflag);
1.21      www      4804: }
                   4805: 
                   4806: # ----------------------------------------------------------------- Revoke Role
                   4807: 
                   4808: sub revokerole {
1.357     www      4809:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4810:     my $now=time;
1.357     www      4811:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4812: }
                   4813: 
                   4814: # ---------------------------------------------------------- Revoke Custom Role
                   4815: 
                   4816: sub revokecustomrole {
1.357     www      4817:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4818:     my $now=time;
1.357     www      4819:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4820:            $deleteflag);
1.17      www      4821: }
                   4822: 
1.533     banghart 4823: # ------------------------------------------------------------ Disk usage
1.535     albertel 4824: sub diskusage {
1.533     banghart 4825:     my ($udom,$uname,$directoryRoot)=@_;
                   4826:     $directoryRoot =~ s/\/$//;
1.535     albertel 4827:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4828:     return $listing;
1.512     banghart 4829: }
                   4830: 
1.566     banghart 4831: sub is_locked {
                   4832:     my ($file_name, $domain, $user) = @_;
                   4833:     my @check;
                   4834:     my $is_locked;
                   4835:     push @check, $file_name;
1.613     albertel 4836:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4837: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4838:     my ($tmp)=keys(%locked);
                   4839:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4840:     
1.566     banghart 4841:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4842:         $is_locked = 'false';
                   4843:         foreach my $entry (@{$locked{$file_name}}) {
                   4844:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4845:                $is_locked = 'true';
                   4846:                last;
1.745     raeburn  4847:            }
                   4848:        }
1.566     banghart 4849:     } else {
                   4850:         $is_locked = 'false';
                   4851:     }
                   4852: }
                   4853: 
1.759     albertel 4854: sub declutter_portfile {
                   4855:     my ($file) = @_;
                   4856:     &logthis("got $file");
                   4857:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4858:     &logthis("ret $file");
                   4859:     return $file;
                   4860: }
                   4861: 
1.559     banghart 4862: # ------------------------------------------------------------- Mark as Read Only
                   4863: 
                   4864: sub mark_as_readonly {
                   4865:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4866:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4867:     my ($tmp)=keys(%current_permissions);
                   4868:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4869:     foreach my $file (@{$files}) {
1.759     albertel 4870: 	$file = &declutter_portfile($file);
1.561     banghart 4871:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4872:     }
1.613     albertel 4873:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4874:     return;
                   4875: }
                   4876: 
1.572     banghart 4877: # ------------------------------------------------------------Save Selected Files
                   4878: 
                   4879: sub save_selected_files {
                   4880:     my ($user, $path, @files) = @_;
                   4881:     my $filename = $user."savedfiles";
1.573     banghart 4882:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4883:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4884:     foreach my $file (@files) {
1.620     albertel 4885:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4886:     }
                   4887:     foreach my $file (@other_files) {
1.574     banghart 4888:         print (OUT $file."\n");
1.572     banghart 4889:     }
1.574     banghart 4890:     close (OUT);
1.572     banghart 4891:     return 'ok';
                   4892: }
                   4893: 
1.574     banghart 4894: sub clear_selected_files {
                   4895:     my ($user) = @_;
                   4896:     my $filename = $user."savedfiles";
                   4897:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4898:     print (OUT undef);
                   4899:     close (OUT);
                   4900:     return ("ok");    
                   4901: }
                   4902: 
1.572     banghart 4903: sub files_in_path {
                   4904:     my ($user, $path) = @_;
                   4905:     my $filename = $user."savedfiles";
                   4906:     my %return_files;
1.574     banghart 4907:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4908:     while (my $line_in = <IN>) {
1.574     banghart 4909:         chomp ($line_in);
                   4910:         my @paths_and_file = split (m!/!, $line_in);
                   4911:         my $file_part = pop (@paths_and_file);
                   4912:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4913:         $path_part.='/';
                   4914:         my $path_and_file = $path_part.$file_part;
                   4915:         if ($path_part eq $path) {
                   4916:             $return_files{$file_part}= 'selected';
                   4917:         }
                   4918:     }
1.574     banghart 4919:     close (IN);
                   4920:     return (\%return_files);
1.572     banghart 4921: }
                   4922: 
                   4923: # called in portfolio select mode, to show files selected NOT in current directory
                   4924: sub files_not_in_path {
                   4925:     my ($user, $path) = @_;
                   4926:     my $filename = $user."savedfiles";
                   4927:     my @return_files;
                   4928:     my $path_part;
1.574     banghart 4929:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4930:     while (<IN>) {
                   4931:         #ok, I know it's clunky, but I want it to work
                   4932:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4933:         my $file_part = pop (@paths_and_file);
                   4934:         chomp ($file_part);
                   4935:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4936:         $path_part .= '/';
                   4937:         my $path_and_file = $path_part.$file_part;
                   4938:         if ($path_part ne $path) {
1.574     banghart 4939:             push (@return_files, ($path_and_file));
1.572     banghart 4940:         }
                   4941:     }
1.574     banghart 4942:     close (OUT);
                   4943:     return (@return_files);
1.572     banghart 4944: }
                   4945: 
1.745     raeburn  4946: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4947: 
1.745     raeburn  4948: sub get_portfile_permissions {
                   4949:     my ($domain,$user) = @_;
1.613     albertel 4950:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4951:     my ($tmp)=keys(%current_permissions);
                   4952:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4953:     return \%current_permissions;
                   4954: }
                   4955: 
                   4956: #---------------------------------------------Get portfolio file access controls
                   4957: 
1.749     raeburn  4958: sub get_access_controls {
1.745     raeburn  4959:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4960:     my %access;
                   4961:     my $real_file = $file;
                   4962:     $file =~ s/\.meta$//;
1.745     raeburn  4963:     if (defined($file)) {
1.749     raeburn  4964:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4965:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 4966:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  4967:             }
                   4968:         }
1.745     raeburn  4969:     } else {
1.749     raeburn  4970:         foreach my $key (keys(%{$current_permissions})) {
                   4971:             if ($key =~ /\0accesscontrol$/) {
                   4972:                 if (defined($group)) {
                   4973:                     if ($key !~ m-^\Q$group\E/-) {
                   4974:                         next;
                   4975:                     }
                   4976:                 }
                   4977:                 my ($fullpath) = split(/\0/,$key);
                   4978:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4979:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4980:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4981:                     }
                   4982:                 }
                   4983:             }
                   4984:         }
                   4985:     }
                   4986:     return %access;
                   4987: }
                   4988: 
                   4989: sub modify_access_controls {
                   4990:     my ($file_name,$changes,$domain,$user)=@_;
                   4991:     my ($outcome,$deloutcome);
                   4992:     my %store_permissions;
                   4993:     my %new_values;
                   4994:     my %new_control;
                   4995:     my %translation;
                   4996:     my @deletions = ();
                   4997:     my $now = time;
                   4998:     if (exists($$changes{'activate'})) {
                   4999:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5000:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5001:             my $numnew = scalar(@newitems);
                   5002:             for (my $i=0; $i<$numnew; $i++) {
                   5003:                 my $newkey = $newitems[$i];
                   5004:                 my $newid = &Apache::loncommon::get_cgi_id();
                   5005:                 $newkey =~ s/^(\d+)/$newid/;
                   5006:                 $translation{$1} = $newid;
                   5007:                 $new_values{$file_name."\0".$newkey} = 
                   5008:                                           $$changes{'activate'}{$newitems[$i]};
                   5009:                 $new_control{$newkey} = $now;
                   5010:             }
                   5011:         }
                   5012:     }
                   5013:     my %todelete;
                   5014:     my %changed_items;
                   5015:     foreach my $action ('delete','update') {
                   5016:         if (exists($$changes{$action})) {
                   5017:             if (ref($$changes{$action}) eq 'HASH') {
                   5018:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5019:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5020:                     if ($action eq 'delete') { 
                   5021:                         $todelete{$itemnum} = 1;
                   5022:                     } else {
                   5023:                         $changed_items{$itemnum} = $key;
                   5024:                     }
                   5025:                 }
1.745     raeburn  5026:             }
                   5027:         }
1.749     raeburn  5028:     }
                   5029:     # get lock on access controls for file.
                   5030:     my $lockhash = {
                   5031:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5032:                                                        ':'.$env{'user.domain'},
                   5033:                    }; 
                   5034:     my $tries = 0;
                   5035:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5036:    
                   5037:     while (($gotlock ne 'ok') && $tries <3) {
                   5038:         $tries ++;
                   5039:         sleep 1;
                   5040:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5041:     }
                   5042:     if ($gotlock eq 'ok') {
                   5043:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5044:         my ($tmp)=keys(%curr_permissions);
                   5045:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5046:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5047:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5048:             if (ref($curr_controls) eq 'HASH') {
                   5049:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5050:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5051:                     if (defined($todelete{$itemnum})) {
                   5052:                         push(@deletions,$file_name."\0".$control_item);
                   5053:                     } else {
                   5054:                         if (defined($changed_items{$itemnum})) {
                   5055:                             $new_control{$changed_items{$itemnum}} = $now;
                   5056:                             push(@deletions,$file_name."\0".$control_item);
                   5057:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5058:                         } else {
                   5059:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5060:                         }
                   5061:                     }
1.745     raeburn  5062:                 }
                   5063:             }
                   5064:         }
1.749     raeburn  5065:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5066:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5067:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5068:         #  remove lock
                   5069:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5070:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5071:     } else {
                   5072:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5073:     }
1.749     raeburn  5074:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5075: }
                   5076: 
                   5077: #------------------------------------------------------Get Marked as Read Only
                   5078: 
                   5079: sub get_marked_as_readonly {
                   5080:     my ($domain,$user,$what,$group) = @_;
                   5081:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5082:     my @readonly_files;
1.629     banghart 5083:     my $cmp1=$what;
                   5084:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5085:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5086:         if (defined($group)) {
                   5087:             if ($file_name !~ m-^\Q$group\E/-) {
                   5088:                 next;
                   5089:             }
                   5090:         }
1.561     banghart 5091:         if (ref($value) eq "ARRAY"){
                   5092:             foreach my $stored_what (@{$value}) {
1.629     banghart 5093:                 my $cmp2=$stored_what;
1.759     albertel 5094:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5095:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5096:                 }
1.629     banghart 5097:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5098:                     push(@readonly_files, $file_name);
1.745     raeburn  5099:                     last;
1.563     banghart 5100:                 } elsif (!defined($what)) {
                   5101:                     push(@readonly_files, $file_name);
1.745     raeburn  5102:                     last;
1.561     banghart 5103:                 }
                   5104:             }
1.745     raeburn  5105:         }
1.561     banghart 5106:     }
                   5107:     return @readonly_files;
                   5108: }
1.577     banghart 5109: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5110: 
1.577     banghart 5111: sub get_marked_as_readonly_hash {
1.745     raeburn  5112:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5113:     my %readonly_files;
1.745     raeburn  5114:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5115:         if (defined($group)) {
                   5116:             if ($file_name !~ m-^\Q$group\E/-) {
                   5117:                 next;
                   5118:             }
                   5119:         }
1.577     banghart 5120:         if (ref($value) eq "ARRAY"){
                   5121:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5122:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5123:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5124:                         if ($lock_descriptor eq 'graded') {
                   5125:                             $readonly_files{$file_name} = 'graded';
                   5126:                         } elsif ($lock_descriptor eq 'handback') {
                   5127:                             $readonly_files{$file_name} = 'handback';
                   5128:                         } else {
                   5129:                             if (!exists($readonly_files{$file_name})) {
                   5130:                                 $readonly_files{$file_name} = 'locked';
                   5131:                             }
                   5132:                         }
1.745     raeburn  5133:                     }
1.750     banghart 5134:                 } 
1.577     banghart 5135:             }
                   5136:         } 
                   5137:     }
                   5138:     return %readonly_files;
                   5139: }
1.559     banghart 5140: # ------------------------------------------------------------ Unmark as Read Only
                   5141: 
                   5142: sub unmark_as_readonly {
1.629     banghart 5143:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5144:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5145:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5146:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5147:     my $symb_crs = $what;
                   5148:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5149:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5150:     my ($tmp)=keys(%current_permissions);
                   5151:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5152:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5153:     foreach my $file (@readonly_files) {
1.759     albertel 5154: 	my $clean_file = &declutter_portfile($file);
                   5155: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5156: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5157:         my @new_locks;
                   5158:         my @del_keys;
                   5159:         if (ref($current_locks) eq "ARRAY"){
                   5160:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5161:                 my $compare=$locker;
1.749     raeburn  5162:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5163:                     $compare=join('',@{$locker});
1.746     raeburn  5164:                     if ($compare ne $symb_crs) {
                   5165:                         push(@new_locks, $locker);
                   5166:                     }
1.563     banghart 5167:                 }
                   5168:             }
1.650     albertel 5169:             if (scalar(@new_locks) > 0) {
1.563     banghart 5170:                 $current_permissions{$file} = \@new_locks;
                   5171:             } else {
                   5172:                 push(@del_keys, $file);
1.613     albertel 5173:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5174:                 delete($current_permissions{$file});
1.563     banghart 5175:             }
                   5176:         }
1.561     banghart 5177:     }
1.613     albertel 5178:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5179:     return;
                   5180: }
1.512     banghart 5181: 
1.17      www      5182: # ------------------------------------------------------------ Directory lister
                   5183: 
                   5184: sub dirlist {
1.253     stredwic 5185:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5186: 
1.18      www      5187:     $uri=~s/^\///;
                   5188:     $uri=~s/\/$//;
1.253     stredwic 5189:     my ($udom, $uname);
                   5190:     (undef,$udom,$uname)=split(/\//,$uri);
                   5191:     if(defined($userdomain)) {
                   5192:         $udom = $userdomain;
                   5193:     }
                   5194:     if(defined($username)) {
                   5195:         $uname = $username;
                   5196:     }
                   5197: 
                   5198:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5199:     if(defined($alternateDirectoryRoot)) {
                   5200:         $dirRoot = $alternateDirectoryRoot;
                   5201:         $dirRoot =~ s/\/$//;
1.751     banghart 5202:     }
1.253     stredwic 5203: 
                   5204:     if($udom) {
                   5205:         if($uname) {
1.605     matthew  5206:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5207:                               homeserver($uname,$udom));
1.605     matthew  5208:             my @listing_results;
                   5209:             if ($listing eq 'unknown_cmd') {
                   5210:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5211:                                homeserver($uname,$udom));
                   5212:                 @listing_results = split(/:/,$listing);
                   5213:             } else {
                   5214:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5215:             }
                   5216:             return @listing_results;
1.253     stredwic 5217:         } elsif(!defined($alternateDirectoryRoot)) {
                   5218:             my $tryserver;
                   5219:             my %allusers=();
                   5220:             foreach $tryserver (keys %libserv) {
                   5221:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5222:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5223:                                       $udom, $tryserver);
1.605     matthew  5224:                     my @listing_results;
                   5225:                     if ($listing eq 'unknown_cmd') {
                   5226:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5227:                                        $udom, $tryserver);
                   5228:                         @listing_results = split(/:/,$listing);
                   5229:                     } else {
                   5230:                         @listing_results =
                   5231:                             map { &unescape($_); } split(/:/,$listing);
                   5232:                     }
                   5233:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5234:                         $listing_results[0] ne 'empty'       &&
                   5235:                         $listing_results[0] ne 'con_lost') {
                   5236:                         foreach (@listing_results) {
1.253     stredwic 5237:                             my ($entry,@stat)=split(/&/,$_);
                   5238:                             $allusers{$entry}=1;
                   5239:                         }
                   5240:                     }
1.191     harris41 5241:                 }
1.253     stredwic 5242:             }
                   5243:             my $alluserstr='';
                   5244:             foreach (sort keys %allusers) {
                   5245:                 $alluserstr.=$_.'&user:';
                   5246:             }
                   5247:             $alluserstr=~s/:$//;
                   5248:             return split(/:/,$alluserstr);
                   5249:         } else {
                   5250:             my @emptyResults = ();
                   5251:             push(@emptyResults, 'missing user name');
                   5252:             return split(':',@emptyResults);
                   5253:         }
                   5254:     } elsif(!defined($alternateDirectoryRoot)) {
                   5255:         my $tryserver;
                   5256:         my %alldom=();
                   5257:         foreach $tryserver (keys %libserv) {
                   5258:             $alldom{$hostdom{$tryserver}}=1;
                   5259:         }
                   5260:         my $alldomstr='';
                   5261:         foreach (sort keys %alldom) {
1.397     albertel 5262:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5263:         }
                   5264:         $alldomstr=~s/:$//;
                   5265:         return split(/:/,$alldomstr);       
                   5266:     } else {
                   5267:         my @emptyResults = ();
                   5268:         push(@emptyResults, 'missing domain');
                   5269:         return split(':',@emptyResults);
1.275     stredwic 5270:     }
                   5271: }
                   5272: 
                   5273: # --------------------------------------------- GetFileTimestamp
                   5274: # This function utilizes dirlist and returns the date stamp for
                   5275: # when it was last modified.  It will also return an error of -1
                   5276: # if an error occurs
                   5277: 
1.410     matthew  5278: ##
                   5279: ## FIXME: This subroutine assumes its caller knows something about the
                   5280: ## directory structure of the home server for the student ($root).
                   5281: ## Not a good assumption to make.  Since this is for looking up files
                   5282: ## in user directories, the full path should be constructed by lond, not
                   5283: ## whatever machine we request data from.
                   5284: ##
1.275     stredwic 5285: sub GetFileTimestamp {
                   5286:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5287:     $studentDomain=~s/\W//g;
                   5288:     $studentName=~s/\W//g;
                   5289:     my $subdir=$studentName.'__';
                   5290:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5291:     my $proname="$studentDomain/$subdir/$studentName";
                   5292:     $proname .= '/'.$filename;
1.375     matthew  5293:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5294:                                               $studentName, $root);
1.275     stredwic 5295:     my @stats = split('&', $fileStat);
                   5296:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5297:         # @stats contains first the filename, then the stat output
                   5298:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5299:     } else {
                   5300:         return -1;
1.253     stredwic 5301:     }
1.26      www      5302: }
                   5303: 
1.712     albertel 5304: sub stat_file {
                   5305:     my ($uri) = @_;
1.787     albertel 5306:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5307: 
1.712     albertel 5308:     my ($udom,$uname,$file,$dir);
                   5309:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5310: 	($udom,$uname,$file) =
                   5311: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5312: 	$file = 'userfiles/'.$file;
1.740     www      5313: 	$dir = &propath($udom,$uname);
1.712     albertel 5314:     }
                   5315:     if ($uri =~ m-^/res/-) {
                   5316: 	($udom,$uname) = 
                   5317: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5318: 	$file = $uri;
                   5319:     }
                   5320: 
                   5321:     if (!$udom || !$uname || !$file) {
                   5322: 	# unable to handle the uri
                   5323: 	return ();
                   5324:     }
                   5325: 
                   5326:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5327:     my @stats = split('&', $result);
1.721     banghart 5328:     
1.712     albertel 5329:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5330: 	shift(@stats); #filename is first
                   5331: 	return @stats;
                   5332:     }
                   5333:     return ();
                   5334: }
                   5335: 
1.26      www      5336: # -------------------------------------------------------- Value of a Condition
                   5337: 
1.713     albertel 5338: # gets the value of a specific preevaluated condition
                   5339: #    stored in the string  $env{user.state.<cid>}
                   5340: # or looks up a condition reference in the bighash and if if hasn't
                   5341: # already been evaluated recurses into docondval to get the value of
                   5342: # the condition, then memoizing it to 
                   5343: #   $env{user.state.<cid>.<condition>}
1.40      www      5344: sub directcondval {
                   5345:     my $number=shift;
1.620     albertel 5346:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5347: 	&Apache::lonuserstate::evalstate();
                   5348:     }
1.713     albertel 5349:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5350: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5351:     } elsif ($number =~ /^_/) {
                   5352: 	my $sub_condition;
                   5353: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5354: 		&GDBM_READER(),0640)) {
                   5355: 	    $sub_condition=$bighash{'conditions'.$number};
                   5356: 	    untie(%bighash);
                   5357: 	}
                   5358: 	my $value = &docondval($sub_condition);
                   5359: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5360: 	return $value;
                   5361:     }
1.620     albertel 5362:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5363:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5364:     } else {
                   5365:        return 2;
                   5366:     }
                   5367: }
                   5368: 
1.713     albertel 5369: # get the collection of conditions for this resource
1.26      www      5370: sub condval {
                   5371:     my $condidx=shift;
1.54      www      5372:     my $allpathcond='';
1.713     albertel 5373:     foreach my $cond (split(/\|/,$condidx)) {
                   5374: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5375: 	    $allpathcond.=
                   5376: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5377: 	}
1.191     harris41 5378:     }
1.54      www      5379:     $allpathcond=~s/\|$//;
1.713     albertel 5380:     return &docondval($allpathcond);
                   5381: }
                   5382: 
                   5383: #evaluates an expression of conditions
                   5384: sub docondval {
                   5385:     my ($allpathcond) = @_;
                   5386:     my $result=0;
                   5387:     if ($env{'request.course.id'}
                   5388: 	&& defined($allpathcond)) {
                   5389: 	my $operand='|';
                   5390: 	my @stack;
                   5391: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5392: 	    if ($chunk eq '(') {
                   5393: 		push @stack,($operand,$result);
                   5394: 	    } elsif ($chunk eq ')') {
                   5395: 		my $before=pop @stack;
                   5396: 		if (pop @stack eq '&') {
                   5397: 		    $result=$result>$before?$before:$result;
                   5398: 		} else {
                   5399: 		    $result=$result>$before?$result:$before;
                   5400: 		}
                   5401: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5402: 		$operand=$chunk;
                   5403: 	    } else {
                   5404: 		my $new=directcondval($chunk);
                   5405: 		if ($operand eq '&') {
                   5406: 		    $result=$result>$new?$new:$result;
                   5407: 		} else {
                   5408: 		    $result=$result>$new?$result:$new;
                   5409: 		}
                   5410: 	    }
                   5411: 	}
1.26      www      5412:     }
                   5413:     return $result;
1.421     albertel 5414: }
                   5415: 
                   5416: # ---------------------------------------------------- Devalidate courseresdata
                   5417: 
                   5418: sub devalidatecourseresdata {
                   5419:     my ($coursenum,$coursedomain)=@_;
                   5420:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5421:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5422: }
                   5423: 
1.763     www      5424: 
1.200     www      5425: # --------------------------------------------------- Course Resourcedata Query
                   5426: 
1.624     albertel 5427: sub get_courseresdata {
                   5428:     my ($coursenum,$coursedomain)=@_;
1.200     www      5429:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5430:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5431:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5432:     my %dumpreply;
1.417     albertel 5433:     unless (defined($cached)) {
1.624     albertel 5434: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5435: 	$result=\%dumpreply;
1.251     albertel 5436: 	my ($tmp) = keys(%dumpreply);
                   5437: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5438: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5439: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5440: 	    return $tmp;
1.416     albertel 5441: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5442: 	    $result=undef;
1.599     albertel 5443: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5444: 	}
                   5445:     }
1.624     albertel 5446:     return $result;
                   5447: }
                   5448: 
1.633     albertel 5449: sub devalidateuserresdata {
                   5450:     my ($uname,$udom)=@_;
                   5451:     my $hashid="$udom:$uname";
                   5452:     &devalidate_cache_new('userres',$hashid);
                   5453: }
                   5454: 
1.624     albertel 5455: sub get_userresdata {
                   5456:     my ($uname,$udom)=@_;
                   5457:     #most student don\'t have any data set, check if there is some data
                   5458:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5459: 
                   5460:     my $hashid="$udom:$uname";
                   5461:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5462:     if (!defined($cached)) {
                   5463: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5464: 	$result=\%resourcedata;
                   5465: 	&do_cache_new('userres',$hashid,$result,600);
                   5466:     }
                   5467:     my ($tmp)=keys(%$result);
                   5468:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5469: 	return $result;
                   5470:     }
                   5471:     #error 2 occurs when the .db doesn't exist
                   5472:     if ($tmp!~/error: 2 /) {
1.672     albertel 5473: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5474: 		 " Trying to get resource data for ".
                   5475: 		 $uname." at ".$udom.": ".
                   5476: 		 $tmp."</font>");
                   5477:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5478: 	#&EXT_cache_set($udom,$uname);
                   5479: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5480: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5481:     }
                   5482:     return $tmp;
                   5483: }
                   5484: 
                   5485: sub resdata {
                   5486:     my ($name,$domain,$type,@which)=@_;
                   5487:     my $result;
                   5488:     if ($type eq 'course') {
                   5489: 	$result=&get_courseresdata($name,$domain);
                   5490:     } elsif ($type eq 'user') {
                   5491: 	$result=&get_userresdata($name,$domain);
                   5492:     }
                   5493:     if (!ref($result)) { return $result; }    
1.251     albertel 5494:     foreach my $item (@which) {
1.417     albertel 5495: 	if (defined($result->{$item})) {
                   5496: 	    return $result->{$item};
1.251     albertel 5497: 	}
1.250     albertel 5498:     }
1.291     albertel 5499:     return undef;
1.200     www      5500: }
                   5501: 
1.379     matthew  5502: #
                   5503: # EXT resource caching routines
                   5504: #
                   5505: 
                   5506: sub clear_EXT_cache_status {
1.383     albertel 5507:     &delenv('cache.EXT.');
1.379     matthew  5508: }
                   5509: 
                   5510: sub EXT_cache_status {
                   5511:     my ($target_domain,$target_user) = @_;
1.383     albertel 5512:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5513:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5514:         # We know already the user has no data
                   5515:         return 1;
                   5516:     } else {
                   5517:         return 0;
                   5518:     }
                   5519: }
                   5520: 
                   5521: sub EXT_cache_set {
                   5522:     my ($target_domain,$target_user) = @_;
1.383     albertel 5523:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5524:     #&appenv($cachename => time);
1.379     matthew  5525: }
                   5526: 
1.28      www      5527: # --------------------------------------------------------- Value of a Variable
1.58      www      5528: sub EXT {
1.715     albertel 5529: 
1.395     albertel 5530:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5531:     unless ($varname) { return ''; }
1.218     albertel 5532:     #get real user name/domain, courseid and symb
                   5533:     my $courseid;
1.359     albertel 5534:     my $publicuser;
1.427     www      5535:     if ($symbparm) {
                   5536: 	$symbparm=&get_symb_from_alias($symbparm);
                   5537:     }
1.218     albertel 5538:     if (!($uname && $udom)) {
1.790   ! albertel 5539:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5540:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5541:     } else {
1.620     albertel 5542: 	$courseid=$env{'request.course.id'};
1.218     albertel 5543:     }
1.48      www      5544:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5545:     my $rest;
1.320     albertel 5546:     if (defined($therest[0])) {
1.48      www      5547:        $rest=join('.',@therest);
                   5548:     } else {
                   5549:        $rest='';
                   5550:     }
1.320     albertel 5551: 
1.57      www      5552:     my $qualifierrest=$qualifier;
                   5553:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5554:     my $spacequalifierrest=$space;
                   5555:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5556:     if ($realm eq 'user') {
1.48      www      5557: # --------------------------------------------------------------- user.resource
                   5558: 	if ($space eq 'resource') {
1.651     albertel 5559: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5560: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5561: 		 &&
1.744     albertel 5562: 		 ($symbparm eq &symbread()) ) {	
                   5563: 		# if we are in the middle of processing the resource the
                   5564: 		# get the value we are planning on committing
                   5565:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5566:                     return $Apache::lonhomework::results{$qualifierrest};
                   5567:                 } else {
                   5568:                     return $Apache::lonhomework::history{$qualifierrest};
                   5569:                 }
1.335     albertel 5570: 	    } else {
1.359     albertel 5571: 		my %restored;
1.620     albertel 5572: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5573: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5574: 		} else {
                   5575: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5576: 		}
1.335     albertel 5577: 		return $restored{$qualifierrest};
                   5578: 	    }
1.48      www      5579: # ----------------------------------------------------------------- user.access
                   5580:         } elsif ($space eq 'access') {
1.218     albertel 5581: 	    # FIXME - not supporting calls for a specific user
1.48      www      5582:             return &allowed($qualifier,$rest);
                   5583: # ------------------------------------------ user.preferences, user.environment
                   5584:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5585: 	    if (($uname eq $env{'user.name'}) &&
                   5586: 		($udom eq $env{'user.domain'})) {
                   5587: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5588: 	    } else {
1.359     albertel 5589: 		my %returnhash;
                   5590: 		if (!$publicuser) {
                   5591: 		    %returnhash=&userenvironment($udom,$uname,
                   5592: 						 $qualifierrest);
                   5593: 		}
1.218     albertel 5594: 		return $returnhash{$qualifierrest};
                   5595: 	    }
1.48      www      5596: # ----------------------------------------------------------------- user.course
                   5597:         } elsif ($space eq 'course') {
1.218     albertel 5598: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5599:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5600: # ------------------------------------------------------------------- user.role
                   5601:         } elsif ($space eq 'role') {
1.218     albertel 5602: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5603:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5604:             if ($qualifier eq 'value') {
                   5605: 		return $role;
                   5606:             } elsif ($qualifier eq 'extent') {
                   5607:                 return $where;
                   5608:             }
                   5609: # ----------------------------------------------------------------- user.domain
                   5610:         } elsif ($space eq 'domain') {
1.218     albertel 5611:             return $udom;
1.48      www      5612: # ------------------------------------------------------------------- user.name
                   5613:         } elsif ($space eq 'name') {
1.218     albertel 5614:             return $uname;
1.48      www      5615: # ---------------------------------------------------- Any other user namespace
1.29      www      5616:         } else {
1.359     albertel 5617: 	    my %reply;
                   5618: 	    if (!$publicuser) {
                   5619: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5620: 	    }
                   5621: 	    return $reply{$qualifierrest};
1.48      www      5622:         }
1.236     www      5623:     } elsif ($realm eq 'query') {
                   5624: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5625:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5626: 						[$spacequalifierrest]);
1.620     albertel 5627: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5628:    } elsif ($realm eq 'request') {
1.48      www      5629: # ------------------------------------------------------------- request.browser
                   5630:         if ($space eq 'browser') {
1.430     www      5631: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5632: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5633: 		    return 1;
                   5634: 		} else {
                   5635: 		    return 0;
                   5636: 		}
                   5637: 	    } else {
1.620     albertel 5638: 		return $env{'browser.'.$qualifier};
1.430     www      5639: 	    }
1.57      www      5640: # ------------------------------------------------------------ request.filename
                   5641:         } else {
1.620     albertel 5642:             return $env{'request.'.$spacequalifierrest};
1.29      www      5643:         }
1.28      www      5644:     } elsif ($realm eq 'course') {
1.48      www      5645: # ---------------------------------------------------------- course.description
1.620     albertel 5646:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5647:     } elsif ($realm eq 'resource') {
1.165     www      5648: 
1.620     albertel 5649: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5650: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5651: 	}
1.693     albertel 5652: 
                   5653: 	if ($space eq 'title') {
                   5654: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5655: 	    return &gettitle($symbparm);
                   5656: 	}
                   5657: 	
                   5658: 	if ($space eq 'map') {
                   5659: 	    my ($map) = &decode_symb($symbparm);
                   5660: 	    return &symbread($map);
                   5661: 	}
                   5662: 
                   5663: 	my ($section, $group, @groups);
1.593     albertel 5664: 	my ($courselevelm,$courselevel);
1.539     albertel 5665: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5666: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5667: 
1.218     albertel 5668: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5669: 
1.60      www      5670: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5671: 	    my $symbp=$symbparm;
1.735     albertel 5672: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5673: 
                   5674: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5675: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5676: 
1.620     albertel 5677: 	    if (($env{'user.name'} eq $uname) &&
                   5678: 		($env{'user.domain'} eq $udom)) {
                   5679: 		$section=$env{'request.course.sec'};
1.733     raeburn  5680:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5681:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5682: 	    } else {
1.539     albertel 5683: 		if (! defined($usection)) {
1.551     albertel 5684: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5685: 		} else {
                   5686: 		    $section = $usection;
                   5687: 		}
1.733     raeburn  5688:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5689: 	    }
                   5690: 
                   5691: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5692: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5693: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5694: 
1.593     albertel 5695: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5696: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5697: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5698: 
1.60      www      5699: # ----------------------------------------------------------- first, check user
1.624     albertel 5700: 
                   5701: 	    my $userreply=&resdata($uname,$udom,'user',
                   5702: 				       ($courselevelr,$courselevelm,
                   5703: 					$courselevel));
                   5704: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5705: 
1.594     albertel 5706: # ------------------------------------------------ second, check some of course
1.684     raeburn  5707:             my $coursereply;
1.691     raeburn  5708:             if (@groups > 0) {
                   5709:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5710:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5711:                 if (defined($coursereply)) { return $coursereply; }
                   5712:             }
1.96      www      5713: 
1.684     raeburn  5714: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5715: 				     $env{'course.'.$courseid.'.domain'},
                   5716: 				     'course',
                   5717: 				     ($seclevelr,$seclevelm,$seclevel,
                   5718: 				      $courselevelr));
1.287     albertel 5719: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5720: 
1.60      www      5721: # ------------------------------------------------------ third, check map parms
1.218     albertel 5722: 	    my %parmhash=();
                   5723: 	    my $thisparm='';
                   5724: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5725: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5726: 		    &GDBM_READER(),0640)) {
1.218     albertel 5727: 		$thisparm=$parmhash{$symbparm};
                   5728: 		untie(%parmhash);
                   5729: 	    }
                   5730: 	    if ($thisparm) { return $thisparm; }
                   5731: 	}
1.594     albertel 5732: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5733: 
1.218     albertel 5734: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5735: 	my $filename;
                   5736: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5737: 	if ($symbparm) {
1.409     www      5738: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5739: 	} else {
1.620     albertel 5740: 	    $filename=$env{'request.filename'};
1.282     albertel 5741: 	}
                   5742: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5743: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5744: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5745: 	if (defined($metadata)) { return $metadata; }
1.142     www      5746: 
1.594     albertel 5747: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5748: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5749: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5750: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5751: 				     $env{'course.'.$courseid.'.domain'},
                   5752: 				     'course',
                   5753: 				     ($courselevelm,$courselevel));
1.593     albertel 5754: 	    if (defined($coursereply)) { return $coursereply; }
                   5755: 	}
1.145     www      5756: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5757: 	unless ($space eq '0') {
1.336     albertel 5758: 	    my @parts=split(/_/,$space);
                   5759: 	    my $id=pop(@parts);
                   5760: 	    my $part=join('_',@parts);
                   5761: 	    if ($part eq '') { $part='0'; }
                   5762: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5763: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5764: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5765: 	}
1.395     albertel 5766: 	if ($recurse) { return undef; }
                   5767: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5768: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5769: 
1.48      www      5770: # ---------------------------------------------------- Any other user namespace
                   5771:     } elsif ($realm eq 'environment') {
                   5772: # ----------------------------------------------------------------- environment
1.620     albertel 5773: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5774: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5775: 	} else {
1.770     albertel 5776: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5777: 		return '';
                   5778: 	    }
1.219     albertel 5779: 	    my %returnhash=&userenvironment($udom,$uname,
                   5780: 					    $spacequalifierrest);
                   5781: 	    return $returnhash{$spacequalifierrest};
                   5782: 	}
1.28      www      5783:     } elsif ($realm eq 'system') {
1.48      www      5784: # ----------------------------------------------------------------- system.time
                   5785: 	if ($space eq 'time') {
                   5786: 	    return time;
                   5787:         }
1.696     albertel 5788:     } elsif ($realm eq 'server') {
                   5789: # ----------------------------------------------------------------- system.time
                   5790: 	if ($space eq 'name') {
                   5791: 	    return $ENV{'SERVER_NAME'};
                   5792:         }
1.28      www      5793:     }
1.48      www      5794:     return '';
1.61      www      5795: }
                   5796: 
1.691     raeburn  5797: sub check_group_parms {
                   5798:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5799:     my @groupitems = ();
                   5800:     my $resultitem;
                   5801:     my @levels = ($symbparm,$mapparm,$what);
                   5802:     foreach my $group (@{$groups}) {
                   5803:         foreach my $level (@levels) {
                   5804:              my $item = $courseid.'.['.$group.'].'.$level;
                   5805:              push(@groupitems,$item);
                   5806:         }
                   5807:     }
                   5808:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5809:                             $env{'course.'.$courseid.'.domain'},
                   5810:                                      'course',@groupitems);
                   5811:     return $coursereply;
                   5812: }
                   5813: 
                   5814: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5815:     my ($courseid,@groups) = @_;
                   5816:     @groups = sort(@groups);
1.691     raeburn  5817:     return @groups;
                   5818: }
                   5819: 
1.395     albertel 5820: sub packages_tab_default {
                   5821:     my ($uri,$varname)=@_;
                   5822:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5823: 
                   5824:     my (@extension,@specifics,$do_default);
                   5825:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5826: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5827: 	if ($pack_type eq 'default') {
                   5828: 	    $do_default=1;
                   5829: 	} elsif ($pack_type eq 'extension') {
                   5830: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5831: 	} else {
                   5832: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5833: 	}
                   5834:     }
                   5835:     # first look for a package that matches the requested part id
                   5836:     foreach my $package (@specifics) {
                   5837: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5838: 	next if ($pack_part ne $part);
                   5839: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5840: 	    return $packagetab{"$pack_type&$name&default"};
                   5841: 	}
                   5842:     }
                   5843:     # look for any possible matching non extension_ package
                   5844:     foreach my $package (@specifics) {
                   5845: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5846: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5847: 	    return $packagetab{"$pack_type&$name&default"};
                   5848: 	}
1.585     albertel 5849: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5850: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5851: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5852: 	}
                   5853:     }
1.738     albertel 5854:     # look for any posible extension_ match
                   5855:     foreach my $package (@extension) {
                   5856: 	my ($package,$pack_type)=@{$package};
                   5857: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5858: 	    return $packagetab{"$pack_type&$name&default"};
                   5859: 	}
                   5860: 	if (defined($packagetab{$package."&$name&default"})) {
                   5861: 	    return $packagetab{$package."&$name&default"};
                   5862: 	}
                   5863:     }
                   5864:     # look for a global default setting
                   5865:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5866: 	return $packagetab{"default&$name&default"};
                   5867:     }
1.395     albertel 5868:     return undef;
                   5869: }
                   5870: 
1.334     albertel 5871: sub add_prefix_and_part {
                   5872:     my ($prefix,$part)=@_;
                   5873:     my $keyroot;
                   5874:     if (defined($prefix) && $prefix !~ /^__/) {
                   5875: 	# prefix that has a part already
                   5876: 	$keyroot=$prefix;
                   5877:     } elsif (defined($prefix)) {
                   5878: 	# prefix that is missing a part
                   5879: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5880:     } else {
                   5881: 	# no prefix at all
                   5882: 	if (defined($part)) { $keyroot='_'.$part; }
                   5883:     }
                   5884:     return $keyroot;
                   5885: }
                   5886: 
1.71      www      5887: # ---------------------------------------------------------------- Get metadata
                   5888: 
1.599     albertel 5889: my %metaentry;
1.71      www      5890: sub metadata {
1.176     www      5891:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5892:     $uri=&declutter($uri);
1.288     albertel 5893:     # if it is a non metadata possible uri return quickly
1.529     albertel 5894:     if (($uri eq '') || 
                   5895: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5896: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5897:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5898: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5899: 	return undef;
1.288     albertel 5900:     }
1.73      www      5901:     my $filename=$uri;
                   5902:     $uri=~s/\.meta$//;
1.172     www      5903: #
                   5904: # Is the metadata already cached?
1.177     www      5905: # Look at timestamp of caching
1.172     www      5906: # Everything is cached by the main uri, libraries are never directly cached
                   5907: #
1.428     albertel 5908:     if (!defined($liburi)) {
1.599     albertel 5909: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5910: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5911:     }
                   5912:     {
1.172     www      5913: #
                   5914: # Is this a recursive call for a library?
                   5915: #
1.599     albertel 5916: #	if (! exists($metacache{$uri})) {
                   5917: #	    $metacache{$uri}={};
                   5918: #	}
1.171     www      5919:         if ($liburi) {
                   5920: 	    $liburi=&declutter($liburi);
                   5921:             $filename=$liburi;
1.401     bowersj2 5922:         } else {
1.599     albertel 5923: 	    &devalidate_cache_new('meta',$uri);
                   5924: 	    undef(%metaentry);
1.401     bowersj2 5925: 	}
1.140     www      5926:         my %metathesekeys=();
1.73      www      5927:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5928: 	my $metastring;
1.768     albertel 5929: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5930: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5931: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5932: 	    $metastring=&getfile($file);
1.489     albertel 5933: 	}
1.208     albertel 5934:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5935:         my $token;
1.140     www      5936:         undef %metathesekeys;
1.71      www      5937:         while ($token=$parser->get_token) {
1.339     albertel 5938: 	    if ($token->[0] eq 'S') {
                   5939: 		if (defined($token->[2]->{'package'})) {
1.172     www      5940: #
                   5941: # This is a package - get package info
                   5942: #
1.339     albertel 5943: 		    my $package=$token->[2]->{'package'};
                   5944: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5945: 		    if (defined($token->[2]->{'id'})) { 
                   5946: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5947: 		    }
1.599     albertel 5948: 		    if ($metaentry{':packages'}) {
                   5949: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5950: 		    } else {
1.599     albertel 5951: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5952: 		    }
1.736     albertel 5953: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5954: 			my $part=$keyroot;
                   5955: 			$part=~s/^\_//;
1.736     albertel 5956: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5957: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5958: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5959: 			    # ignore package.tab specified default values
                   5960:                             # here &package_tab_default() will fetch those
                   5961: 			    if ($subp eq 'default') { next; }
1.736     albertel 5962: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5963: 			    my $unikey;
                   5964: 			    if ($pack =~ /_0$/) {
                   5965: 				$unikey='parameter_0_'.$name;
                   5966: 				$part=0;
                   5967: 			    } else {
                   5968: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5969: 			    }
1.339     albertel 5970: 			    if ($subp eq 'display') {
                   5971: 				$value.=' [Part: '.$part.']';
                   5972: 			    }
1.599     albertel 5973: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5974: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5975: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5976: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5977: 			    }
1.599     albertel 5978: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5979: 				$metaentry{':'.$unikey}=
                   5980: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5981: 			    }
1.339     albertel 5982: 			}
                   5983: 		    }
                   5984: 		} else {
1.172     www      5985: #
                   5986: # This is not a package - some other kind of start tag
1.339     albertel 5987: #
                   5988: 		    my $entry=$token->[1];
                   5989: 		    my $unikey;
                   5990: 		    if ($entry eq 'import') {
                   5991: 			$unikey='';
                   5992: 		    } else {
                   5993: 			$unikey=$entry;
                   5994: 		    }
                   5995: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5996: 
                   5997: 		    if (defined($token->[2]->{'id'})) { 
                   5998: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5999: 		    }
1.175     www      6000: 
1.339     albertel 6001: 		    if ($entry eq 'import') {
1.175     www      6002: #
                   6003: # Importing a library here
1.339     albertel 6004: #
                   6005: 			if ($depthcount<20) {
                   6006: 			    my $location=$parser->get_text('/import');
                   6007: 			    my $dir=$filename;
                   6008: 			    $dir=~s|[^/]*$||;
                   6009: 			    $location=&filelocation($dir,$location);
1.736     albertel 6010: 			    my $metadata = 
                   6011: 				&metadata($uri,'keys', $location,$unikey,
                   6012: 					  $depthcount+1);
                   6013: 			    foreach my $meta (split(',',$metadata)) {
                   6014: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6015: 				$metathesekeys{$meta}=1;
1.339     albertel 6016: 			    }
                   6017: 			}
                   6018: 		    } else { 
                   6019: 			
                   6020: 			if (defined($token->[2]->{'name'})) { 
                   6021: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6022: 			}
                   6023: 			$metathesekeys{$unikey}=1;
1.736     albertel 6024: 			foreach my $param (@{$token->[3]}) {
                   6025: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6026: 				$token->[2]->{$param};
1.339     albertel 6027: 			}
                   6028: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6029: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6030: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6031: 		 # only ws inside the tag, and not in default, so use default
                   6032: 		 # as value
1.599     albertel 6033: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6034: 			} else {
1.321     albertel 6035: 		  # either something interesting inside the tag or default
                   6036:                   # uninteresting
1.599     albertel 6037: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6038: 			}
1.172     www      6039: # end of not-a-package not-a-library import
1.339     albertel 6040: 		    }
1.172     www      6041: # end of not-a-package start tag
1.339     albertel 6042: 		}
1.172     www      6043: # the next is the end of "start tag"
1.339     albertel 6044: 	    }
                   6045: 	}
1.483     albertel 6046: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6047: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6048: 	    #no specific packages #how's our extension
                   6049: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6050: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6051: 					 \%metathesekeys);
                   6052: 	}
1.599     albertel 6053: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6054: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6055: 		#no specific packages well let's get default then
                   6056: 		if ($key!~/^default&/) { next; }
1.488     albertel 6057: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6058: 					     \%metathesekeys);
                   6059: 	    }
                   6060: 	}
1.338     www      6061: # are there custom rights to evaluate
1.599     albertel 6062: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6063: 
1.338     www      6064:     #
                   6065:     # Importing a rights file here
1.339     albertel 6066:     #
                   6067: 	    unless ($depthcount) {
1.599     albertel 6068: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6069: 		my $dir=$filename;
                   6070: 		$dir=~s|[^/]*$||;
                   6071: 		$location=&filelocation($dir,$location);
1.736     albertel 6072: 		my $rights_metadata =
                   6073: 		    &metadata($uri,'keys',$location,'_rights',
                   6074: 			      $depthcount+1);
                   6075: 		foreach my $rights (split(',',$rights_metadata)) {
                   6076: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6077: 		    $metathesekeys{$rights}=1;
1.339     albertel 6078: 		}
                   6079: 	    }
                   6080: 	}
1.737     albertel 6081: 	# uniqifiy package listing
                   6082: 	my %seen;
                   6083: 	my @uniq_packages =
                   6084: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6085: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6086: 
                   6087: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6088: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6089: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6090: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6091: # this is the end of "was not already recently cached
1.71      www      6092:     }
1.599     albertel 6093:     return $metaentry{':'.$what};
1.261     albertel 6094: }
                   6095: 
1.488     albertel 6096: sub metadata_create_package_def {
1.483     albertel 6097:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6098:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6099:     if ($subp eq 'default') { next; }
                   6100:     
1.599     albertel 6101:     if (defined($metaentry{':packages'})) {
                   6102: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6103:     } else {
1.599     albertel 6104: 	$metaentry{':packages'}=$package;
1.483     albertel 6105:     }
                   6106:     my $value=$packagetab{$key};
                   6107:     my $unikey;
                   6108:     $unikey='parameter_0_'.$name;
1.599     albertel 6109:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6110:     $$metathesekeys{$unikey}=1;
1.599     albertel 6111:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6112: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6113:     }
1.599     albertel 6114:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6115: 	$metaentry{':'.$unikey}=
                   6116: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6117:     }
                   6118: }
                   6119: 
1.261     albertel 6120: sub metadata_generate_part0 {
                   6121:     my ($metadata,$metacache,$uri) = @_;
                   6122:     my %allnames;
1.737     albertel 6123:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6124: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6125: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6126: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6127: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6128: 	    $allnames{$name}=$part;
                   6129: 	  }
                   6130: 	}
                   6131:     }
                   6132:     foreach my $name (keys(%allnames)) {
                   6133:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6134:       my $key=":parameter_0_$name";
1.261     albertel 6135:       $$metacache{"$key.part"}='0';
                   6136:       $$metacache{"$key.name"}=$name;
1.428     albertel 6137:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6138: 					   $allnames{$name}.'_'.$name.
                   6139: 					   '.type'};
1.428     albertel 6140:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6141: 			     '.display'};
1.644     www      6142:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6143:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6144:       $$metacache{"$key.display"}=$olddis;
                   6145:     }
1.71      www      6146: }
                   6147: 
1.764     albertel 6148: # ------------------------------------------------------ Devalidate title cache
                   6149: 
                   6150: sub devalidate_title_cache {
                   6151:     my ($url)=@_;
                   6152:     if (!$env{'request.course.id'}) { return; }
                   6153:     my $symb=&symbread($url);
                   6154:     if (!$symb) { return; }
                   6155:     my $key=$env{'request.course.id'}."\0".$symb;
                   6156:     &devalidate_cache_new('title',$key);
                   6157: }
                   6158: 
1.301     www      6159: # ------------------------------------------------- Get the title of a resource
                   6160: 
                   6161: sub gettitle {
                   6162:     my $urlsymb=shift;
                   6163:     my $symb=&symbread($urlsymb);
1.534     albertel 6164:     if ($symb) {
1.620     albertel 6165: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6166: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6167: 	if (defined($cached)) { 
                   6168: 	    return $result;
                   6169: 	}
1.534     albertel 6170: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6171: 	my $title='';
                   6172: 	my %bighash;
1.620     albertel 6173: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6174: 		&GDBM_READER(),0640)) {
                   6175: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6176: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6177: 	    untie %bighash;
                   6178: 	}
                   6179: 	$title=~s/\&colon\;/\:/gs;
                   6180: 	if ($title) {
1.599     albertel 6181: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6182: 	}
                   6183: 	$urlsymb=$url;
                   6184:     }
                   6185:     my $title=&metadata($urlsymb,'title');
                   6186:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6187:     return $title;
1.301     www      6188: }
1.613     albertel 6189: 
1.614     albertel 6190: sub get_slot {
                   6191:     my ($which,$cnum,$cdom)=@_;
                   6192:     if (!$cnum || !$cdom) {
1.790   ! albertel 6193: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6194: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6195: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6196:     }
1.703     albertel 6197:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6198:     my %slotinfo;
                   6199:     if (exists($remembered{$key})) {
                   6200: 	$slotinfo{$which} = $remembered{$key};
                   6201:     } else {
                   6202: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6203: 	&Apache::lonhomework::showhash(%slotinfo);
                   6204: 	my ($tmp)=keys(%slotinfo);
                   6205: 	if ($tmp=~/^error:/) { return (); }
                   6206: 	$remembered{$key} = $slotinfo{$which};
                   6207:     }
1.616     albertel 6208:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6209: 	return %{$slotinfo{$which}};
                   6210:     }
                   6211:     return $slotinfo{$which};
1.614     albertel 6212: }
1.31      www      6213: # ------------------------------------------------- Update symbolic store links
                   6214: 
                   6215: sub symblist {
                   6216:     my ($mapname,%newhash)=@_;
1.438     www      6217:     $mapname=&deversion(&declutter($mapname));
1.31      www      6218:     my %hash;
1.620     albertel 6219:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6220:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6221:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6222: 	    foreach my $url (keys %newhash) {
                   6223: 		next if ($url eq 'last_known'
                   6224: 			 && $env{'form.no_update_last_known'});
                   6225: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6226: 						    $newhash{$url}->[1],
                   6227: 						    $newhash{$url}->[0]);
1.191     harris41 6228:             }
1.31      www      6229:             if (untie(%hash)) {
                   6230: 		return 'ok';
                   6231:             }
                   6232:         }
                   6233:     }
                   6234:     return 'error';
1.212     www      6235: }
                   6236: 
                   6237: # --------------------------------------------------------------- Verify a symb
                   6238: 
                   6239: sub symbverify {
1.510     www      6240:     my ($symb,$thisurl)=@_;
                   6241:     my $thisfn=$thisurl;
1.439     www      6242:     $thisfn=&declutter($thisfn);
1.215     www      6243: # direct jump to resource in page or to a sequence - will construct own symbs
                   6244:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6245: # check URL part
1.409     www      6246:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6247: 
1.431     www      6248:     unless ($url eq $thisfn) { return 0; }
1.213     www      6249: 
1.216     www      6250:     $symb=&symbclean($symb);
1.510     www      6251:     $thisurl=&deversion($thisurl);
1.439     www      6252:     $thisfn=&deversion($thisfn);
1.213     www      6253: 
                   6254:     my %bighash;
                   6255:     my $okay=0;
1.431     www      6256: 
1.620     albertel 6257:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6258:                             &GDBM_READER(),0640)) {
1.510     www      6259:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6260:         unless ($ids) { 
1.510     www      6261:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6262:         }
                   6263:         if ($ids) {
                   6264: # ------------------------------------------------------------------- Has ID(s)
                   6265: 	    foreach (split(/\,/,$ids)) {
1.644     www      6266: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6267:                if (
                   6268:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6269:    eq $symb) { 
1.620     albertel 6270: 		   if (($env{'request.role.adv'}) ||
                   6271: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6272: 		       $okay=1; 
                   6273: 		   }
                   6274: 	       }
1.216     www      6275: 	   }
                   6276:         }
1.213     www      6277: 	untie(%bighash);
                   6278:     }
                   6279:     return $okay;
1.31      www      6280: }
                   6281: 
1.210     www      6282: # --------------------------------------------------------------- Clean-up symb
                   6283: 
                   6284: sub symbclean {
                   6285:     my $symb=shift;
1.568     albertel 6286:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6287: # remove version from map
                   6288:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6289: 
1.210     www      6290: # remove version from URL
                   6291:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6292: 
1.507     www      6293: # remove wrapper
                   6294: 
1.510     www      6295:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6296:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6297:     return $symb;
1.409     www      6298: }
                   6299: 
                   6300: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6301: 
                   6302: sub encode_symb {
                   6303:     my ($map,$resid,$url)=@_;
                   6304:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6305: }
1.409     www      6306: 
                   6307: sub decode_symb {
1.568     albertel 6308:     my $symb=shift;
                   6309:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6310:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6311:     return (&fixversion($map),$resid,&fixversion($url));
                   6312: }
                   6313: 
                   6314: sub fixversion {
                   6315:     my $fn=shift;
1.609     banghart 6316:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6317:     my %bighash;
                   6318:     my $uri=&clutter($fn);
1.620     albertel 6319:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6320: # is this cached?
1.599     albertel 6321:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6322:     if (defined($cached)) { return $result; }
                   6323: # unfortunately not cached, or expired
1.620     albertel 6324:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6325: 	    &GDBM_READER(),0640)) {
                   6326:  	if ($bighash{'version_'.$uri}) {
                   6327:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6328:  	    unless (($version eq 'mostrecent') || 
                   6329: 		    ($version==&getversion($uri))) {
1.440     www      6330:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6331:  	    }
                   6332:  	}
                   6333:  	untie %bighash;
1.413     www      6334:     }
1.599     albertel 6335:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6336: }
                   6337: 
                   6338: sub deversion {
                   6339:     my $url=shift;
                   6340:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6341:     return $url;
1.210     www      6342: }
                   6343: 
1.31      www      6344: # ------------------------------------------------------ Return symb list entry
                   6345: 
                   6346: sub symbread {
1.249     www      6347:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6348:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6349:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6350: # no filename provided? try from environment
1.44      www      6351:     unless ($thisfn) {
1.620     albertel 6352:         if ($env{'request.symb'}) {
                   6353: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6354: 	}
1.620     albertel 6355: 	$thisfn=$env{'request.filename'};
1.44      www      6356:     }
1.569     albertel 6357:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6358: # is that filename actually a symb? Verify, clean, and return
                   6359:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6360: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6361: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6362: 	}
1.242     www      6363:     }
1.44      www      6364:     $thisfn=declutter($thisfn);
1.31      www      6365:     my %hash;
1.37      www      6366:     my %bighash;
                   6367:     my $syval='';
1.620     albertel 6368:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6369:         my $targetfn = $thisfn;
1.609     banghart 6370:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6371:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6372:         }
1.687     albertel 6373: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6374: 	    $targetfn=$1;
                   6375: 	}
1.620     albertel 6376:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6377:                       &GDBM_READER(),0640)) {
1.481     raeburn  6378: 	    $syval=$hash{$targetfn};
1.37      www      6379:             untie(%hash);
                   6380:         }
                   6381: # ---------------------------------------------------------- There was an entry
                   6382:         if ($syval) {
1.601     albertel 6383: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6384: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6385: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6386: 		    #return $env{$cache_str}='';
1.601     albertel 6387: 		#}    
                   6388: 		#$syval.=$1;
                   6389: 	    #}
1.37      www      6390:         } else {
                   6391: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6392:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6393:                             &GDBM_READER(),0640)) {
1.37      www      6394: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6395:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6396:               unless ($ids) { 
                   6397:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6398:               }
                   6399:               unless ($ids) {
                   6400: # alias?
                   6401: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6402:               }
1.37      www      6403:               if ($ids) {
                   6404: # ------------------------------------------------------------------- Has ID(s)
                   6405:                  my @possibilities=split(/\,/,$ids);
1.39      www      6406:                  if ($#possibilities==0) {
                   6407: # ----------------------------------------------- There is only one possibility
1.37      www      6408: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6409: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6410: 						    $resid,$thisfn);
1.249     www      6411:                  } elsif (!$donotrecurse) {
1.39      www      6412: # ------------------------------------------ There is more than one possibility
                   6413:                      my $realpossible=0;
1.191     harris41 6414:                      foreach (@possibilities) {
1.39      www      6415: 			 my $file=$bighash{'src_'.$_};
                   6416:                          if (&allowed('bre',$file)) {
                   6417:          		    my ($mapid,$resid)=split(/\./,$_);
                   6418:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6419: 				$realpossible++;
1.626     albertel 6420:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6421: 						    $resid,$thisfn);
1.39      www      6422:                             }
                   6423: 			 }
1.191     harris41 6424:                      }
1.39      www      6425: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6426:                  } else {
                   6427:                      $syval='';
1.37      www      6428:                  }
                   6429: 	      }
                   6430:               untie(%bighash)
1.481     raeburn  6431:            }
1.31      www      6432:         }
1.62      www      6433:         if ($syval) {
1.620     albertel 6434: 	    return $env{$cache_str}=$syval;
1.62      www      6435:         }
1.31      www      6436:     }
1.44      www      6437:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6438:     return $env{$cache_str}='';
1.31      www      6439: }
                   6440: 
                   6441: # ---------------------------------------------------------- Return random seed
                   6442: 
1.32      www      6443: sub numval {
                   6444:     my $txt=shift;
                   6445:     $txt=~tr/A-J/0-9/;
                   6446:     $txt=~tr/a-j/0-9/;
                   6447:     $txt=~tr/K-T/0-9/;
                   6448:     $txt=~tr/k-t/0-9/;
                   6449:     $txt=~tr/U-Z/0-5/;
                   6450:     $txt=~tr/u-z/0-5/;
                   6451:     $txt=~s/\D//g;
1.564     albertel 6452:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6453:     return int($txt);
1.368     albertel 6454: }
                   6455: 
1.484     albertel 6456: sub numval2 {
                   6457:     my $txt=shift;
                   6458:     $txt=~tr/A-J/0-9/;
                   6459:     $txt=~tr/a-j/0-9/;
                   6460:     $txt=~tr/K-T/0-9/;
                   6461:     $txt=~tr/k-t/0-9/;
                   6462:     $txt=~tr/U-Z/0-5/;
                   6463:     $txt=~tr/u-z/0-5/;
                   6464:     $txt=~s/\D//g;
                   6465:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6466:     my $total;
                   6467:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6468:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6469:     return int($total);
                   6470: }
                   6471: 
1.575     albertel 6472: sub numval3 {
                   6473:     use integer;
                   6474:     my $txt=shift;
                   6475:     $txt=~tr/A-J/0-9/;
                   6476:     $txt=~tr/a-j/0-9/;
                   6477:     $txt=~tr/K-T/0-9/;
                   6478:     $txt=~tr/k-t/0-9/;
                   6479:     $txt=~tr/U-Z/0-5/;
                   6480:     $txt=~tr/u-z/0-5/;
                   6481:     $txt=~s/\D//g;
                   6482:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6483:     my $total;
                   6484:     foreach my $val (@txts) { $total+=$val; }
                   6485:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6486:     return $total;
                   6487: }
                   6488: 
1.675     albertel 6489: sub digest {
                   6490:     my ($data)=@_;
                   6491:     my $digest=&Digest::MD5::md5($data);
                   6492:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6493:     my ($e,$f);
                   6494:     {
                   6495:         use integer;
                   6496:         $e=($a+$b);
                   6497:         $f=($c+$d);
                   6498:         if ($_64bit) {
                   6499:             $e=(($e<<32)>>32);
                   6500:             $f=(($f<<32)>>32);
                   6501:         }
                   6502:     }
                   6503:     if (wantarray) {
                   6504: 	return ($e,$f);
                   6505:     } else {
                   6506: 	my $g;
                   6507: 	{
                   6508: 	    use integer;
                   6509: 	    $g=($e+$f);
                   6510: 	    if ($_64bit) {
                   6511: 		$g=(($g<<32)>>32);
                   6512: 	    }
                   6513: 	}
                   6514: 	return $g;
                   6515:     }
                   6516: }
                   6517: 
1.368     albertel 6518: sub latest_rnd_algorithm_id {
1.675     albertel 6519:     return '64bit5';
1.366     albertel 6520: }
1.32      www      6521: 
1.503     albertel 6522: sub get_rand_alg {
                   6523:     my ($courseid)=@_;
1.790   ! albertel 6524:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6525:     if ($courseid) {
1.620     albertel 6526: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6527:     }
                   6528:     return &latest_rnd_algorithm_id();
                   6529: }
                   6530: 
1.562     albertel 6531: sub validCODE {
                   6532:     my ($CODE)=@_;
                   6533:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6534:     return 0;
                   6535: }
                   6536: 
1.491     albertel 6537: sub getCODE {
1.620     albertel 6538:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6539:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6540: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6541: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6542: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6543:     }
                   6544:     return undef;
                   6545: }
                   6546: 
1.31      www      6547: sub rndseed {
1.155     albertel 6548:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6549: 
1.790   ! albertel 6550:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6551:     if (!$symb) {
1.366     albertel 6552: 	unless ($symb=$wsymb) { return time; }
                   6553:     }
                   6554:     if (!$courseid) { $courseid=$wcourseid; }
                   6555:     if (!$domain) { $domain=$wdomain; }
                   6556:     if (!$username) { $username=$wusername }
1.503     albertel 6557:     my $which=&get_rand_alg();
1.491     albertel 6558:     if (defined(&getCODE())) {
1.675     albertel 6559: 	if ($which eq '64bit5') {
                   6560: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6561: 	} elsif ($which eq '64bit4') {
1.575     albertel 6562: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6563: 	} else {
                   6564: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6565: 	}
1.675     albertel 6566:     } elsif ($which eq '64bit5') {
                   6567: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6568:     } elsif ($which eq '64bit4') {
                   6569: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6570:     } elsif ($which eq '64bit3') {
                   6571: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6572:     } elsif ($which eq '64bit2') {
                   6573: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6574:     } elsif ($which eq '64bit') {
                   6575: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6576:     }
                   6577:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6578: }
                   6579: 
                   6580: sub rndseed_32bit {
                   6581:     my ($symb,$courseid,$domain,$username)=@_;
                   6582:     {
                   6583: 	use integer;
                   6584: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6585: 	my $symbseed=numval($symb) << 22;
                   6586: 	my $namechck=unpack("%32C*",$username) << 17;
                   6587: 	my $nameseed=numval($username) << 12;
                   6588: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6589: 	my $courseseed=unpack("%32C*",$courseid);
                   6590: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790   ! albertel 6591: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
        !          6592: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6593: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6594: 	return $num;
                   6595:     }
                   6596: }
                   6597: 
                   6598: sub rndseed_64bit {
                   6599:     my ($symb,$courseid,$domain,$username)=@_;
                   6600:     {
                   6601: 	use integer;
                   6602: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6603: 	my $symbseed=numval($symb) << 10;
                   6604: 	my $namechck=unpack("%32S*",$username);
                   6605: 	
                   6606: 	my $nameseed=numval($username) << 21;
                   6607: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6608: 	my $courseseed=unpack("%32S*",$courseid);
                   6609: 	
                   6610: 	my $num1=$symbchck+$symbseed+$namechck;
                   6611: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790   ! albertel 6612: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
        !          6613: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6614: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6615: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6616: 	return "$num1,$num2";
1.155     albertel 6617:     }
1.366     albertel 6618: }
                   6619: 
1.443     albertel 6620: sub rndseed_64bit2 {
                   6621:     my ($symb,$courseid,$domain,$username)=@_;
                   6622:     {
                   6623: 	use integer;
                   6624: 	# strings need to be an even # of cahracters long, it it is odd the
                   6625:         # last characters gets thrown away
                   6626: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6627: 	my $symbseed=numval($symb) << 10;
                   6628: 	my $namechck=unpack("%32S*",$username.' ');
                   6629: 	
                   6630: 	my $nameseed=numval($username) << 21;
1.501     albertel 6631: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6632: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6633: 	
                   6634: 	my $num1=$symbchck+$symbseed+$namechck;
                   6635: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790   ! albertel 6636: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
        !          6637: 	#&logthis("rndseed :$num:$symb");
1.501     albertel 6638: 	return "$num1,$num2";
                   6639:     }
                   6640: }
                   6641: 
                   6642: sub rndseed_64bit3 {
                   6643:     my ($symb,$courseid,$domain,$username)=@_;
                   6644:     {
                   6645: 	use integer;
                   6646: 	# strings need to be an even # of cahracters long, it it is odd the
                   6647:         # last characters gets thrown away
                   6648: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6649: 	my $symbseed=numval2($symb) << 10;
                   6650: 	my $namechck=unpack("%32S*",$username.' ');
                   6651: 	
                   6652: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6653: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6654: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6655: 	
                   6656: 	my $num1=$symbchck+$symbseed+$namechck;
                   6657: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790   ! albertel 6658: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
        !          6659: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6660: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6661: 	
1.503     albertel 6662: 	return "$num1:$num2";
1.443     albertel 6663:     }
                   6664: }
                   6665: 
1.575     albertel 6666: sub rndseed_64bit4 {
                   6667:     my ($symb,$courseid,$domain,$username)=@_;
                   6668:     {
                   6669: 	use integer;
                   6670: 	# strings need to be an even # of cahracters long, it it is odd the
                   6671:         # last characters gets thrown away
                   6672: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6673: 	my $symbseed=numval3($symb) << 10;
                   6674: 	my $namechck=unpack("%32S*",$username.' ');
                   6675: 	
                   6676: 	my $nameseed=numval3($username) << 21;
                   6677: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6678: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6679: 	
                   6680: 	my $num1=$symbchck+$symbseed+$namechck;
                   6681: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790   ! albertel 6682: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
        !          6683: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6684: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6685: 	
                   6686: 	return "$num1:$num2";
                   6687:     }
                   6688: }
                   6689: 
1.675     albertel 6690: sub rndseed_64bit5 {
                   6691:     my ($symb,$courseid,$domain,$username)=@_;
                   6692:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6693:     return "$num1:$num2";
                   6694: }
                   6695: 
1.366     albertel 6696: sub rndseed_CODE_64bit {
                   6697:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6698:     {
1.366     albertel 6699: 	use integer;
1.443     albertel 6700: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6701: 	my $symbseed=numval2($symb);
1.491     albertel 6702: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6703: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6704: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6705: 	my $num1=$symbseed+$CODEchck;
                   6706: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790   ! albertel 6707: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
        !          6708: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6709: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6710: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6711: 	return "$num1:$num2";
1.366     albertel 6712:     }
                   6713: }
                   6714: 
1.575     albertel 6715: sub rndseed_CODE_64bit4 {
                   6716:     my ($symb,$courseid,$domain,$username)=@_;
                   6717:     {
                   6718: 	use integer;
                   6719: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6720: 	my $symbseed=numval3($symb);
                   6721: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6722: 	my $CODEseed=numval3(&getCODE());
                   6723: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6724: 	my $num1=$symbseed+$CODEchck;
                   6725: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790   ! albertel 6726: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
        !          6727: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6728: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6729: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6730: 	return "$num1:$num2";
                   6731:     }
                   6732: }
                   6733: 
1.675     albertel 6734: sub rndseed_CODE_64bit5 {
                   6735:     my ($symb,$courseid,$domain,$username)=@_;
                   6736:     my $code = &getCODE();
                   6737:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6738:     return "$num1:$num2";
                   6739: }
                   6740: 
1.366     albertel 6741: sub setup_random_from_rndseed {
                   6742:     my ($rndseed)=@_;
1.503     albertel 6743:     if ($rndseed =~/([,:])/) {
                   6744: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6745: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6746:     } else {
                   6747: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6748:     }
1.36      albertel 6749: }
                   6750: 
1.474     albertel 6751: sub latest_receipt_algorithm_id {
                   6752:     return 'receipt2';
                   6753: }
                   6754: 
1.480     www      6755: sub recunique {
                   6756:     my $fucourseid=shift;
                   6757:     my $unique;
1.620     albertel 6758:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6759: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6760:     } else {
                   6761: 	$unique=$perlvar{'lonReceipt'};
                   6762:     }
                   6763:     return unpack("%32C*",$unique);
                   6764: }
                   6765: 
                   6766: sub recprefix {
                   6767:     my $fucourseid=shift;
                   6768:     my $prefix;
1.620     albertel 6769:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6770: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6771:     } else {
                   6772: 	$prefix=$perlvar{'lonHostID'};
                   6773:     }
                   6774:     return unpack("%32C*",$prefix);
                   6775: }
                   6776: 
1.76      www      6777: sub ireceipt {
1.474     albertel 6778:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6779:     my $cuname=unpack("%32C*",$funame);
                   6780:     my $cudom=unpack("%32C*",$fudom);
                   6781:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6782:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6783:     my $cunique=&recunique($fucourseid);
1.474     albertel 6784:     my $cpart=unpack("%32S*",$part);
1.480     www      6785:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6786:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6787: 	$env{'request.state'} eq 'construct') {
1.790   ! albertel 6788: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6789: 			       
                   6790: 	$return.= ($cunique%$cuname+
                   6791: 		   $cunique%$cudom+
                   6792: 		   $cusymb%$cuname+
                   6793: 		   $cusymb%$cudom+
                   6794: 		   $cucourseid%$cuname+
                   6795: 		   $cucourseid%$cudom+
                   6796: 		   $cpart%$cuname+
                   6797: 		   $cpart%$cudom);
                   6798:     } else {
                   6799: 	$return.= ($cunique%$cuname+
                   6800: 		   $cunique%$cudom+
                   6801: 		   $cusymb%$cuname+
                   6802: 		   $cusymb%$cudom+
                   6803: 		   $cucourseid%$cuname+
                   6804: 		   $cucourseid%$cudom);
                   6805:     }
                   6806:     return $return;
1.76      www      6807: }
                   6808: 
                   6809: sub receipt {
1.474     albertel 6810:     my ($part)=@_;
1.790   ! albertel 6811:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6812:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6813: }
1.260     ng       6814: 
1.790   ! albertel 6815: sub whichuser {
        !          6816:     my ($passedsymb)=@_;
        !          6817:     my ($symb,$courseid,$domain,$name,$publicuser);
        !          6818:     if (defined($env{'form.grade_symb'})) {
        !          6819: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
        !          6820: 	my $allowed=&allowed('vgr',$tmp_courseid);
        !          6821: 	if (!$allowed &&
        !          6822: 	    exists($env{'request.course.sec'}) &&
        !          6823: 	    $env{'request.course.sec'} !~ /^\s*$/) {
        !          6824: 	    $allowed=&allowed('vgr',$tmp_courseid.
        !          6825: 			      '/'.$env{'request.course.sec'});
        !          6826: 	}
        !          6827: 	if ($allowed) {
        !          6828: 	    ($symb)=&get_env_multiple('form.grade_symb');
        !          6829: 	    $courseid=$tmp_courseid;
        !          6830: 	    ($domain)=&get_env_multiple('form.grade_domain');
        !          6831: 	    ($name)=&get_env_multiple('form.grade_username');
        !          6832: 	    return ($symb,$courseid,$domain,$name,$publicuser);
        !          6833: 	}
        !          6834:     }
        !          6835:     if (!$passedsymb) {
        !          6836: 	$symb=&symbread();
        !          6837:     } else {
        !          6838: 	$symb=$passedsymb;
        !          6839:     }
        !          6840:     $courseid=$env{'request.course.id'};
        !          6841:     $domain=$env{'user.domain'};
        !          6842:     $name=$env{'user.name'};
        !          6843:     if ($name eq 'public' && $domain eq 'public') {
        !          6844: 	if (!defined($env{'form.username'})) {
        !          6845: 	    $env{'form.username'}.=time.rand(10000000);
        !          6846: 	}
        !          6847: 	$name.=$env{'form.username'};
        !          6848:     }
        !          6849:     return ($symb,$courseid,$domain,$name,$publicuser);
        !          6850: 
        !          6851: }
        !          6852: 
1.36      albertel 6853: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6854: # returns either the contents of the file or 
                   6855: # -1 if the file doesn't exist
1.481     raeburn  6856: #
                   6857: # if the target is a file that was uploaded via DOCS, 
                   6858: # a check will be made to see if a current copy exists on the local server,
                   6859: # if it does this will be served, otherwise a copy will be retrieved from
                   6860: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6861: # the local server.   
1.472     albertel 6862: 
1.36      albertel 6863: sub getfile {
1.538     albertel 6864:     my ($file) = @_;
1.609     banghart 6865:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6866:     &repcopy($file);
                   6867:     return &readfile($file);
                   6868: }
                   6869: 
                   6870: sub repcopy_userfile {
                   6871:     my ($file)=@_;
1.609     banghart 6872:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6873:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6874:     my ($cdom,$cnum,$filename) = 
                   6875: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6876:     my ($info,$rtncode);
                   6877:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6878:     if (-e "$file") {
                   6879: 	my @fileinfo = stat($file);
                   6880: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6881: 	if ($lwpresp ne 'ok') {
                   6882: 	    if ($rtncode eq '404') {
1.538     albertel 6883: 		unlink($file);
1.482     albertel 6884: 	    }
1.517     albertel 6885: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6886: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6887: 	    #my $response=$ua->request($request);
                   6888: 	    #if ($response->is_success()) {
                   6889: 	#	return $response->content;
                   6890: 	#    } else {
                   6891: 	#	return -1;
                   6892: 	#    }
1.482     albertel 6893: 	    return -1;
                   6894: 	}
                   6895: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6896: 	    return 'ok';
1.482     albertel 6897: 	}
                   6898: 	$info = '';
1.538     albertel 6899: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6900: 	if ($lwpresp ne 'ok') {
                   6901: 	    return -1;
                   6902: 	}
                   6903:     } else {
1.538     albertel 6904: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6905: 	if ($lwpresp ne 'ok') {
1.517     albertel 6906: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6907: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6908: 	    my $response=$ua->request($request);
                   6909: 	    if ($response->is_success()) {
1.538     albertel 6910: 		$info=$response->content;
1.517     albertel 6911: 	    } else {
                   6912: 		return -1;
                   6913: 	    }
1.482     albertel 6914: 	}
                   6915: 	my @parts = ($cdom,$cnum); 
                   6916: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6917: 	    push @parts, split(/\//,$1);
1.518     albertel 6918: 	}
1.538     albertel 6919: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6920: 	foreach my $part (@parts) {
                   6921: 	    $path .= '/'.$part;
                   6922: 	    if (!-e $path) {
                   6923: 		mkdir($path,0770);
                   6924: 	    }
                   6925: 	}
                   6926:     }
1.538     albertel 6927:     open(FILE,">$file");
1.482     albertel 6928:     print FILE $info;
                   6929:     close(FILE);
1.607     raeburn  6930:     return 'ok';
1.481     raeburn  6931: }
                   6932: 
1.517     albertel 6933: sub tokenwrapper {
                   6934:     my $uri=shift;
1.552     albertel 6935:     $uri=~s|^http\://([^/]+)||;
                   6936:     $uri=~s|^/||;
1.620     albertel 6937:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6938:     my $token=$1;
1.552     albertel 6939:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6940:     if ($udom && $uname && $file) {
                   6941: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6942:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6943:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6944:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6945:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6946:     } else {
                   6947:         return '/adm/notfound.html';
                   6948:     }
                   6949: }
                   6950: 
1.481     raeburn  6951: sub getuploaded {
                   6952:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6953:     $uri=~s/^\///;
                   6954:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6955:     my $ua=new LWP::UserAgent;
                   6956:     my $request=new HTTP::Request($reqtype,$uri);
                   6957:     my $response=$ua->request($request);
                   6958:     $$rtncode = $response->code;
1.482     albertel 6959:     if (! $response->is_success()) {
                   6960: 	return 'failed';
                   6961:     }      
                   6962:     if ($reqtype eq 'HEAD') {
1.486     www      6963: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6964:     } elsif ($reqtype eq 'GET') {
                   6965: 	$$info = $response->content;
1.472     albertel 6966:     }
1.482     albertel 6967:     return 'ok';
1.36      albertel 6968: }
                   6969: 
1.481     raeburn  6970: sub readfile {
                   6971:     my $file = shift;
                   6972:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6973:     my $fh;
                   6974:     open($fh,"<$file");
                   6975:     my $a='';
                   6976:     while (<$fh>) { $a .=$_; }
                   6977:     return $a;
                   6978: }
                   6979: 
1.36      albertel 6980: sub filelocation {
1.590     banghart 6981:     my ($dir,$file) = @_;
                   6982:     my $location;
                   6983:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6984: 
                   6985:     if ($file =~ m-^/adm/-) {
                   6986: 	$file=~s-^/adm/wrapper/-/-;
                   6987: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6988:     }
1.590     banghart 6989:     if ($file=~m:^/~:) { # is a contruction space reference
                   6990:         $location = $file;
                   6991:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6992:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6993: 	# is a correct contruction space reference
                   6994:         $location = $file;
1.609     banghart 6995:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6996:         my ($udom,$uname,$filename)=
1.609     banghart 6997:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6998:         my $home=&homeserver($uname,$udom);
                   6999:         my $is_me=0;
                   7000:         my @ids=&current_machine_ids();
                   7001:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7002:         if ($is_me) {
1.740     www      7003:   	    $location=&propath($udom,$uname).
1.590     banghart 7004:   	      '/userfiles/'.$filename;
                   7005:         } else {
                   7006:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7007:   	      $udom.'/'.$uname.'/'.$filename;
                   7008:         }
                   7009:     } else {
                   7010:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7011:         $file=~s:^/res/:/:;
                   7012:         if ( !( $file =~ m:^/:) ) {
                   7013:             $location = $dir. '/'.$file;
                   7014:         } else {
                   7015:             $location = '/home/httpd/html/res'.$file;
                   7016:         }
1.59      albertel 7017:     }
1.590     banghart 7018:     $location=~s://+:/:g; # remove duplicate /
                   7019:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7020:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7021:     return $location;
1.46      www      7022: }
1.36      albertel 7023: 
1.46      www      7024: sub hreflocation {
                   7025:     my ($dir,$file)=@_;
1.460     albertel 7026:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7027: 	$file=filelocation($dir,$file);
1.700     albertel 7028:     } elsif ($file=~m-^/adm/-) {
                   7029: 	$file=~s-^/adm/wrapper/-/-;
                   7030: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7031:     }
                   7032:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7033: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   7034:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 7035: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 7036:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   7037: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7038: 	    -/uploaded/$1/$2/-x;
1.46      www      7039:     }
1.462     albertel 7040:     return $file;
1.465     albertel 7041: }
                   7042: 
                   7043: sub current_machine_domains {
                   7044:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7045:     my @domains;
                   7046:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7047: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7048: 	if ($hostname eq $name) {
                   7049: 	    push(@domains,$hostdom{$id});
                   7050: 	}
                   7051:     }
                   7052:     return @domains;
                   7053: }
                   7054: 
                   7055: sub current_machine_ids {
                   7056:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7057:     my @ids;
                   7058:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7059: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7060: 	if ($hostname eq $name) {
                   7061: 	    push(@ids,$id);
                   7062: 	}
                   7063:     }
                   7064:     return @ids;
1.31      www      7065: }
                   7066: 
                   7067: # ------------------------------------------------------------- Declutters URLs
                   7068: 
                   7069: sub declutter {
                   7070:     my $thisfn=shift;
1.569     albertel 7071:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7072:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7073:     $thisfn=~s/^\///;
1.697     albertel 7074:     $thisfn=~s|^adm/wrapper/||;
                   7075:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7076:     $thisfn=~s/^res\///;
1.235     www      7077:     $thisfn=~s/\?.+$//;
1.268     www      7078:     return $thisfn;
                   7079: }
                   7080: 
                   7081: # ------------------------------------------------------------- Clutter up URLs
                   7082: 
                   7083: sub clutter {
                   7084:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7085:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7086:        $thisfn='/res'.$thisfn; 
                   7087:     }
1.694     albertel 7088:     if ($thisfn !~m|/adm|) {
1.695     albertel 7089: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7090: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7091: 	} else {
                   7092: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7093: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7094: 	    if ($embstyle eq 'ssi'
                   7095: 		|| ($embstyle eq 'hdn')
                   7096: 		|| ($embstyle eq 'rat')
                   7097: 		|| ($embstyle eq 'prv')
                   7098: 		|| ($embstyle eq 'ign')) {
                   7099: 		#do nothing with these
                   7100: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7101: 		|| ($embstyle eq 'emb')
                   7102: 		|| ($embstyle eq 'wrp')) {
                   7103: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7104: 	    } elsif ($embstyle eq 'unk'
                   7105: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7106: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7107: 	    } else {
1.718     www      7108: #		&logthis("Got a blank emb style");
1.695     albertel 7109: 	    }
1.694     albertel 7110: 	}
                   7111:     }
1.31      www      7112:     return $thisfn;
1.12      www      7113: }
                   7114: 
1.787     albertel 7115: sub clutter_with_no_wrapper {
                   7116:     my $uri = &clutter(shift);
                   7117:     if ($uri =~ m-^/adm/-) {
                   7118: 	$uri =~ s-^/adm/wrapper/-/-;
                   7119: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7120:     }
                   7121:     return $uri;
                   7122: }
                   7123: 
1.557     albertel 7124: sub freeze_escape {
                   7125:     my ($value)=@_;
                   7126:     if (ref($value)) {
                   7127: 	$value=&nfreeze($value);
                   7128: 	return '__FROZEN__'.&escape($value);
                   7129:     }
                   7130:     return &escape($value);
                   7131: }
                   7132: 
1.11      www      7133: 
1.557     albertel 7134: sub thaw_unescape {
                   7135:     my ($value)=@_;
                   7136:     if ($value =~ /^__FROZEN__/) {
                   7137: 	substr($value,0,10,undef);
                   7138: 	$value=&unescape($value);
                   7139: 	return &thaw($value);
                   7140:     }
                   7141:     return &unescape($value);
                   7142: }
                   7143: 
1.436     albertel 7144: sub correct_line_ends {
                   7145:     my ($result)=@_;
                   7146:     $$result =~s/\r\n/\n/mg;
                   7147:     $$result =~s/\r/\n/mg;
1.415     albertel 7148: }
1.1       albertel 7149: # ================================================================ Main Program
                   7150: 
1.184     www      7151: sub goodbye {
1.204     albertel 7152:    &logthis("Starting Shut down");
1.443     albertel 7153: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7154:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7155: #converted
1.599     albertel 7156: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7157:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7158: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7159: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7160: #1.1 only
1.599     albertel 7161: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7162: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7163: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7164: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7165:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7166:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7167:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7168:    &flushcourselogs();
                   7169:    &logthis("Shutting down");
                   7170: }
                   7171: 
1.179     www      7172: BEGIN {
1.228     harris41 7173: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7174:     unless ($readit) {
1.217     harris41 7175: {
1.781     raeburn  7176:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7177:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7178: }
1.1       albertel 7179: 
1.327     albertel 7180: # ------------------------------------------------------------ Read domain file
                   7181: {
                   7182:     %domaindescription = ();
                   7183:     %domain_auth_def = ();
                   7184:     %domain_auth_arg_def = ();
1.448     albertel 7185:     my $fh;
                   7186:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7187:        while (<$fh>) {
1.390     matthew  7188:            next if (/^(\#|\s*$)/);
                   7189: #           next if /^\#/;
1.327     albertel 7190:            chomp;
1.403     www      7191:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7192: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7193: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7194:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7195: 	   $domaindescription{$domain}=$domain_description;
                   7196: 	   $domain_lang_def{$domain}=$def_lang;
                   7197: 	   $domain_city{$domain}=$city;
                   7198: 	   $domain_longi{$domain}=$longi;
                   7199: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7200:            $domain_primary{$domain}=$primary;
1.403     www      7201: 
1.448     albertel 7202:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7203: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7204: 	}
1.327     albertel 7205:     }
1.448     albertel 7206:     close ($fh);
1.327     albertel 7207: }
                   7208: 
                   7209: 
1.1       albertel 7210: # ------------------------------------------------------------- Read hosts file
                   7211: {
1.448     albertel 7212:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7213: 
                   7214:     while (my $configline=<$config>) {
1.303     matthew  7215:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7216:        chomp($configline);
1.595     albertel 7217:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7218:        $name=~s/\s//g;
1.595     albertel 7219:        if ($id && $domain && $role && $name) {
1.252     albertel 7220: 	 $hostname{$id}=$name;
                   7221: 	 $hostdom{$id}=$domain;
                   7222: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7223:        }
1.1       albertel 7224:     }
1.448     albertel 7225:     close($config);
1.619     albertel 7226:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7227:     #&get_iphost();
1.1       albertel 7228: }
                   7229: 
1.598     albertel 7230: sub get_iphost {
                   7231:     if (%iphost) { return %iphost; }
1.653     albertel 7232:     my %name_to_ip;
1.598     albertel 7233:     foreach my $id (keys(%hostname)) {
                   7234: 	my $name=$hostname{$id};
1.653     albertel 7235: 	my $ip;
                   7236: 	if (!exists($name_to_ip{$name})) {
                   7237: 	    $ip = gethostbyname($name);
                   7238: 	    if (!$ip || length($ip) ne 4) {
                   7239: 		&logthis("Skipping host $id name $name no IP found\n");
                   7240: 		next;
                   7241: 	    }
                   7242: 	    $ip=inet_ntoa($ip);
                   7243: 	    $name_to_ip{$name} = $ip;
                   7244: 	} else {
                   7245: 	    $ip = $name_to_ip{$name};
1.598     albertel 7246: 	}
                   7247: 	push(@{$iphost{$ip}},$id);
                   7248:     }
                   7249:     return %iphost;
                   7250: }
                   7251: 
1.1       albertel 7252: # ------------------------------------------------------ Read spare server file
                   7253: {
1.448     albertel 7254:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7255: 
                   7256:     while (my $configline=<$config>) {
                   7257:        chomp($configline);
1.284     matthew  7258:        if ($configline) {
1.784     albertel 7259: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7260: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7261: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7262:        }
                   7263:     }
1.448     albertel 7264:     close($config);
1.1       albertel 7265: }
1.11      www      7266: # ------------------------------------------------------------ Read permissions
                   7267: {
1.448     albertel 7268:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7269: 
                   7270:     while (my $configline=<$config>) {
1.448     albertel 7271: 	chomp($configline);
                   7272: 	if ($configline) {
                   7273: 	    my ($role,$perm)=split(/ /,$configline);
                   7274: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7275: 	}
1.11      www      7276:     }
1.448     albertel 7277:     close($config);
1.11      www      7278: }
                   7279: 
                   7280: # -------------------------------------------- Read plain texts for permissions
                   7281: {
1.448     albertel 7282:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7283: 
                   7284:     while (my $configline=<$config>) {
1.448     albertel 7285: 	chomp($configline);
                   7286: 	if ($configline) {
1.742     raeburn  7287: 	    my ($short,@plain)=split(/:/,$configline);
                   7288:             %{$prp{$short}} = ();
                   7289: 	    if (@plain > 0) {
                   7290:                 $prp{$short}{'std'} = $plain[0];
                   7291:                 for (my $i=1; $i<@plain; $i++) {
                   7292:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7293:                 }
                   7294:             }
1.448     albertel 7295: 	}
1.135     www      7296:     }
1.448     albertel 7297:     close($config);
1.135     www      7298: }
                   7299: 
                   7300: # ---------------------------------------------------------- Read package table
                   7301: {
1.448     albertel 7302:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7303: 
                   7304:     while (my $configline=<$config>) {
1.483     albertel 7305: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7306: 	chomp($configline);
                   7307: 	my ($short,$plain)=split(/:/,$configline);
                   7308: 	my ($pack,$name)=split(/\&/,$short);
                   7309: 	if ($plain ne '') {
                   7310: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7311: 	    $packagetab{$short}=$plain; 
                   7312: 	}
1.11      www      7313:     }
1.448     albertel 7314:     close($config);
1.329     matthew  7315: }
                   7316: 
                   7317: # ------------- set up temporary directory
                   7318: {
                   7319:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7320: 
1.11      www      7321: }
                   7322: 
1.599     albertel 7323: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7324: 
1.281     www      7325: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7326: $dumpcount=0;
1.22      www      7327: 
1.163     harris41 7328: &logtouch();
1.672     albertel 7329: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7330: $readit=1;
1.564     albertel 7331:     {
                   7332: 	use integer;
                   7333: 	my $test=(2**32)+1;
1.568     albertel 7334: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7335: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7336:     }
1.195     www      7337: }
1.1       albertel 7338: }
1.179     www      7339: 
1.1       albertel 7340: 1;
1.191     harris41 7341: __END__
                   7342: 
1.243     albertel 7343: =pod
                   7344: 
1.191     harris41 7345: =head1 NAME
                   7346: 
1.243     albertel 7347: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7348: 
                   7349: =head1 SYNOPSIS
                   7350: 
1.243     albertel 7351: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7352: 
                   7353:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7354: 
1.243     albertel 7355: Common parameters:
                   7356: 
                   7357: =over 4
                   7358: 
                   7359: =item *
                   7360: 
                   7361: $uname : an internal username (if $cname expecting a course Id specifically)
                   7362: 
                   7363: =item *
                   7364: 
                   7365: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7366: 
                   7367: =item *
                   7368: 
                   7369: $symb : a resource instance identifier
                   7370: 
                   7371: =item *
                   7372: 
                   7373: $namespace : the name of a .db file that contains the data needed or
                   7374: being set.
                   7375: 
                   7376: =back
                   7377: 
1.394     bowersj2 7378: =head1 OVERVIEW
1.191     harris41 7379: 
1.394     bowersj2 7380: lonnet provides subroutines which interact with the
                   7381: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7382: about classes, users, and resources.
1.243     albertel 7383: 
                   7384: For many of these objects you can also use this to store data about
                   7385: them or modify them in various ways.
1.191     harris41 7386: 
1.394     bowersj2 7387: =head2 Symbs
1.191     harris41 7388: 
1.394     bowersj2 7389: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7390: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7391: map, the resource number of the resource in the map, and the URL of
                   7392: the resource itself. The latter is somewhat redundant, but might help
                   7393: if maps change.
                   7394: 
                   7395: An example is
                   7396: 
                   7397:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7398: 
                   7399: The respective map entry is
                   7400: 
                   7401:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7402:   title="Problem 2">
                   7403:  </resource>
                   7404: 
                   7405: Symbs are used by the random number generator, as well as to store and
                   7406: restore data specific to a certain instance of for example a problem.
                   7407: 
                   7408: =head2 Storing And Retrieving Data
                   7409: 
                   7410: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7411: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7412: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7413: is is the non-critical message twin of cstore. These functions are for
                   7414: handlers to store a perl hash to a user's permanent data space in an
                   7415: easy manner, and to retrieve it again on another call. It is expected
                   7416: that a handler would use this once at the beginning to retrieve data,
                   7417: and then again once at the end to send only the new data back.
                   7418: 
                   7419: The data is stored in the user's data directory on the user's
                   7420: homeserver under the ID of the course.
                   7421: 
                   7422: The hash that is returned by restore will have all of the previous
                   7423: value for all of the elements of the hash.
                   7424: 
                   7425: Example:
                   7426: 
                   7427:  #creating a hash
                   7428:  my %hash;
                   7429:  $hash{'foo'}='bar';
                   7430: 
                   7431:  #storing it
                   7432:  &Apache::lonnet::cstore(\%hash);
                   7433: 
                   7434:  #changing a value
                   7435:  $hash{'foo'}='notbar';
                   7436: 
                   7437:  #adding a new value
                   7438:  $hash{'bar'}='foo';
                   7439:  &Apache::lonnet::cstore(\%hash);
                   7440: 
                   7441:  #retrieving the hash
                   7442:  my %history=&Apache::lonnet::restore();
                   7443: 
                   7444:  #print the hash
                   7445:  foreach my $key (sort(keys(%history))) {
                   7446:    print("\%history{$key} = $history{$key}");
                   7447:  }
                   7448: 
                   7449: Will print out:
1.191     harris41 7450: 
1.394     bowersj2 7451:  %history{1:foo} = bar
                   7452:  %history{1:keys} = foo:timestamp
                   7453:  %history{1:timestamp} = 990455579
                   7454:  %history{2:bar} = foo
                   7455:  %history{2:foo} = notbar
                   7456:  %history{2:keys} = foo:bar:timestamp
                   7457:  %history{2:timestamp} = 990455580
                   7458:  %history{bar} = foo
                   7459:  %history{foo} = notbar
                   7460:  %history{timestamp} = 990455580
                   7461:  %history{version} = 2
                   7462: 
                   7463: Note that the special hash entries C<keys>, C<version> and
                   7464: C<timestamp> were added to the hash. C<version> will be equal to the
                   7465: total number of versions of the data that have been stored. The
                   7466: C<timestamp> attribute will be the UNIX time the hash was
                   7467: stored. C<keys> is available in every historical section to list which
                   7468: keys were added or changed at a specific historical revision of a
                   7469: hash.
                   7470: 
                   7471: B<Warning>: do not store the hash that restore returns directly. This
                   7472: will cause a mess since it will restore the historical keys as if the
                   7473: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7474: 
1.394     bowersj2 7475: Calling convention:
1.191     harris41 7476: 
1.394     bowersj2 7477:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7478:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7479: 
1.394     bowersj2 7480: For more detailed information, see lonnet specific documentation.
1.191     harris41 7481: 
1.394     bowersj2 7482: =head1 RETURN MESSAGES
1.191     harris41 7483: 
1.394     bowersj2 7484: =over 4
1.191     harris41 7485: 
1.394     bowersj2 7486: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7487: 
1.394     bowersj2 7488: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7489: when the connection is brought back up
1.191     harris41 7490: 
1.394     bowersj2 7491: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7492: for later delivery
1.191     harris41 7493: 
1.394     bowersj2 7494: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7495: 
1.394     bowersj2 7496: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7497: that was requested
1.191     harris41 7498: 
1.243     albertel 7499: =back
1.191     harris41 7500: 
1.243     albertel 7501: =head1 PUBLIC SUBROUTINES
1.191     harris41 7502: 
1.243     albertel 7503: =head2 Session Environment Functions
1.191     harris41 7504: 
1.243     albertel 7505: =over 4
1.191     harris41 7506: 
1.394     bowersj2 7507: =item * 
                   7508: X<appenv()>
                   7509: B<appenv(%hash)>: the value of %hash is written to
                   7510: the user envirnoment file, and will be restored for each access this
1.620     albertel 7511: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7512: process
1.191     harris41 7513: 
                   7514: =item *
1.394     bowersj2 7515: X<delenv()>
                   7516: B<delenv($regexp)>: removes all items from the session
                   7517: environment file that matches the regular expression in $regexp. The
1.620     albertel 7518: values are also delted from the current processes %env.
1.191     harris41 7519: 
1.243     albertel 7520: =back
                   7521: 
                   7522: =head2 User Information
1.191     harris41 7523: 
1.243     albertel 7524: =over 4
1.191     harris41 7525: 
                   7526: =item *
1.394     bowersj2 7527: X<queryauthenticate()>
                   7528: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7529: authentication scheme
                   7530: 
                   7531: =item *
1.394     bowersj2 7532: X<authenticate()>
                   7533: B<authenticate($uname,$upass,$udom)>: try to
                   7534: authenticate user from domain's lib servers (first use the current
                   7535: one). C<$upass> should be the users password.
1.191     harris41 7536: 
                   7537: =item *
1.394     bowersj2 7538: X<homeserver()>
                   7539: B<homeserver($uname,$udom)>: find the server which has
                   7540: the user's directory and files (there must be only one), this caches
                   7541: the answer, and also caches if there is a borken connection.
1.191     harris41 7542: 
                   7543: =item *
1.394     bowersj2 7544: X<idget()>
                   7545: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7546: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7547: username, and only 1 username per ID in a specific domain) (returns
                   7548: hash: id=>name,id=>name)
1.191     harris41 7549: 
                   7550: =item *
1.394     bowersj2 7551: X<idrget()>
                   7552: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7553: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7554: 
                   7555: =item *
1.394     bowersj2 7556: X<idput()>
                   7557: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7558: 
                   7559: =item *
1.394     bowersj2 7560: X<rolesinit()>
                   7561: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7562: 
                   7563: =item *
1.551     albertel 7564: X<getsection()>
                   7565: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7566: course $cname, return section name/number or '' for "not in course"
                   7567: and '-1' for "no section"
                   7568: 
                   7569: =item *
1.394     bowersj2 7570: X<userenvironment()>
                   7571: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7572: passed in @what from the requested user's environment, returns a hash
                   7573: 
                   7574: =back
                   7575: 
                   7576: =head2 User Roles
                   7577: 
                   7578: =over 4
                   7579: 
                   7580: =item *
                   7581: 
                   7582: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7583: actions
                   7584:  F: full access
                   7585:  U,I,K: authentication modes (cxx only)
                   7586:  '': forbidden
                   7587:  1: user needs to choose course
                   7588:  2: browse allowed
1.766     albertel 7589:  A: passphrase authentication needed
1.243     albertel 7590: 
                   7591: =item *
                   7592: 
                   7593: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7594: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7595: and course level
                   7596: 
                   7597: =item *
                   7598: 
                   7599: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7600: explanation of a user role term
                   7601: 
                   7602: =back
                   7603: 
                   7604: =head2 User Modification
                   7605: 
                   7606: =over 4
                   7607: 
                   7608: =item *
                   7609: 
                   7610: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7611: user for the level given by URL.  Optional start and end dates (leave empty
                   7612: string or zero for "no date")
1.191     harris41 7613: 
                   7614: =item *
                   7615: 
1.243     albertel 7616: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7617: change a users, password, possible return values are: ok,
                   7618: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7619: refused
1.191     harris41 7620: 
                   7621: =item *
                   7622: 
1.243     albertel 7623: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7624: 
                   7625: =item *
                   7626: 
1.243     albertel 7627: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7628: modify user
1.191     harris41 7629: 
                   7630: =item *
                   7631: 
1.286     matthew  7632: modifystudent
                   7633: 
                   7634: modify a students enrollment and identification information.
                   7635: The course id is resolved based on the current users environment.  
                   7636: This means the envoking user must be a course coordinator or otherwise
                   7637: associated with a course.
                   7638: 
1.297     matthew  7639: This call is essentially a wrapper for lonnet::modifyuser and
                   7640: lonnet::modify_student_enrollment
1.286     matthew  7641: 
                   7642: Inputs: 
                   7643: 
                   7644: =over 4
                   7645: 
                   7646: =item B<$udom> Students loncapa domain
                   7647: 
                   7648: =item B<$uname> Students loncapa login name
                   7649: 
                   7650: =item B<$uid> Students id/student number
                   7651: 
                   7652: =item B<$umode> Students authentication mode
                   7653: 
                   7654: =item B<$upass> Students password
                   7655: 
                   7656: =item B<$first> Students first name
                   7657: 
                   7658: =item B<$middle> Students middle name
                   7659: 
                   7660: =item B<$last> Students last name
                   7661: 
                   7662: =item B<$gene> Students generation
                   7663: 
                   7664: =item B<$usec> Students section in course
                   7665: 
                   7666: =item B<$end> Unix time of the roles expiration
                   7667: 
                   7668: =item B<$start> Unix time of the roles start date
                   7669: 
                   7670: =item B<$forceid> If defined, allow $uid to be changed
                   7671: 
                   7672: =item B<$desiredhome> server to use as home server for student
                   7673: 
                   7674: =back
1.297     matthew  7675: 
                   7676: =item *
                   7677: 
                   7678: modify_student_enrollment
                   7679: 
                   7680: Change a students enrollment status in a class.  The environment variable
                   7681: 'role.request.course' must be defined for this function to proceed.
                   7682: 
                   7683: Inputs:
                   7684: 
                   7685: =over 4
                   7686: 
                   7687: =item $udom, students domain
                   7688: 
                   7689: =item $uname, students name
                   7690: 
                   7691: =item $uid, students user id
                   7692: 
                   7693: =item $first, students first name
                   7694: 
                   7695: =item $middle
                   7696: 
                   7697: =item $last
                   7698: 
                   7699: =item $gene
                   7700: 
                   7701: =item $usec
                   7702: 
                   7703: =item $end
                   7704: 
                   7705: =item $start
                   7706: 
                   7707: =back
                   7708: 
1.191     harris41 7709: 
                   7710: =item *
                   7711: 
1.243     albertel 7712: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7713: custom role; give a custom role to a user for the level given by URL.  Specify
                   7714: name and domain of role author, and role name
1.191     harris41 7715: 
                   7716: =item *
                   7717: 
1.243     albertel 7718: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7719: 
                   7720: =item *
                   7721: 
1.243     albertel 7722: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7723: 
                   7724: =back
                   7725: 
                   7726: =head2 Course Infomation
                   7727: 
                   7728: =over 4
1.191     harris41 7729: 
                   7730: =item *
                   7731: 
1.631     albertel 7732: coursedescription($courseid) : returns a hash of information about the
                   7733: specified course id, including all environment settings for the
                   7734: course, the description of the course will be in the hash under the
                   7735: key 'description'
1.191     harris41 7736: 
                   7737: =item *
                   7738: 
1.624     albertel 7739: resdata($name,$domain,$type,@which) : request for current parameter
                   7740: setting for a specific $type, where $type is either 'course' or 'user',
                   7741: @what should be a list of parameters to ask about. This routine caches
                   7742: answers for 5 minutes.
1.243     albertel 7743: 
                   7744: =back
                   7745: 
                   7746: =head2 Course Modification
                   7747: 
                   7748: =over 4
1.191     harris41 7749: 
                   7750: =item *
                   7751: 
1.243     albertel 7752: writecoursepref($courseid,%prefs) : write preferences (environment
                   7753: database) for a course
1.191     harris41 7754: 
                   7755: =item *
                   7756: 
1.243     albertel 7757: createcourse($udom,$description,$url) : make/modify course
                   7758: 
                   7759: =back
                   7760: 
                   7761: =head2 Resource Subroutines
                   7762: 
                   7763: =over 4
1.191     harris41 7764: 
                   7765: =item *
                   7766: 
1.243     albertel 7767: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7768: 
                   7769: =item *
                   7770: 
1.243     albertel 7771: repcopy($filename) : subscribes to the requested file, and attempts to
                   7772: replicate from the owning library server, Might return
1.607     raeburn  7773: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7774: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7775: resource. Expects the local filesystem pathname
                   7776: (/home/httpd/html/res/....)
                   7777: 
                   7778: =back
                   7779: 
                   7780: =head2 Resource Information
                   7781: 
                   7782: =over 4
1.191     harris41 7783: 
                   7784: =item *
                   7785: 
1.243     albertel 7786: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7787: a vairety of different possible values, $varname should be a request
                   7788: string, and the other parameters can be used to specify who and what
                   7789: one is asking about.
                   7790: 
                   7791: Possible values for $varname are environment.lastname (or other item
                   7792: from the envirnment hash), user.name (or someother aspect about the
                   7793: user), resource.0.maxtries (or some other part and parameter of a
                   7794: resource)
1.204     albertel 7795: 
                   7796: =item *
                   7797: 
1.243     albertel 7798: directcondval($number) : get current value of a condition; reads from a state
                   7799: string
1.204     albertel 7800: 
                   7801: =item *
                   7802: 
1.243     albertel 7803: condval($condidx) : value of condition index based on state
1.204     albertel 7804: 
                   7805: =item *
                   7806: 
1.243     albertel 7807: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7808: resource's metadata, $what should be either a specific key, or either
                   7809: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7810: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7811: 
                   7812: this function automatically caches all requests
1.191     harris41 7813: 
                   7814: =item *
                   7815: 
1.243     albertel 7816: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7817: network of library servers; returns file handle of where SQL and regex results
                   7818: will be stored for query
1.191     harris41 7819: 
                   7820: =item *
                   7821: 
1.243     albertel 7822: symbread($filename) : return symbolic list entry (filename argument optional);
                   7823: returns the data handle
1.191     harris41 7824: 
                   7825: =item *
                   7826: 
1.243     albertel 7827: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7828: a possible symb for the URL in $thisfn, and if is an encryypted
                   7829: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7830: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7831: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7832: 
1.191     harris41 7833: 
                   7834: =item *
                   7835: 
1.243     albertel 7836: symbclean($symb) : removes versions numbers from a symb, returns the
                   7837: cleaned symb
1.191     harris41 7838: 
                   7839: =item *
                   7840: 
1.243     albertel 7841: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7842: course map, user must be in a course for it to work.
1.191     harris41 7843: 
                   7844: =item *
                   7845: 
1.243     albertel 7846: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7847: 
                   7848: =item *
                   7849: 
1.243     albertel 7850: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7851: a random seed, all arguments are optional, if they aren't sent it uses the
                   7852: environment to derive them. Note: if symb isn't sent and it can't get one
                   7853: from &symbread it will use the current time as its return value
1.191     harris41 7854: 
                   7855: =item *
                   7856: 
1.243     albertel 7857: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7858: unfakeable, receipt
1.191     harris41 7859: 
                   7860: =item *
                   7861: 
1.620     albertel 7862: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7863: 
                   7864: =item *
                   7865: 
1.243     albertel 7866: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7867: 
                   7868: =item *
                   7869: 
1.243     albertel 7870: 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 7871: 
                   7872: =item *
                   7873: 
1.243     albertel 7874: 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 7875: 
                   7876: =item *
                   7877: 
1.243     albertel 7878: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7879: 
                   7880: =item *
                   7881: 
1.243     albertel 7882: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7883: forcing spreadsheet to reevaluate the resource scores next time.
                   7884: 
                   7885: =back
                   7886: 
                   7887: =head2 Storing/Retreiving Data
                   7888: 
                   7889: =over 4
1.191     harris41 7890: 
                   7891: =item *
                   7892: 
1.243     albertel 7893: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7894: for this url; hashref needs to be given and should be a \%hashname; the
                   7895: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7896: be derived from the env
1.191     harris41 7897: 
                   7898: =item *
                   7899: 
1.243     albertel 7900: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7901: uses critical subroutine
1.191     harris41 7902: 
                   7903: =item *
                   7904: 
1.243     albertel 7905: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7906: all args are optional
1.191     harris41 7907: 
                   7908: =item *
                   7909: 
1.717     albertel 7910: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7911: dumps the complete (or key matching regexp) namespace into a hash
                   7912: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7913: normally &store()ed into
                   7914: 
                   7915: $range should be either an integer '100' (give me the first 100
                   7916:                                            matching records)
                   7917:               or be  two integers sperated by a - with no spaces
                   7918:                  '30-50' (give me the 30th through the 50th matching
                   7919:                           records)
                   7920: 
                   7921: 
                   7922: =item *
                   7923: 
                   7924: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7925: replaces a &store() version of data with a replacement set of data
                   7926: for a particular resource in a namespace passed in the $storehash hash 
                   7927: reference
                   7928: 
                   7929: =item *
                   7930: 
1.243     albertel 7931: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7932: works very similar to store/cstore, but all data is stored in a
                   7933: temporary location and can be reset using tmpreset, $storehash should
                   7934: be a hash reference, returns nothing on success
1.191     harris41 7935: 
                   7936: =item *
                   7937: 
1.243     albertel 7938: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7939: similar to restore, but all data is stored in a temporary location and
                   7940: can be reset using tmpreset. Returns a hash of values on success,
                   7941: error string otherwise.
1.191     harris41 7942: 
                   7943: =item *
                   7944: 
1.243     albertel 7945: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7946: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7947: 
                   7948: =item *
                   7949: 
1.243     albertel 7950: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7951: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7952: 
                   7953: =item *
                   7954: 
1.243     albertel 7955: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7956: namesp ($udom and $uname are optional)
1.191     harris41 7957: 
                   7958: =item *
                   7959: 
1.702     albertel 7960: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7961: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7962: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7963: 
1.702     albertel 7964: $range should be either an integer '100' (give me the first 100
                   7965:                                            matching records)
                   7966:               or be  two integers sperated by a - with no spaces
                   7967:                  '30-50' (give me the 30th through the 50th matching
                   7968:                           records)
1.449     matthew  7969: =item *
                   7970: 
                   7971: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7972: $store can be a scalar, an array reference, or if the amount to be 
                   7973: incremented is > 1, a hash reference.
                   7974: 
                   7975: ($udom and $uname are optional)
1.191     harris41 7976: 
                   7977: =item *
                   7978: 
1.243     albertel 7979: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7980: ($udom and $uname are optional)
1.191     harris41 7981: 
                   7982: =item *
                   7983: 
1.243     albertel 7984: cput($namespace,$storehash,$udom,$uname) : critical put
                   7985: ($udom and $uname are optional)
1.191     harris41 7986: 
                   7987: =item *
                   7988: 
1.748     albertel 7989: newput($namespace,$storehash,$udom,$uname) :
                   7990: 
                   7991: Attempts to store the items in the $storehash, but only if they don't
                   7992: currently exist, if this succeeds you can be certain that you have 
                   7993: successfully created a new key value pair in the $namespace db.
                   7994: 
                   7995: 
                   7996: Args:
                   7997:  $namespace: name of database to store values to
                   7998:  $storehash: hashref to store to the db
                   7999:  $udom: (optional) domain of user containing the db
                   8000:  $uname: (optional) name of user caontaining the db
                   8001: 
                   8002: Returns:
                   8003:  'ok' -> succeeded in storing all keys of $storehash
                   8004:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8005:                         least <key> already existed in the db (other
                   8006:                         requested keys may also already exist)
                   8007:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8008:  'con_lost' -> unable to contact request server
                   8009:  'refused' -> action was not allowed by remote machine
                   8010: 
                   8011: 
                   8012: =item *
                   8013: 
1.243     albertel 8014: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8015: reference filled in from namesp (encrypts the return communication)
                   8016: ($udom and $uname are optional)
1.191     harris41 8017: 
                   8018: =item *
                   8019: 
1.243     albertel 8020: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8021: critical subroutine
                   8022: 
                   8023: =back
                   8024: 
                   8025: =head2 Network Status Functions
                   8026: 
                   8027: =over 4
1.191     harris41 8028: 
                   8029: =item *
                   8030: 
                   8031: dirlist($uri) : return directory list based on URI
                   8032: 
                   8033: =item *
                   8034: 
1.243     albertel 8035: spareserver() : find server with least workload from spare.tab
                   8036: 
                   8037: =back
                   8038: 
                   8039: =head2 Apache Request
                   8040: 
                   8041: =over 4
1.191     harris41 8042: 
                   8043: =item *
                   8044: 
1.243     albertel 8045: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8046: localhost, posts hash
                   8047: 
                   8048: =back
                   8049: 
                   8050: =head2 Data to String to Data
                   8051: 
                   8052: =over 4
1.191     harris41 8053: 
                   8054: =item *
                   8055: 
1.243     albertel 8056: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8057: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8058: 
                   8059: =item *
                   8060: 
1.243     albertel 8061: hashref2str($hashref) : convert a hashref into a string complete with
                   8062: escaping and '=' and '&' separators, supports elements that are
                   8063: arrayrefs and hashrefs
1.191     harris41 8064: 
                   8065: =item *
                   8066: 
1.243     albertel 8067: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8068: with escaping and '&' separators, supports elements that are arrayrefs
                   8069: and hashrefs
1.191     harris41 8070: 
                   8071: =item *
                   8072: 
1.243     albertel 8073: str2hash($string) : convert string to hash using unescaping and
                   8074: splitting on '=' and '&', supports elements that are arrayrefs and
                   8075: hashrefs
1.191     harris41 8076: 
                   8077: =item *
                   8078: 
1.243     albertel 8079: str2array($string) : convert string to hash using unescaping and
                   8080: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8081: 
                   8082: =back
                   8083: 
                   8084: =head2 Logging Routines
                   8085: 
                   8086: =over 4
                   8087: 
                   8088: These routines allow one to make log messages in the lonnet.log and
                   8089: lonnet.perm logfiles.
1.191     harris41 8090: 
                   8091: =item *
                   8092: 
1.243     albertel 8093: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8094: 
                   8095: =item *
                   8096: 
1.243     albertel 8097: logthis() : append message to the normal lonnet.log file, it gets
                   8098: preiodically rolled over and deleted.
1.191     harris41 8099: 
                   8100: =item *
                   8101: 
1.243     albertel 8102: logperm() : append a permanent message to lonnet.perm.log, this log
                   8103: file never gets deleted by any automated portion of the system, only
                   8104: messages of critical importance should go in here.
                   8105: 
                   8106: =back
                   8107: 
                   8108: =head2 General File Helper Routines
                   8109: 
                   8110: =over 4
1.191     harris41 8111: 
                   8112: =item *
                   8113: 
1.481     raeburn  8114: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8115: (a) files in /uploaded
                   8116:   (i) If a local copy of the file exists - 
                   8117:       compares modification date of local copy with last-modified date for 
                   8118:       definitive version stored on home server for course. If local copy is 
                   8119:       stale, requests a new version from the home server and stores it. 
                   8120:       If the original has been removed from the home server, then local copy 
                   8121:       is unlinked.
                   8122:   (ii) If local copy does not exist -
                   8123:       requests the file from the home server and stores it. 
                   8124:   
                   8125:   If $caller is 'uploadrep':  
                   8126:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8127:     for request for files originally uploaded via DOCS. 
                   8128:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8129:   
                   8130:   Otherwise:
                   8131:      This indicates a call from the content generation phase of the request.
                   8132:      -  returns the entire contents of the file or -1.
                   8133:      
                   8134: (b) files in /res
                   8135:    - returns the entire contents of a file or -1; 
                   8136:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8137: 
1.712     albertel 8138: 
                   8139: =item *
                   8140: 
                   8141: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8142:                   reference
                   8143: 
                   8144: returns either a stat() list of data about the file or an empty list
                   8145: if the file doesn't exist or couldn't find out about it (connection
                   8146: problems or user unknown)
                   8147: 
1.191     harris41 8148: =item *
                   8149: 
1.243     albertel 8150: filelocation($dir,$file) : returns file system location of a file
                   8151: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8152: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8153: and a file of ../bob will become /a/bob)
1.191     harris41 8154: 
                   8155: =item *
                   8156: 
                   8157: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8158: filelocation except for hrefs
                   8159: 
                   8160: =item *
                   8161: 
                   8162: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8163: 
1.243     albertel 8164: =back
                   8165: 
1.608     albertel 8166: =head2 Usererfile file routines (/uploaded*)
                   8167: 
                   8168: =over 4
                   8169: 
                   8170: =item *
                   8171: 
                   8172: userfileupload(): main rotine for putting a file in a user or course's
                   8173:                   filespace, arguments are,
                   8174: 
1.620     albertel 8175:  formname - required - this is the name of the element in $env where the
1.608     albertel 8176:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8177:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8178:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8179:  coursedoc - if true, store the file in the course of the active role
                   8180:              of the current user
                   8181:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8182:          if undefined, it will be placed in "unknown"
                   8183: 
                   8184:  (This routine calls clean_filename() to remove any dangerous
                   8185:  characters from the filename, and then calls finuserfileupload() to
                   8186:  complete the transaction)
                   8187: 
                   8188:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8189:  and /adm/notfound.html if unsuccessful
                   8190: 
                   8191: =item *
                   8192: 
                   8193: clean_filename(): routine for cleaing a filename up for storage in
                   8194:                  userfile space, argument is:
                   8195: 
                   8196:  filename - proposed filename
                   8197: 
                   8198: returns: the new clean filename
                   8199: 
                   8200: =item *
                   8201: 
                   8202: finishuserfileupload(): routine that creaes and sends the file to
                   8203: userspace, probably shouldn't be called directly
                   8204: 
                   8205:   docuname: username or courseid of destination for the file
                   8206:   docudom: domain of user/course of destination for the file
                   8207:   formname: same as for userfileupload()
                   8208:   fname: filename (inculding subdirectories) for the file
                   8209: 
                   8210:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8211:  and /adm/notfound.html if unsuccessful
                   8212: 
                   8213: =item *
                   8214: 
                   8215: renameuserfile(): renames an existing userfile to a new name
                   8216: 
                   8217:   Args:
                   8218:    docuname: username or courseid of destination for the file
                   8219:    docudom: domain of user/course of destination for the file
                   8220:    old: current file name (including any subdirs under userfiles)
                   8221:    new: desired file name (including any subdirs under userfiles)
                   8222: 
                   8223: =item *
                   8224: 
                   8225: mkdiruserfile(): creates a directory is a userfiles dir
                   8226: 
                   8227:   Args:
                   8228:    docuname: username or courseid of destination for the file
                   8229:    docudom: domain of user/course of destination for the file
                   8230:    dir: dir to create (including any subdirs under userfiles)
                   8231: 
                   8232: =item *
                   8233: 
                   8234: removeuserfile(): removes a file that exists in userfiles
                   8235: 
                   8236:   Args:
                   8237:    docuname: username or courseid of destination for the file
                   8238:    docudom: domain of user/course of destination for the file
                   8239:    fname: filname to delete (including any subdirs under userfiles)
                   8240: 
                   8241: =item *
                   8242: 
                   8243: removeuploadedurl(): convience function for removeuserfile()
                   8244: 
                   8245:   Args:
                   8246:    url:  a full /uploaded/... url to delete
                   8247: 
1.747     albertel 8248: =item * 
                   8249: 
                   8250: get_portfile_permissions():
                   8251:   Args:
                   8252:     domain: domain of user or course contain the portfolio files
                   8253:     user: name of user or num of course contain the portfolio files
                   8254:   Returns:
                   8255:     hashref of a dump of the proper file_permissions.db
                   8256:    
                   8257: 
                   8258: =item * 
                   8259: 
                   8260: get_access_controls():
                   8261: 
                   8262: Args:
                   8263:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8264:   group: (optional) the group you want the files associated with
                   8265:   file: (optional) the file you want access info on
                   8266: 
                   8267: Returns:
1.749     raeburn  8268:     a hash (keys are file names) of hashes containing
                   8269:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8270:         values are XML containing access control settings (see below) 
1.747     albertel 8271: 
                   8272: Internal notes:
                   8273: 
1.749     raeburn  8274:  access controls are stored in file_permissions.db as key=value pairs.
                   8275:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8276:         where scope -> public,guest,course,group,domains or users.
                   8277:               end -> UNIX time for end of access (0 -> no end date)
                   8278:               start -> UNIX time for start of access
                   8279: 
                   8280:     value -> XML description of access control
                   8281:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8282:             <start></start>
                   8283:             <end></end>
                   8284: 
                   8285:             <password></password>  for scope type = guest
                   8286: 
                   8287:             <domain></domain>     for scope type = course or group
                   8288:             <number></number>
                   8289:             <roles id="">
                   8290:              <role></role>
                   8291:              <access></access>
                   8292:              <section></section>
                   8293:              <group></group>
                   8294:             </roles>
                   8295: 
                   8296:             <dom></dom>         for scope type = domains
                   8297: 
                   8298:             <users>             for scope type = users
                   8299:              <user>
                   8300:               <uname></uname>
                   8301:               <udom></udom>
                   8302:              </user>
                   8303:             </users>
                   8304:            </scope> 
                   8305:               
                   8306:  Access data is also aggregated for each file in an additional key=value pair:
                   8307:  key -> path to file/file_name\0accesscontrol 
                   8308:  value -> reference to hash
                   8309:           hash contains key = value pairs
                   8310:           where key = uniqueID:scope_end_start
                   8311:                 value = UNIX time record was last updated
                   8312: 
                   8313:           Used to improve speed of look-ups of access controls for each file.  
                   8314:  
                   8315:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8316: 
                   8317: modify_access_controls():
                   8318: 
                   8319: Modifies access controls for a portfolio file
                   8320: Args
                   8321: 1. file name
                   8322: 2. reference to hash of required changes,
                   8323: 3. domain
                   8324: 4. username
                   8325:   where domain,username are the domain of the portfolio owner 
                   8326:   (either a user or a course) 
                   8327: 
                   8328: Returns:
                   8329: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8330: 2. result of deletions ('ok' or 'error', with error message).
                   8331: 3. reference to hash of any new or updated access controls.
                   8332: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8333:    key = integer (inbound ID)
                   8334:    value = uniqueID  
1.747     albertel 8335: 
1.608     albertel 8336: =back
                   8337: 
1.243     albertel 8338: =head2 HTTP Helper Routines
                   8339: 
                   8340: =over 4
                   8341: 
1.191     harris41 8342: =item *
                   8343: 
                   8344: escape() : unpack non-word characters into CGI-compatible hex codes
                   8345: 
                   8346: =item *
                   8347: 
                   8348: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8349: 
1.243     albertel 8350: =back
                   8351: 
                   8352: =head1 PRIVATE SUBROUTINES
                   8353: 
                   8354: =head2 Underlying communication routines (Shouldn't call)
                   8355: 
                   8356: =over 4
                   8357: 
                   8358: =item *
                   8359: 
                   8360: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8361: 
                   8362: =item *
                   8363: 
                   8364: reply() : uses subreply to send a message to remote machine, logs all failures
                   8365: 
                   8366: =item *
                   8367: 
                   8368: critical() : passes a critical message to another server; if cannot
                   8369: get through then place message in connection buffer directory and
                   8370: returns con_delayed, if incapable of saving message, returns
                   8371: con_failed
                   8372: 
                   8373: =item *
                   8374: 
                   8375: reconlonc() : tries to reconnect lonc client processes.
                   8376: 
                   8377: =back
                   8378: 
                   8379: =head2 Resource Access Logging
                   8380: 
                   8381: =over 4
                   8382: 
                   8383: =item *
                   8384: 
                   8385: flushcourselogs() : flush (save) buffer logs and access logs
                   8386: 
                   8387: =item *
                   8388: 
                   8389: courselog($what) : save message for course in hash
                   8390: 
                   8391: =item *
                   8392: 
                   8393: courseacclog($what) : save message for course using &courselog().  Perform
                   8394: special processing for specific resource types (problems, exams, quizzes, etc).
                   8395: 
1.191     harris41 8396: =item *
                   8397: 
                   8398: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8399: as a PerlChildExitHandler
1.243     albertel 8400: 
                   8401: =back
                   8402: 
                   8403: =head2 Other
                   8404: 
                   8405: =over 4
                   8406: 
                   8407: =item *
                   8408: 
                   8409: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8410: 
                   8411: =back
                   8412: 
                   8413: =cut

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