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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.792   ! raeburn     4: # $Id: lonnet.pm,v 1.791 2006/10/13 04:23:15 raeburn 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.791     raeburn  1982:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
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.791     raeburn  1991:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
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.792   ! raeburn  4260: sub auto_instcode_defaults {
        !          4261:     my ($domain,$returnhash,$code_order) = @_;
        !          4262:     my @homeservers;
        !          4263:     foreach my $tryserver (keys %libserv) {
        !          4264:         if ($hostdom{$tryserver} eq $domain) {
        !          4265:             if (!grep/^\Q$tryserver\E$/,@homeservers) {
        !          4266:                 push(@homeservers,$tryserver);
        !          4267:             }
        !          4268:         }
        !          4269:     }
        !          4270:     my $ok_response = 0;
        !          4271:     my $response;
        !          4272:     while (@homeservers > 0 && $ok_response == 0) {
        !          4273:         my $server = shift(@homeservers);
        !          4274:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
        !          4275:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
        !          4276:             foreach (split(/\&/,$response)) {
        !          4277:                 my ($name,$value)=split(/\=/,$_);
        !          4278:                 if ($name eq 'code_order') {
        !          4279:                     @{$code_order} = split(/\&/,&unescape($value));
        !          4280:                 } else {
        !          4281:                     $$returnhash{&unescape($name)}=&unescape($value);
        !          4282:                 }
        !          4283:             }
        !          4284:         }
        !          4285:         $ok_response = 1;
        !          4286:     }
        !          4287:     if ($ok_response) {
        !          4288:         return 'ok';
        !          4289:     } else {
        !          4290:         return $response;
        !          4291:     }
        !          4292: } 
        !          4293: 
1.777     albertel 4294: sub auto_validate_class_sec {
1.773     raeburn  4295:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4296:     my $homeserver = &homeserver($cnum,$cdom);
                   4297:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4298:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4299:     return $response;
                   4300: }
                   4301: 
1.679     raeburn  4302: # ------------------------------------------------------- Course Group routines
                   4303: 
                   4304: sub get_coursegroups {
1.683     raeburn  4305:     my ($cdom,$cnum,$group) = @_;
                   4306:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4307: }
                   4308: 
                   4309: sub modify_coursegroup {
                   4310:     my ($cdom,$cnum,$groupsettings) = @_;
                   4311:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4312: }
                   4313: 
                   4314: sub modify_group_roles {
                   4315:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4316:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4317:     my $role = 'gr/'.&escape($userprivs);
                   4318:     my ($uname,$udom) = split(/:/,$user);
                   4319:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4320:     if ($result eq 'ok') {
                   4321:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4322:     }
1.679     raeburn  4323:     return $result;
                   4324: }
                   4325: 
                   4326: sub modify_coursegroup_membership {
                   4327:     my ($cdom,$cnum,$membership) = @_;
                   4328:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4329:     return $result;
                   4330: }
                   4331: 
1.682     raeburn  4332: sub get_active_groups {
                   4333:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4334:     my $now = time;
                   4335:     my %groups = ();
                   4336:     foreach my $key (keys(%env)) {
                   4337:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4338:             my ($start,$end) = split(/\./,$env{$key});
                   4339:             if (($end!=0) && ($end<$now)) { next; }
                   4340:             if (($start!=0) && ($start>$now)) { next; }
                   4341:             if ($1 eq $cdom && $2 eq $cnum) {
                   4342:                 $groups{$3} = $env{$key} ;
                   4343:             }
                   4344:         }
                   4345:     }
                   4346:     return %groups;
                   4347: }
                   4348: 
1.683     raeburn  4349: sub get_group_membership {
                   4350:     my ($cdom,$cnum,$group) = @_;
                   4351:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4352: }
                   4353: 
                   4354: sub get_users_groups {
                   4355:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4356:     my @usersgroups;
1.683     raeburn  4357:     my $cachetime=1800;
                   4358:     $courseid=~s/\_/\//g;
                   4359:     $courseid=~s/^(\w)/\/$1/;
                   4360: 
                   4361:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4362:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4363:     if (defined($cached)) {
1.734     albertel 4364:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4365:     } else {  
                   4366:         $grouplist = '';
                   4367:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4368:         my ($tmp) = keys(%roleshash);
                   4369:         if ($tmp=~/^error:/) {
                   4370:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4371:         } else {
                   4372:             my $access_end = $env{'course.'.$courseid.
                   4373:                                   '.default_enrollment_end_date'};
                   4374:             my $now = time;
1.734     albertel 4375:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4376:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4377:                     my $group = $1;
                   4378:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4379:                         my $start = $2;
                   4380:                         my $end = $1;
                   4381:                         if ($start == -1) { next; } # deleted from group
                   4382:                         if (($start!=0) && ($start>$now)) { next; }
                   4383:                         if (($end!=0) && ($end<$now)) {
                   4384:                             if ($access_end && $access_end < $now) {
                   4385:                                 if ($access_end - $end < 86400) {
                   4386:                                     push(@usersgroups,$group);
                   4387:                                 }
                   4388:                             }
                   4389:                             next;
                   4390:                         }
                   4391:                         push(@usersgroups,$group);
                   4392:                     }
1.683     raeburn  4393:                 }
                   4394:             }
1.733     raeburn  4395:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4396:             $grouplist = join(':',@usersgroups);
                   4397:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4398:         }
                   4399:     }
1.733     raeburn  4400:     return @usersgroups;
1.683     raeburn  4401: }
                   4402: 
                   4403: sub devalidate_getgroups_cache {
                   4404:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4405:     my $courseid = $cdom.'_'.$cnum;
                   4406:     $courseid=~s/\_/\//g;
                   4407:     $courseid=~s/^(\w)/\/$1/;
                   4408:     my $hashid="$udom:$uname:$courseid";
                   4409:     &devalidate_cache_new('getgroups',$hashid);
                   4410: }
                   4411: 
1.12      www      4412: # ------------------------------------------------------------------ Plain Text
                   4413: 
                   4414: sub plaintext {
1.742     raeburn  4415:     my ($short,$type,$cid) = @_;
1.758     albertel 4416:     if ($short =~ /^cr/) {
                   4417: 	return (split('/',$short))[-1];
                   4418:     }
1.742     raeburn  4419:     if (!defined($cid)) {
                   4420:         $cid = $env{'request.course.id'};
                   4421:     }
                   4422:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4423:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4424:                                           '.plaintext'});
                   4425:     }
                   4426:     my %rolenames = (
                   4427:                       Course => 'std',
                   4428:                       Group => 'alt1',
                   4429:                     );
                   4430:     if (defined($type) && 
                   4431:          defined($rolenames{$type}) && 
                   4432:          defined($prp{$short}{$rolenames{$type}})) {
                   4433:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4434:     } else {
                   4435:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4436:     }
1.12      www      4437: }
                   4438: 
                   4439: # ----------------------------------------------------------------- Assign Role
                   4440: 
                   4441: sub assignrole {
1.357     www      4442:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4443:     my $mrole;
                   4444:     if ($role =~ /^cr\//) {
1.393     www      4445:         my $cwosec=$url;
                   4446:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4447: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4448:            &logthis('Refused custom assignrole: '.
                   4449:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4450: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4451:            return 'refused'; 
                   4452:         }
1.21      www      4453:         $mrole='cr';
1.678     raeburn  4454:     } elsif ($role =~ /^gr\//) {
                   4455:         my $cwogrp=$url;
                   4456:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4457:         unless (&allowed('mdg',$cwogrp)) {
                   4458:             &logthis('Refused group assignrole: '.
                   4459:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4460:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4461:             return 'refused';
                   4462:         }
                   4463:         $mrole='gr';
1.21      www      4464:     } else {
1.82      www      4465:         my $cwosec=$url;
1.83      www      4466:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4467:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4468:            &logthis('Refused assignrole: '.
                   4469:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4470: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4471:            return 'refused'; 
                   4472:         }
1.21      www      4473:         $mrole=$role;
                   4474:     }
1.620     albertel 4475:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4476:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4477:     if ($end) { $command.='_'.$end; }
1.21      www      4478:     if ($start) {
                   4479: 	if ($end) { 
1.81      www      4480:            $command.='_'.$start; 
1.21      www      4481:         } else {
1.81      www      4482:            $command.='_0_'.$start;
1.21      www      4483:         }
                   4484:     }
1.739     raeburn  4485:     my $origstart = $start;
                   4486:     my $origend = $end;
1.357     www      4487: # actually delete
                   4488:     if ($deleteflag) {
1.373     www      4489: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4490: # modify command to delete the role
1.620     albertel 4491:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4492:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4493: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4494: # set start and finish to negative values for userrolelog
                   4495:            $start=-1;
                   4496:            $end=-1;
                   4497:         }
                   4498:     }
                   4499: # send command
1.349     www      4500:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4501: # log new user role if status is ok
1.349     www      4502:     if ($answer eq 'ok') {
1.663     raeburn  4503: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4504: # for course roles, perform group memberships changes triggered by role change.
                   4505:         unless ($role =~ /^gr/) {
                   4506:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4507:                                              $origstart);
                   4508:         }
1.349     www      4509:     }
                   4510:     return $answer;
1.169     harris41 4511: }
                   4512: 
                   4513: # -------------------------------------------------- Modify user authentication
1.197     www      4514: # Overrides without validation
                   4515: 
1.169     harris41 4516: sub modifyuserauth {
                   4517:     my ($udom,$uname,$umode,$upass)=@_;
                   4518:     my $uhome=&homeserver($uname,$udom);
1.197     www      4519:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4520:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4521:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4522:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4523:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4524: 		     &escape($upass),$uhome);
1.620     albertel 4525:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4526:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4527:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4528:     &log($udom,,$uname,$uhome,
1.620     albertel 4529:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4530:                                      $env{'user.name'}.', '.$umode.
1.197     www      4531:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4532:     unless ($reply eq 'ok') {
1.197     www      4533:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4534: 	return 'error: '.$reply;
                   4535:     }   
1.170     harris41 4536:     return 'ok';
1.80      www      4537: }
                   4538: 
1.81      www      4539: # --------------------------------------------------------------- Modify a user
1.80      www      4540: 
1.81      www      4541: sub modifyuser {
1.206     matthew  4542:     my ($udom,    $uname, $uid,
                   4543:         $umode,   $upass, $first,
                   4544:         $middle,  $last,  $gene,
1.387     www      4545:         $forceid, $desiredhome, $email)=@_;
1.198     www      4546:     $udom=~s/\W//g;
                   4547:     $uname=~s/\W//g;
1.81      www      4548:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4549:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4550: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4551:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4552:                                      ' desiredhome not specified'). 
1.620     albertel 4553:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4554:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4555:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4556: # ----------------------------------------------------------------- Create User
1.406     albertel 4557:     if (($uhome eq 'no_host') && 
                   4558: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4559:         my $unhome='';
1.209     matthew  4560:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4561:             $unhome = $desiredhome;
1.620     albertel 4562: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4563: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4564:         } else { # load balancing routine for determining $unhome
1.80      www      4565:             my $tryserver;
1.81      www      4566:             my $loadm=10000000;
1.80      www      4567:             foreach $tryserver (keys %libserv) {
                   4568: 	       if ($hostdom{$tryserver} eq $udom) {
                   4569:                   my $answer=reply('load',$tryserver);
                   4570:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4571: 		      $loadm=$answer;
                   4572:                       $unhome=$tryserver;
                   4573:                   }
                   4574: 	       }
                   4575: 	    }
                   4576:         }
                   4577:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4578: 	    return 'error: unable to find a home server for '.$uname.
                   4579:                    ' in domain '.$udom;
1.80      www      4580:         }
                   4581:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4582:                          &escape($upass),$unhome);
                   4583: 	unless ($reply eq 'ok') {
                   4584:             return 'error: '.$reply;
                   4585:         }   
1.230     stredwic 4586:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4587:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4588: 	    return 'error: unable verify users home machine.';
1.80      www      4589:         }
1.209     matthew  4590:     }   # End of creation of new user
1.80      www      4591: # ---------------------------------------------------------------------- Add ID
                   4592:     if ($uid) {
                   4593:        $uid=~tr/A-Z/a-z/;
                   4594:        my %uidhash=&idrget($udom,$uname);
1.196     www      4595:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4596:          && (!$forceid)) {
1.80      www      4597: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4598: 	      return 'error: user id "'.$uid.'" does not match '.
                   4599:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4600:           }
                   4601:        } else {
                   4602: 	  &idput($udom,($uname => $uid));
                   4603:        }
                   4604:     }
                   4605: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4606:     my @tmp=&get('environment',
1.134     albertel 4607: 		   ['firstname','middlename','lastname','generation'],
                   4608: 		   $udom,$uname);
1.313     matthew  4609:     my %names;
                   4610:     if ($tmp[0] =~ m/^error:.*/) { 
                   4611:         %names=(); 
                   4612:     } else {
                   4613:         %names = @tmp;
                   4614:     }
1.388     www      4615: #
                   4616: # Make sure to not trash student environment if instructor does not bother
                   4617: # to supply name and email information
                   4618: #
                   4619:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4620:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4621:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4622:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4623:     if ($email) {
                   4624:        $email=~s/[^\w\@\.\-\,]//gs;
                   4625:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4626: 			   $names{'critnotification'} = $email;
                   4627: 			   $names{'permanentemail'} = $email; }
                   4628:     }
1.134     albertel 4629:     my $reply = &put('environment', \%names, $udom,$uname);
                   4630:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4631:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4632:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4633:              $umode.', '.$first.', '.$middle.', '.
                   4634: 	     $last.', '.$gene.' by '.
1.620     albertel 4635:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4636:     return 'ok';
1.80      www      4637: }
                   4638: 
1.81      www      4639: # -------------------------------------------------------------- Modify student
1.80      www      4640: 
1.81      www      4641: sub modifystudent {
                   4642:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4643:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4644:     if (!$cid) {
1.620     albertel 4645: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4646: 	    return 'not_in_class';
                   4647: 	}
1.80      www      4648:     }
                   4649: # --------------------------------------------------------------- Make the user
1.81      www      4650:     my $reply=&modifyuser
1.209     matthew  4651: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4652:          $desiredhome,$email);
1.80      www      4653:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4654:     # This will cause &modify_student_enrollment to get the uid from the
                   4655:     # students environment
                   4656:     $uid = undef if (!$forceid);
1.455     albertel 4657:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4658: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4659:     return $reply;
                   4660: }
                   4661: 
                   4662: sub modify_student_enrollment {
1.515     raeburn  4663:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4664:     my ($cdom,$cnum,$chome);
                   4665:     if (!$cid) {
1.620     albertel 4666: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4667: 	    return 'not_in_class';
                   4668: 	}
1.620     albertel 4669: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4670: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4671:     } else {
                   4672: 	($cdom,$cnum)=split(/_/,$cid);
                   4673:     }
1.620     albertel 4674:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4675:     if (!$chome) {
1.457     raeburn  4676: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4677:     }
1.455     albertel 4678:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4679:     # Make sure the user exists
1.81      www      4680:     my $uhome=&homeserver($uname,$udom);
                   4681:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4682: 	return 'error: no such user';
                   4683:     }
1.297     matthew  4684:     # Get student data if we were not given enough information
                   4685:     if (!defined($first)  || $first  eq '' || 
                   4686:         !defined($last)   || $last   eq '' || 
                   4687:         !defined($uid)    || $uid    eq '' || 
                   4688:         !defined($middle) || $middle eq '' || 
                   4689:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4690:         # They did not supply us with enough data to enroll the student, so
                   4691:         # we need to pick up more information.
1.297     matthew  4692:         my %tmp = &get('environment',
1.294     matthew  4693:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4694:                        ,$udom,$uname);
                   4695: 
1.455     albertel 4696:         #foreach (keys(%tmp)) {
                   4697:         #    &logthis("key $_ = ".$tmp{$_});
                   4698:         #}
1.294     matthew  4699:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4700:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4701:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4702:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4703:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4704:     }
1.556     albertel 4705:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4706:     my $reply=cput('classlist',
                   4707: 		   {"$uname:$udom" => 
1.515     raeburn  4708: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4709: 		   $cdom,$cnum);
1.81      www      4710:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4711: 	return 'error: '.$reply;
1.652     albertel 4712:     } else {
                   4713: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4714:     }
1.297     matthew  4715:     # Add student role to user
1.83      www      4716:     my $uurl='/'.$cid;
1.81      www      4717:     $uurl=~s/\_/\//g;
                   4718:     if ($usec) {
                   4719: 	$uurl.='/'.$usec;
                   4720:     }
                   4721:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4722: }
                   4723: 
1.556     albertel 4724: sub format_name {
                   4725:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4726:     my $name;
                   4727:     if ($first ne 'lastname') {
                   4728: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4729:     } else {
                   4730: 	if ($lastname=~/\S/) {
                   4731: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4732: 	    $name=~s/\s+,/,/;
                   4733: 	} else {
                   4734: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4735: 	}
                   4736:     }
                   4737:     $name=~s/^\s+//;
                   4738:     $name=~s/\s+$//;
                   4739:     $name=~s/\s+/ /g;
                   4740:     return $name;
                   4741: }
                   4742: 
1.84      www      4743: # ------------------------------------------------- Write to course preferences
                   4744: 
                   4745: sub writecoursepref {
                   4746:     my ($courseid,%prefs)=@_;
                   4747:     $courseid=~s/^\///;
                   4748:     $courseid=~s/\_/\//g;
                   4749:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4750:     my $chome=homeserver($cnum,$cdomain);
                   4751:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4752: 	return 'error: no such course';
                   4753:     }
                   4754:     my $cstring='';
1.191     harris41 4755:     foreach (keys %prefs) {
1.84      www      4756: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4757:     }
1.84      www      4758:     $cstring=~s/\&$//;
                   4759:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4760: }
                   4761: 
                   4762: # ---------------------------------------------------------- Make/modify course
                   4763: 
                   4764: sub createcourse {
1.741     raeburn  4765:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4766:         $course_owner,$crstype)=@_;
1.84      www      4767:     $url=&declutter($url);
                   4768:     my $cid='';
1.264     matthew  4769:     unless (&allowed('ccc',$udom)) {
1.84      www      4770:         return 'refused';
                   4771:     }
                   4772: # ------------------------------------------------------------------- Create ID
1.674     www      4773:    my $uname=int(1+rand(9)).
                   4774:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4775:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4776:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4777: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4778:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4779:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4780:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4781:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4782:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4783:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4784:            return 'error: unable to generate unique course-ID';
                   4785:        } 
                   4786:    }
1.264     matthew  4787: # ------------------------------------------------ Check supplied server name
1.620     albertel 4788:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4789:     if (! exists($libserv{$course_server})) {
                   4790:         return 'error:bad server name '.$course_server;
                   4791:     }
1.84      www      4792: # ------------------------------------------------------------- Make the course
                   4793:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4794:                       $course_server);
1.84      www      4795:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4796:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4797:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4798: 	return 'error: no such course';
                   4799:     }
1.271     www      4800: # ----------------------------------------------------------------- Course made
1.516     raeburn  4801: # log existence
                   4802:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4803:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4804:                   &escape($crstype),$uhome);
1.358     www      4805:     &flushcourselogs();
                   4806: # set toplevel url
1.271     www      4807:     my $topurl=$url;
                   4808:     unless ($nonstandard) {
                   4809: # ------------------------------------------ For standard courses, make top url
                   4810:         my $mapurl=&clutter($url);
1.278     www      4811:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4812:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4813: <map>
                   4814: <resource id="1" type="start"></resource>
                   4815: <resource id="2" src="$mapurl"></resource>
                   4816: <resource id="3" type="finish"></resource>
                   4817: <link index="1" from="1" to="2"></link>
                   4818: <link index="2" from="2" to="3"></link>
                   4819: </map>
                   4820: ENDINITMAP
                   4821:         $topurl=&declutter(
1.638     albertel 4822:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4823:                           );
                   4824:     }
                   4825: # ----------------------------------------------------------- Write preferences
1.84      www      4826:     &writecoursepref($udom.'_'.$uname,
                   4827:                      ('description' => $description,
1.271     www      4828:                       'url'         => $topurl));
1.84      www      4829:     return '/'.$udom.'/'.$uname;
                   4830: }
                   4831: 
1.21      www      4832: # ---------------------------------------------------------- Assign Custom Role
                   4833: 
                   4834: sub assigncustomrole {
1.357     www      4835:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4836:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4837:                        $end,$start,$deleteflag);
1.21      www      4838: }
                   4839: 
                   4840: # ----------------------------------------------------------------- Revoke Role
                   4841: 
                   4842: sub revokerole {
1.357     www      4843:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4844:     my $now=time;
1.357     www      4845:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4846: }
                   4847: 
                   4848: # ---------------------------------------------------------- Revoke Custom Role
                   4849: 
                   4850: sub revokecustomrole {
1.357     www      4851:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4852:     my $now=time;
1.357     www      4853:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4854:            $deleteflag);
1.17      www      4855: }
                   4856: 
1.533     banghart 4857: # ------------------------------------------------------------ Disk usage
1.535     albertel 4858: sub diskusage {
1.533     banghart 4859:     my ($udom,$uname,$directoryRoot)=@_;
                   4860:     $directoryRoot =~ s/\/$//;
1.535     albertel 4861:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4862:     return $listing;
1.512     banghart 4863: }
                   4864: 
1.566     banghart 4865: sub is_locked {
                   4866:     my ($file_name, $domain, $user) = @_;
                   4867:     my @check;
                   4868:     my $is_locked;
                   4869:     push @check, $file_name;
1.613     albertel 4870:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4871: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4872:     my ($tmp)=keys(%locked);
                   4873:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4874:     
1.566     banghart 4875:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4876:         $is_locked = 'false';
                   4877:         foreach my $entry (@{$locked{$file_name}}) {
                   4878:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4879:                $is_locked = 'true';
                   4880:                last;
1.745     raeburn  4881:            }
                   4882:        }
1.566     banghart 4883:     } else {
                   4884:         $is_locked = 'false';
                   4885:     }
                   4886: }
                   4887: 
1.759     albertel 4888: sub declutter_portfile {
                   4889:     my ($file) = @_;
                   4890:     &logthis("got $file");
                   4891:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4892:     &logthis("ret $file");
                   4893:     return $file;
                   4894: }
                   4895: 
1.559     banghart 4896: # ------------------------------------------------------------- Mark as Read Only
                   4897: 
                   4898: sub mark_as_readonly {
                   4899:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4900:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4901:     my ($tmp)=keys(%current_permissions);
                   4902:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4903:     foreach my $file (@{$files}) {
1.759     albertel 4904: 	$file = &declutter_portfile($file);
1.561     banghart 4905:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4906:     }
1.613     albertel 4907:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4908:     return;
                   4909: }
                   4910: 
1.572     banghart 4911: # ------------------------------------------------------------Save Selected Files
                   4912: 
                   4913: sub save_selected_files {
                   4914:     my ($user, $path, @files) = @_;
                   4915:     my $filename = $user."savedfiles";
1.573     banghart 4916:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4917:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4918:     foreach my $file (@files) {
1.620     albertel 4919:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4920:     }
                   4921:     foreach my $file (@other_files) {
1.574     banghart 4922:         print (OUT $file."\n");
1.572     banghart 4923:     }
1.574     banghart 4924:     close (OUT);
1.572     banghart 4925:     return 'ok';
                   4926: }
                   4927: 
1.574     banghart 4928: sub clear_selected_files {
                   4929:     my ($user) = @_;
                   4930:     my $filename = $user."savedfiles";
                   4931:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4932:     print (OUT undef);
                   4933:     close (OUT);
                   4934:     return ("ok");    
                   4935: }
                   4936: 
1.572     banghart 4937: sub files_in_path {
                   4938:     my ($user, $path) = @_;
                   4939:     my $filename = $user."savedfiles";
                   4940:     my %return_files;
1.574     banghart 4941:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4942:     while (my $line_in = <IN>) {
1.574     banghart 4943:         chomp ($line_in);
                   4944:         my @paths_and_file = split (m!/!, $line_in);
                   4945:         my $file_part = pop (@paths_and_file);
                   4946:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4947:         $path_part.='/';
                   4948:         my $path_and_file = $path_part.$file_part;
                   4949:         if ($path_part eq $path) {
                   4950:             $return_files{$file_part}= 'selected';
                   4951:         }
                   4952:     }
1.574     banghart 4953:     close (IN);
                   4954:     return (\%return_files);
1.572     banghart 4955: }
                   4956: 
                   4957: # called in portfolio select mode, to show files selected NOT in current directory
                   4958: sub files_not_in_path {
                   4959:     my ($user, $path) = @_;
                   4960:     my $filename = $user."savedfiles";
                   4961:     my @return_files;
                   4962:     my $path_part;
1.574     banghart 4963:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4964:     while (<IN>) {
                   4965:         #ok, I know it's clunky, but I want it to work
                   4966:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4967:         my $file_part = pop (@paths_and_file);
                   4968:         chomp ($file_part);
                   4969:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4970:         $path_part .= '/';
                   4971:         my $path_and_file = $path_part.$file_part;
                   4972:         if ($path_part ne $path) {
1.574     banghart 4973:             push (@return_files, ($path_and_file));
1.572     banghart 4974:         }
                   4975:     }
1.574     banghart 4976:     close (OUT);
                   4977:     return (@return_files);
1.572     banghart 4978: }
                   4979: 
1.745     raeburn  4980: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4981: 
1.745     raeburn  4982: sub get_portfile_permissions {
                   4983:     my ($domain,$user) = @_;
1.613     albertel 4984:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4985:     my ($tmp)=keys(%current_permissions);
                   4986:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4987:     return \%current_permissions;
                   4988: }
                   4989: 
                   4990: #---------------------------------------------Get portfolio file access controls
                   4991: 
1.749     raeburn  4992: sub get_access_controls {
1.745     raeburn  4993:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4994:     my %access;
                   4995:     my $real_file = $file;
                   4996:     $file =~ s/\.meta$//;
1.745     raeburn  4997:     if (defined($file)) {
1.749     raeburn  4998:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4999:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5000:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5001:             }
                   5002:         }
1.745     raeburn  5003:     } else {
1.749     raeburn  5004:         foreach my $key (keys(%{$current_permissions})) {
                   5005:             if ($key =~ /\0accesscontrol$/) {
                   5006:                 if (defined($group)) {
                   5007:                     if ($key !~ m-^\Q$group\E/-) {
                   5008:                         next;
                   5009:                     }
                   5010:                 }
                   5011:                 my ($fullpath) = split(/\0/,$key);
                   5012:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5013:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5014:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5015:                     }
                   5016:                 }
                   5017:             }
                   5018:         }
                   5019:     }
                   5020:     return %access;
                   5021: }
                   5022: 
                   5023: sub modify_access_controls {
                   5024:     my ($file_name,$changes,$domain,$user)=@_;
                   5025:     my ($outcome,$deloutcome);
                   5026:     my %store_permissions;
                   5027:     my %new_values;
                   5028:     my %new_control;
                   5029:     my %translation;
                   5030:     my @deletions = ();
                   5031:     my $now = time;
                   5032:     if (exists($$changes{'activate'})) {
                   5033:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5034:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5035:             my $numnew = scalar(@newitems);
                   5036:             for (my $i=0; $i<$numnew; $i++) {
                   5037:                 my $newkey = $newitems[$i];
                   5038:                 my $newid = &Apache::loncommon::get_cgi_id();
                   5039:                 $newkey =~ s/^(\d+)/$newid/;
                   5040:                 $translation{$1} = $newid;
                   5041:                 $new_values{$file_name."\0".$newkey} = 
                   5042:                                           $$changes{'activate'}{$newitems[$i]};
                   5043:                 $new_control{$newkey} = $now;
                   5044:             }
                   5045:         }
                   5046:     }
                   5047:     my %todelete;
                   5048:     my %changed_items;
                   5049:     foreach my $action ('delete','update') {
                   5050:         if (exists($$changes{$action})) {
                   5051:             if (ref($$changes{$action}) eq 'HASH') {
                   5052:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5053:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5054:                     if ($action eq 'delete') { 
                   5055:                         $todelete{$itemnum} = 1;
                   5056:                     } else {
                   5057:                         $changed_items{$itemnum} = $key;
                   5058:                     }
                   5059:                 }
1.745     raeburn  5060:             }
                   5061:         }
1.749     raeburn  5062:     }
                   5063:     # get lock on access controls for file.
                   5064:     my $lockhash = {
                   5065:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5066:                                                        ':'.$env{'user.domain'},
                   5067:                    }; 
                   5068:     my $tries = 0;
                   5069:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5070:    
                   5071:     while (($gotlock ne 'ok') && $tries <3) {
                   5072:         $tries ++;
                   5073:         sleep 1;
                   5074:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5075:     }
                   5076:     if ($gotlock eq 'ok') {
                   5077:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5078:         my ($tmp)=keys(%curr_permissions);
                   5079:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5080:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5081:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5082:             if (ref($curr_controls) eq 'HASH') {
                   5083:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5084:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5085:                     if (defined($todelete{$itemnum})) {
                   5086:                         push(@deletions,$file_name."\0".$control_item);
                   5087:                     } else {
                   5088:                         if (defined($changed_items{$itemnum})) {
                   5089:                             $new_control{$changed_items{$itemnum}} = $now;
                   5090:                             push(@deletions,$file_name."\0".$control_item);
                   5091:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5092:                         } else {
                   5093:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5094:                         }
                   5095:                     }
1.745     raeburn  5096:                 }
                   5097:             }
                   5098:         }
1.749     raeburn  5099:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5100:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5101:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5102:         #  remove lock
                   5103:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5104:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5105:     } else {
                   5106:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5107:     }
1.749     raeburn  5108:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5109: }
                   5110: 
                   5111: #------------------------------------------------------Get Marked as Read Only
                   5112: 
                   5113: sub get_marked_as_readonly {
                   5114:     my ($domain,$user,$what,$group) = @_;
                   5115:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5116:     my @readonly_files;
1.629     banghart 5117:     my $cmp1=$what;
                   5118:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5119:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5120:         if (defined($group)) {
                   5121:             if ($file_name !~ m-^\Q$group\E/-) {
                   5122:                 next;
                   5123:             }
                   5124:         }
1.561     banghart 5125:         if (ref($value) eq "ARRAY"){
                   5126:             foreach my $stored_what (@{$value}) {
1.629     banghart 5127:                 my $cmp2=$stored_what;
1.759     albertel 5128:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5129:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5130:                 }
1.629     banghart 5131:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5132:                     push(@readonly_files, $file_name);
1.745     raeburn  5133:                     last;
1.563     banghart 5134:                 } elsif (!defined($what)) {
                   5135:                     push(@readonly_files, $file_name);
1.745     raeburn  5136:                     last;
1.561     banghart 5137:                 }
                   5138:             }
1.745     raeburn  5139:         }
1.561     banghart 5140:     }
                   5141:     return @readonly_files;
                   5142: }
1.577     banghart 5143: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5144: 
1.577     banghart 5145: sub get_marked_as_readonly_hash {
1.745     raeburn  5146:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5147:     my %readonly_files;
1.745     raeburn  5148:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5149:         if (defined($group)) {
                   5150:             if ($file_name !~ m-^\Q$group\E/-) {
                   5151:                 next;
                   5152:             }
                   5153:         }
1.577     banghart 5154:         if (ref($value) eq "ARRAY"){
                   5155:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5156:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5157:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5158:                         if ($lock_descriptor eq 'graded') {
                   5159:                             $readonly_files{$file_name} = 'graded';
                   5160:                         } elsif ($lock_descriptor eq 'handback') {
                   5161:                             $readonly_files{$file_name} = 'handback';
                   5162:                         } else {
                   5163:                             if (!exists($readonly_files{$file_name})) {
                   5164:                                 $readonly_files{$file_name} = 'locked';
                   5165:                             }
                   5166:                         }
1.745     raeburn  5167:                     }
1.750     banghart 5168:                 } 
1.577     banghart 5169:             }
                   5170:         } 
                   5171:     }
                   5172:     return %readonly_files;
                   5173: }
1.559     banghart 5174: # ------------------------------------------------------------ Unmark as Read Only
                   5175: 
                   5176: sub unmark_as_readonly {
1.629     banghart 5177:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5178:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5179:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5180:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5181:     my $symb_crs = $what;
                   5182:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5183:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5184:     my ($tmp)=keys(%current_permissions);
                   5185:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5186:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5187:     foreach my $file (@readonly_files) {
1.759     albertel 5188: 	my $clean_file = &declutter_portfile($file);
                   5189: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5190: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5191:         my @new_locks;
                   5192:         my @del_keys;
                   5193:         if (ref($current_locks) eq "ARRAY"){
                   5194:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5195:                 my $compare=$locker;
1.749     raeburn  5196:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5197:                     $compare=join('',@{$locker});
1.746     raeburn  5198:                     if ($compare ne $symb_crs) {
                   5199:                         push(@new_locks, $locker);
                   5200:                     }
1.563     banghart 5201:                 }
                   5202:             }
1.650     albertel 5203:             if (scalar(@new_locks) > 0) {
1.563     banghart 5204:                 $current_permissions{$file} = \@new_locks;
                   5205:             } else {
                   5206:                 push(@del_keys, $file);
1.613     albertel 5207:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5208:                 delete($current_permissions{$file});
1.563     banghart 5209:             }
                   5210:         }
1.561     banghart 5211:     }
1.613     albertel 5212:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5213:     return;
                   5214: }
1.512     banghart 5215: 
1.17      www      5216: # ------------------------------------------------------------ Directory lister
                   5217: 
                   5218: sub dirlist {
1.253     stredwic 5219:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5220: 
1.18      www      5221:     $uri=~s/^\///;
                   5222:     $uri=~s/\/$//;
1.253     stredwic 5223:     my ($udom, $uname);
                   5224:     (undef,$udom,$uname)=split(/\//,$uri);
                   5225:     if(defined($userdomain)) {
                   5226:         $udom = $userdomain;
                   5227:     }
                   5228:     if(defined($username)) {
                   5229:         $uname = $username;
                   5230:     }
                   5231: 
                   5232:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5233:     if(defined($alternateDirectoryRoot)) {
                   5234:         $dirRoot = $alternateDirectoryRoot;
                   5235:         $dirRoot =~ s/\/$//;
1.751     banghart 5236:     }
1.253     stredwic 5237: 
                   5238:     if($udom) {
                   5239:         if($uname) {
1.605     matthew  5240:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5241:                               homeserver($uname,$udom));
1.605     matthew  5242:             my @listing_results;
                   5243:             if ($listing eq 'unknown_cmd') {
                   5244:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5245:                                homeserver($uname,$udom));
                   5246:                 @listing_results = split(/:/,$listing);
                   5247:             } else {
                   5248:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5249:             }
                   5250:             return @listing_results;
1.253     stredwic 5251:         } elsif(!defined($alternateDirectoryRoot)) {
                   5252:             my $tryserver;
                   5253:             my %allusers=();
                   5254:             foreach $tryserver (keys %libserv) {
                   5255:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5256:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5257:                                       $udom, $tryserver);
1.605     matthew  5258:                     my @listing_results;
                   5259:                     if ($listing eq 'unknown_cmd') {
                   5260:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5261:                                        $udom, $tryserver);
                   5262:                         @listing_results = split(/:/,$listing);
                   5263:                     } else {
                   5264:                         @listing_results =
                   5265:                             map { &unescape($_); } split(/:/,$listing);
                   5266:                     }
                   5267:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5268:                         $listing_results[0] ne 'empty'       &&
                   5269:                         $listing_results[0] ne 'con_lost') {
                   5270:                         foreach (@listing_results) {
1.253     stredwic 5271:                             my ($entry,@stat)=split(/&/,$_);
                   5272:                             $allusers{$entry}=1;
                   5273:                         }
                   5274:                     }
1.191     harris41 5275:                 }
1.253     stredwic 5276:             }
                   5277:             my $alluserstr='';
                   5278:             foreach (sort keys %allusers) {
                   5279:                 $alluserstr.=$_.'&user:';
                   5280:             }
                   5281:             $alluserstr=~s/:$//;
                   5282:             return split(/:/,$alluserstr);
                   5283:         } else {
                   5284:             my @emptyResults = ();
                   5285:             push(@emptyResults, 'missing user name');
                   5286:             return split(':',@emptyResults);
                   5287:         }
                   5288:     } elsif(!defined($alternateDirectoryRoot)) {
                   5289:         my $tryserver;
                   5290:         my %alldom=();
                   5291:         foreach $tryserver (keys %libserv) {
                   5292:             $alldom{$hostdom{$tryserver}}=1;
                   5293:         }
                   5294:         my $alldomstr='';
                   5295:         foreach (sort keys %alldom) {
1.397     albertel 5296:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5297:         }
                   5298:         $alldomstr=~s/:$//;
                   5299:         return split(/:/,$alldomstr);       
                   5300:     } else {
                   5301:         my @emptyResults = ();
                   5302:         push(@emptyResults, 'missing domain');
                   5303:         return split(':',@emptyResults);
1.275     stredwic 5304:     }
                   5305: }
                   5306: 
                   5307: # --------------------------------------------- GetFileTimestamp
                   5308: # This function utilizes dirlist and returns the date stamp for
                   5309: # when it was last modified.  It will also return an error of -1
                   5310: # if an error occurs
                   5311: 
1.410     matthew  5312: ##
                   5313: ## FIXME: This subroutine assumes its caller knows something about the
                   5314: ## directory structure of the home server for the student ($root).
                   5315: ## Not a good assumption to make.  Since this is for looking up files
                   5316: ## in user directories, the full path should be constructed by lond, not
                   5317: ## whatever machine we request data from.
                   5318: ##
1.275     stredwic 5319: sub GetFileTimestamp {
                   5320:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5321:     $studentDomain=~s/\W//g;
                   5322:     $studentName=~s/\W//g;
                   5323:     my $subdir=$studentName.'__';
                   5324:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5325:     my $proname="$studentDomain/$subdir/$studentName";
                   5326:     $proname .= '/'.$filename;
1.375     matthew  5327:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5328:                                               $studentName, $root);
1.275     stredwic 5329:     my @stats = split('&', $fileStat);
                   5330:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5331:         # @stats contains first the filename, then the stat output
                   5332:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5333:     } else {
                   5334:         return -1;
1.253     stredwic 5335:     }
1.26      www      5336: }
                   5337: 
1.712     albertel 5338: sub stat_file {
                   5339:     my ($uri) = @_;
1.787     albertel 5340:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5341: 
1.712     albertel 5342:     my ($udom,$uname,$file,$dir);
                   5343:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5344: 	($udom,$uname,$file) =
                   5345: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5346: 	$file = 'userfiles/'.$file;
1.740     www      5347: 	$dir = &propath($udom,$uname);
1.712     albertel 5348:     }
                   5349:     if ($uri =~ m-^/res/-) {
                   5350: 	($udom,$uname) = 
                   5351: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5352: 	$file = $uri;
                   5353:     }
                   5354: 
                   5355:     if (!$udom || !$uname || !$file) {
                   5356: 	# unable to handle the uri
                   5357: 	return ();
                   5358:     }
                   5359: 
                   5360:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5361:     my @stats = split('&', $result);
1.721     banghart 5362:     
1.712     albertel 5363:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5364: 	shift(@stats); #filename is first
                   5365: 	return @stats;
                   5366:     }
                   5367:     return ();
                   5368: }
                   5369: 
1.26      www      5370: # -------------------------------------------------------- Value of a Condition
                   5371: 
1.713     albertel 5372: # gets the value of a specific preevaluated condition
                   5373: #    stored in the string  $env{user.state.<cid>}
                   5374: # or looks up a condition reference in the bighash and if if hasn't
                   5375: # already been evaluated recurses into docondval to get the value of
                   5376: # the condition, then memoizing it to 
                   5377: #   $env{user.state.<cid>.<condition>}
1.40      www      5378: sub directcondval {
                   5379:     my $number=shift;
1.620     albertel 5380:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5381: 	&Apache::lonuserstate::evalstate();
                   5382:     }
1.713     albertel 5383:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5384: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5385:     } elsif ($number =~ /^_/) {
                   5386: 	my $sub_condition;
                   5387: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5388: 		&GDBM_READER(),0640)) {
                   5389: 	    $sub_condition=$bighash{'conditions'.$number};
                   5390: 	    untie(%bighash);
                   5391: 	}
                   5392: 	my $value = &docondval($sub_condition);
                   5393: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5394: 	return $value;
                   5395:     }
1.620     albertel 5396:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5397:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5398:     } else {
                   5399:        return 2;
                   5400:     }
                   5401: }
                   5402: 
1.713     albertel 5403: # get the collection of conditions for this resource
1.26      www      5404: sub condval {
                   5405:     my $condidx=shift;
1.54      www      5406:     my $allpathcond='';
1.713     albertel 5407:     foreach my $cond (split(/\|/,$condidx)) {
                   5408: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5409: 	    $allpathcond.=
                   5410: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5411: 	}
1.191     harris41 5412:     }
1.54      www      5413:     $allpathcond=~s/\|$//;
1.713     albertel 5414:     return &docondval($allpathcond);
                   5415: }
                   5416: 
                   5417: #evaluates an expression of conditions
                   5418: sub docondval {
                   5419:     my ($allpathcond) = @_;
                   5420:     my $result=0;
                   5421:     if ($env{'request.course.id'}
                   5422: 	&& defined($allpathcond)) {
                   5423: 	my $operand='|';
                   5424: 	my @stack;
                   5425: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5426: 	    if ($chunk eq '(') {
                   5427: 		push @stack,($operand,$result);
                   5428: 	    } elsif ($chunk eq ')') {
                   5429: 		my $before=pop @stack;
                   5430: 		if (pop @stack eq '&') {
                   5431: 		    $result=$result>$before?$before:$result;
                   5432: 		} else {
                   5433: 		    $result=$result>$before?$result:$before;
                   5434: 		}
                   5435: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5436: 		$operand=$chunk;
                   5437: 	    } else {
                   5438: 		my $new=directcondval($chunk);
                   5439: 		if ($operand eq '&') {
                   5440: 		    $result=$result>$new?$new:$result;
                   5441: 		} else {
                   5442: 		    $result=$result>$new?$result:$new;
                   5443: 		}
                   5444: 	    }
                   5445: 	}
1.26      www      5446:     }
                   5447:     return $result;
1.421     albertel 5448: }
                   5449: 
                   5450: # ---------------------------------------------------- Devalidate courseresdata
                   5451: 
                   5452: sub devalidatecourseresdata {
                   5453:     my ($coursenum,$coursedomain)=@_;
                   5454:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5455:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5456: }
                   5457: 
1.763     www      5458: 
1.200     www      5459: # --------------------------------------------------- Course Resourcedata Query
                   5460: 
1.624     albertel 5461: sub get_courseresdata {
                   5462:     my ($coursenum,$coursedomain)=@_;
1.200     www      5463:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5464:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5465:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5466:     my %dumpreply;
1.417     albertel 5467:     unless (defined($cached)) {
1.624     albertel 5468: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5469: 	$result=\%dumpreply;
1.251     albertel 5470: 	my ($tmp) = keys(%dumpreply);
                   5471: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5472: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5473: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5474: 	    return $tmp;
1.416     albertel 5475: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5476: 	    $result=undef;
1.599     albertel 5477: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5478: 	}
                   5479:     }
1.624     albertel 5480:     return $result;
                   5481: }
                   5482: 
1.633     albertel 5483: sub devalidateuserresdata {
                   5484:     my ($uname,$udom)=@_;
                   5485:     my $hashid="$udom:$uname";
                   5486:     &devalidate_cache_new('userres',$hashid);
                   5487: }
                   5488: 
1.624     albertel 5489: sub get_userresdata {
                   5490:     my ($uname,$udom)=@_;
                   5491:     #most student don\'t have any data set, check if there is some data
                   5492:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5493: 
                   5494:     my $hashid="$udom:$uname";
                   5495:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5496:     if (!defined($cached)) {
                   5497: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5498: 	$result=\%resourcedata;
                   5499: 	&do_cache_new('userres',$hashid,$result,600);
                   5500:     }
                   5501:     my ($tmp)=keys(%$result);
                   5502:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5503: 	return $result;
                   5504:     }
                   5505:     #error 2 occurs when the .db doesn't exist
                   5506:     if ($tmp!~/error: 2 /) {
1.672     albertel 5507: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5508: 		 " Trying to get resource data for ".
                   5509: 		 $uname." at ".$udom.": ".
                   5510: 		 $tmp."</font>");
                   5511:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5512: 	#&EXT_cache_set($udom,$uname);
                   5513: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5514: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5515:     }
                   5516:     return $tmp;
                   5517: }
                   5518: 
                   5519: sub resdata {
                   5520:     my ($name,$domain,$type,@which)=@_;
                   5521:     my $result;
                   5522:     if ($type eq 'course') {
                   5523: 	$result=&get_courseresdata($name,$domain);
                   5524:     } elsif ($type eq 'user') {
                   5525: 	$result=&get_userresdata($name,$domain);
                   5526:     }
                   5527:     if (!ref($result)) { return $result; }    
1.251     albertel 5528:     foreach my $item (@which) {
1.417     albertel 5529: 	if (defined($result->{$item})) {
                   5530: 	    return $result->{$item};
1.251     albertel 5531: 	}
1.250     albertel 5532:     }
1.291     albertel 5533:     return undef;
1.200     www      5534: }
                   5535: 
1.379     matthew  5536: #
                   5537: # EXT resource caching routines
                   5538: #
                   5539: 
                   5540: sub clear_EXT_cache_status {
1.383     albertel 5541:     &delenv('cache.EXT.');
1.379     matthew  5542: }
                   5543: 
                   5544: sub EXT_cache_status {
                   5545:     my ($target_domain,$target_user) = @_;
1.383     albertel 5546:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5547:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5548:         # We know already the user has no data
                   5549:         return 1;
                   5550:     } else {
                   5551:         return 0;
                   5552:     }
                   5553: }
                   5554: 
                   5555: sub EXT_cache_set {
                   5556:     my ($target_domain,$target_user) = @_;
1.383     albertel 5557:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5558:     #&appenv($cachename => time);
1.379     matthew  5559: }
                   5560: 
1.28      www      5561: # --------------------------------------------------------- Value of a Variable
1.58      www      5562: sub EXT {
1.715     albertel 5563: 
1.395     albertel 5564:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5565:     unless ($varname) { return ''; }
1.218     albertel 5566:     #get real user name/domain, courseid and symb
                   5567:     my $courseid;
1.359     albertel 5568:     my $publicuser;
1.427     www      5569:     if ($symbparm) {
                   5570: 	$symbparm=&get_symb_from_alias($symbparm);
                   5571:     }
1.218     albertel 5572:     if (!($uname && $udom)) {
1.790     albertel 5573:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5574:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5575:     } else {
1.620     albertel 5576: 	$courseid=$env{'request.course.id'};
1.218     albertel 5577:     }
1.48      www      5578:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5579:     my $rest;
1.320     albertel 5580:     if (defined($therest[0])) {
1.48      www      5581:        $rest=join('.',@therest);
                   5582:     } else {
                   5583:        $rest='';
                   5584:     }
1.320     albertel 5585: 
1.57      www      5586:     my $qualifierrest=$qualifier;
                   5587:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5588:     my $spacequalifierrest=$space;
                   5589:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5590:     if ($realm eq 'user') {
1.48      www      5591: # --------------------------------------------------------------- user.resource
                   5592: 	if ($space eq 'resource') {
1.651     albertel 5593: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5594: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5595: 		 &&
1.744     albertel 5596: 		 ($symbparm eq &symbread()) ) {	
                   5597: 		# if we are in the middle of processing the resource the
                   5598: 		# get the value we are planning on committing
                   5599:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5600:                     return $Apache::lonhomework::results{$qualifierrest};
                   5601:                 } else {
                   5602:                     return $Apache::lonhomework::history{$qualifierrest};
                   5603:                 }
1.335     albertel 5604: 	    } else {
1.359     albertel 5605: 		my %restored;
1.620     albertel 5606: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5607: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5608: 		} else {
                   5609: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5610: 		}
1.335     albertel 5611: 		return $restored{$qualifierrest};
                   5612: 	    }
1.48      www      5613: # ----------------------------------------------------------------- user.access
                   5614:         } elsif ($space eq 'access') {
1.218     albertel 5615: 	    # FIXME - not supporting calls for a specific user
1.48      www      5616:             return &allowed($qualifier,$rest);
                   5617: # ------------------------------------------ user.preferences, user.environment
                   5618:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5619: 	    if (($uname eq $env{'user.name'}) &&
                   5620: 		($udom eq $env{'user.domain'})) {
                   5621: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5622: 	    } else {
1.359     albertel 5623: 		my %returnhash;
                   5624: 		if (!$publicuser) {
                   5625: 		    %returnhash=&userenvironment($udom,$uname,
                   5626: 						 $qualifierrest);
                   5627: 		}
1.218     albertel 5628: 		return $returnhash{$qualifierrest};
                   5629: 	    }
1.48      www      5630: # ----------------------------------------------------------------- user.course
                   5631:         } elsif ($space eq 'course') {
1.218     albertel 5632: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5633:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5634: # ------------------------------------------------------------------- user.role
                   5635:         } elsif ($space eq 'role') {
1.218     albertel 5636: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5637:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5638:             if ($qualifier eq 'value') {
                   5639: 		return $role;
                   5640:             } elsif ($qualifier eq 'extent') {
                   5641:                 return $where;
                   5642:             }
                   5643: # ----------------------------------------------------------------- user.domain
                   5644:         } elsif ($space eq 'domain') {
1.218     albertel 5645:             return $udom;
1.48      www      5646: # ------------------------------------------------------------------- user.name
                   5647:         } elsif ($space eq 'name') {
1.218     albertel 5648:             return $uname;
1.48      www      5649: # ---------------------------------------------------- Any other user namespace
1.29      www      5650:         } else {
1.359     albertel 5651: 	    my %reply;
                   5652: 	    if (!$publicuser) {
                   5653: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5654: 	    }
                   5655: 	    return $reply{$qualifierrest};
1.48      www      5656:         }
1.236     www      5657:     } elsif ($realm eq 'query') {
                   5658: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5659:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5660: 						[$spacequalifierrest]);
1.620     albertel 5661: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5662:    } elsif ($realm eq 'request') {
1.48      www      5663: # ------------------------------------------------------------- request.browser
                   5664:         if ($space eq 'browser') {
1.430     www      5665: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5666: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5667: 		    return 1;
                   5668: 		} else {
                   5669: 		    return 0;
                   5670: 		}
                   5671: 	    } else {
1.620     albertel 5672: 		return $env{'browser.'.$qualifier};
1.430     www      5673: 	    }
1.57      www      5674: # ------------------------------------------------------------ request.filename
                   5675:         } else {
1.620     albertel 5676:             return $env{'request.'.$spacequalifierrest};
1.29      www      5677:         }
1.28      www      5678:     } elsif ($realm eq 'course') {
1.48      www      5679: # ---------------------------------------------------------- course.description
1.620     albertel 5680:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5681:     } elsif ($realm eq 'resource') {
1.165     www      5682: 
1.620     albertel 5683: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5684: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5685: 	}
1.693     albertel 5686: 
                   5687: 	if ($space eq 'title') {
                   5688: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5689: 	    return &gettitle($symbparm);
                   5690: 	}
                   5691: 	
                   5692: 	if ($space eq 'map') {
                   5693: 	    my ($map) = &decode_symb($symbparm);
                   5694: 	    return &symbread($map);
                   5695: 	}
                   5696: 
                   5697: 	my ($section, $group, @groups);
1.593     albertel 5698: 	my ($courselevelm,$courselevel);
1.539     albertel 5699: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5700: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5701: 
1.218     albertel 5702: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5703: 
1.60      www      5704: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5705: 	    my $symbp=$symbparm;
1.735     albertel 5706: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5707: 
                   5708: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5709: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5710: 
1.620     albertel 5711: 	    if (($env{'user.name'} eq $uname) &&
                   5712: 		($env{'user.domain'} eq $udom)) {
                   5713: 		$section=$env{'request.course.sec'};
1.733     raeburn  5714:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5715:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5716: 	    } else {
1.539     albertel 5717: 		if (! defined($usection)) {
1.551     albertel 5718: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5719: 		} else {
                   5720: 		    $section = $usection;
                   5721: 		}
1.733     raeburn  5722:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5723: 	    }
                   5724: 
                   5725: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5726: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5727: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5728: 
1.593     albertel 5729: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5730: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5731: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5732: 
1.60      www      5733: # ----------------------------------------------------------- first, check user
1.624     albertel 5734: 
                   5735: 	    my $userreply=&resdata($uname,$udom,'user',
                   5736: 				       ($courselevelr,$courselevelm,
                   5737: 					$courselevel));
                   5738: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5739: 
1.594     albertel 5740: # ------------------------------------------------ second, check some of course
1.684     raeburn  5741:             my $coursereply;
1.691     raeburn  5742:             if (@groups > 0) {
                   5743:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5744:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5745:                 if (defined($coursereply)) { return $coursereply; }
                   5746:             }
1.96      www      5747: 
1.684     raeburn  5748: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5749: 				     $env{'course.'.$courseid.'.domain'},
                   5750: 				     'course',
                   5751: 				     ($seclevelr,$seclevelm,$seclevel,
                   5752: 				      $courselevelr));
1.287     albertel 5753: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5754: 
1.60      www      5755: # ------------------------------------------------------ third, check map parms
1.218     albertel 5756: 	    my %parmhash=();
                   5757: 	    my $thisparm='';
                   5758: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5759: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5760: 		    &GDBM_READER(),0640)) {
1.218     albertel 5761: 		$thisparm=$parmhash{$symbparm};
                   5762: 		untie(%parmhash);
                   5763: 	    }
                   5764: 	    if ($thisparm) { return $thisparm; }
                   5765: 	}
1.594     albertel 5766: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5767: 
1.218     albertel 5768: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5769: 	my $filename;
                   5770: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5771: 	if ($symbparm) {
1.409     www      5772: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5773: 	} else {
1.620     albertel 5774: 	    $filename=$env{'request.filename'};
1.282     albertel 5775: 	}
                   5776: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5777: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5778: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5779: 	if (defined($metadata)) { return $metadata; }
1.142     www      5780: 
1.594     albertel 5781: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5782: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5783: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5784: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5785: 				     $env{'course.'.$courseid.'.domain'},
                   5786: 				     'course',
                   5787: 				     ($courselevelm,$courselevel));
1.593     albertel 5788: 	    if (defined($coursereply)) { return $coursereply; }
                   5789: 	}
1.145     www      5790: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5791: 	unless ($space eq '0') {
1.336     albertel 5792: 	    my @parts=split(/_/,$space);
                   5793: 	    my $id=pop(@parts);
                   5794: 	    my $part=join('_',@parts);
                   5795: 	    if ($part eq '') { $part='0'; }
                   5796: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5797: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5798: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5799: 	}
1.395     albertel 5800: 	if ($recurse) { return undef; }
                   5801: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5802: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5803: 
1.48      www      5804: # ---------------------------------------------------- Any other user namespace
                   5805:     } elsif ($realm eq 'environment') {
                   5806: # ----------------------------------------------------------------- environment
1.620     albertel 5807: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5808: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5809: 	} else {
1.770     albertel 5810: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5811: 		return '';
                   5812: 	    }
1.219     albertel 5813: 	    my %returnhash=&userenvironment($udom,$uname,
                   5814: 					    $spacequalifierrest);
                   5815: 	    return $returnhash{$spacequalifierrest};
                   5816: 	}
1.28      www      5817:     } elsif ($realm eq 'system') {
1.48      www      5818: # ----------------------------------------------------------------- system.time
                   5819: 	if ($space eq 'time') {
                   5820: 	    return time;
                   5821:         }
1.696     albertel 5822:     } elsif ($realm eq 'server') {
                   5823: # ----------------------------------------------------------------- system.time
                   5824: 	if ($space eq 'name') {
                   5825: 	    return $ENV{'SERVER_NAME'};
                   5826:         }
1.28      www      5827:     }
1.48      www      5828:     return '';
1.61      www      5829: }
                   5830: 
1.691     raeburn  5831: sub check_group_parms {
                   5832:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5833:     my @groupitems = ();
                   5834:     my $resultitem;
                   5835:     my @levels = ($symbparm,$mapparm,$what);
                   5836:     foreach my $group (@{$groups}) {
                   5837:         foreach my $level (@levels) {
                   5838:              my $item = $courseid.'.['.$group.'].'.$level;
                   5839:              push(@groupitems,$item);
                   5840:         }
                   5841:     }
                   5842:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5843:                             $env{'course.'.$courseid.'.domain'},
                   5844:                                      'course',@groupitems);
                   5845:     return $coursereply;
                   5846: }
                   5847: 
                   5848: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5849:     my ($courseid,@groups) = @_;
                   5850:     @groups = sort(@groups);
1.691     raeburn  5851:     return @groups;
                   5852: }
                   5853: 
1.395     albertel 5854: sub packages_tab_default {
                   5855:     my ($uri,$varname)=@_;
                   5856:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5857: 
                   5858:     my (@extension,@specifics,$do_default);
                   5859:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5860: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5861: 	if ($pack_type eq 'default') {
                   5862: 	    $do_default=1;
                   5863: 	} elsif ($pack_type eq 'extension') {
                   5864: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5865: 	} else {
                   5866: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5867: 	}
                   5868:     }
                   5869:     # first look for a package that matches the requested part id
                   5870:     foreach my $package (@specifics) {
                   5871: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5872: 	next if ($pack_part ne $part);
                   5873: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5874: 	    return $packagetab{"$pack_type&$name&default"};
                   5875: 	}
                   5876:     }
                   5877:     # look for any possible matching non extension_ package
                   5878:     foreach my $package (@specifics) {
                   5879: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5880: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5881: 	    return $packagetab{"$pack_type&$name&default"};
                   5882: 	}
1.585     albertel 5883: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5884: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5885: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5886: 	}
                   5887:     }
1.738     albertel 5888:     # look for any posible extension_ match
                   5889:     foreach my $package (@extension) {
                   5890: 	my ($package,$pack_type)=@{$package};
                   5891: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5892: 	    return $packagetab{"$pack_type&$name&default"};
                   5893: 	}
                   5894: 	if (defined($packagetab{$package."&$name&default"})) {
                   5895: 	    return $packagetab{$package."&$name&default"};
                   5896: 	}
                   5897:     }
                   5898:     # look for a global default setting
                   5899:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5900: 	return $packagetab{"default&$name&default"};
                   5901:     }
1.395     albertel 5902:     return undef;
                   5903: }
                   5904: 
1.334     albertel 5905: sub add_prefix_and_part {
                   5906:     my ($prefix,$part)=@_;
                   5907:     my $keyroot;
                   5908:     if (defined($prefix) && $prefix !~ /^__/) {
                   5909: 	# prefix that has a part already
                   5910: 	$keyroot=$prefix;
                   5911:     } elsif (defined($prefix)) {
                   5912: 	# prefix that is missing a part
                   5913: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5914:     } else {
                   5915: 	# no prefix at all
                   5916: 	if (defined($part)) { $keyroot='_'.$part; }
                   5917:     }
                   5918:     return $keyroot;
                   5919: }
                   5920: 
1.71      www      5921: # ---------------------------------------------------------------- Get metadata
                   5922: 
1.599     albertel 5923: my %metaentry;
1.71      www      5924: sub metadata {
1.176     www      5925:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5926:     $uri=&declutter($uri);
1.288     albertel 5927:     # if it is a non metadata possible uri return quickly
1.529     albertel 5928:     if (($uri eq '') || 
                   5929: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5930: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5931:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5932: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5933: 	return undef;
1.288     albertel 5934:     }
1.73      www      5935:     my $filename=$uri;
                   5936:     $uri=~s/\.meta$//;
1.172     www      5937: #
                   5938: # Is the metadata already cached?
1.177     www      5939: # Look at timestamp of caching
1.172     www      5940: # Everything is cached by the main uri, libraries are never directly cached
                   5941: #
1.428     albertel 5942:     if (!defined($liburi)) {
1.599     albertel 5943: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5944: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5945:     }
                   5946:     {
1.172     www      5947: #
                   5948: # Is this a recursive call for a library?
                   5949: #
1.599     albertel 5950: #	if (! exists($metacache{$uri})) {
                   5951: #	    $metacache{$uri}={};
                   5952: #	}
1.171     www      5953:         if ($liburi) {
                   5954: 	    $liburi=&declutter($liburi);
                   5955:             $filename=$liburi;
1.401     bowersj2 5956:         } else {
1.599     albertel 5957: 	    &devalidate_cache_new('meta',$uri);
                   5958: 	    undef(%metaentry);
1.401     bowersj2 5959: 	}
1.140     www      5960:         my %metathesekeys=();
1.73      www      5961:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5962: 	my $metastring;
1.768     albertel 5963: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5964: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5965: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5966: 	    $metastring=&getfile($file);
1.489     albertel 5967: 	}
1.208     albertel 5968:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5969:         my $token;
1.140     www      5970:         undef %metathesekeys;
1.71      www      5971:         while ($token=$parser->get_token) {
1.339     albertel 5972: 	    if ($token->[0] eq 'S') {
                   5973: 		if (defined($token->[2]->{'package'})) {
1.172     www      5974: #
                   5975: # This is a package - get package info
                   5976: #
1.339     albertel 5977: 		    my $package=$token->[2]->{'package'};
                   5978: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5979: 		    if (defined($token->[2]->{'id'})) { 
                   5980: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5981: 		    }
1.599     albertel 5982: 		    if ($metaentry{':packages'}) {
                   5983: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5984: 		    } else {
1.599     albertel 5985: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5986: 		    }
1.736     albertel 5987: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5988: 			my $part=$keyroot;
                   5989: 			$part=~s/^\_//;
1.736     albertel 5990: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5991: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5992: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5993: 			    # ignore package.tab specified default values
                   5994:                             # here &package_tab_default() will fetch those
                   5995: 			    if ($subp eq 'default') { next; }
1.736     albertel 5996: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5997: 			    my $unikey;
                   5998: 			    if ($pack =~ /_0$/) {
                   5999: 				$unikey='parameter_0_'.$name;
                   6000: 				$part=0;
                   6001: 			    } else {
                   6002: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6003: 			    }
1.339     albertel 6004: 			    if ($subp eq 'display') {
                   6005: 				$value.=' [Part: '.$part.']';
                   6006: 			    }
1.599     albertel 6007: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6008: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6009: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6010: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6011: 			    }
1.599     albertel 6012: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6013: 				$metaentry{':'.$unikey}=
                   6014: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6015: 			    }
1.339     albertel 6016: 			}
                   6017: 		    }
                   6018: 		} else {
1.172     www      6019: #
                   6020: # This is not a package - some other kind of start tag
1.339     albertel 6021: #
                   6022: 		    my $entry=$token->[1];
                   6023: 		    my $unikey;
                   6024: 		    if ($entry eq 'import') {
                   6025: 			$unikey='';
                   6026: 		    } else {
                   6027: 			$unikey=$entry;
                   6028: 		    }
                   6029: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6030: 
                   6031: 		    if (defined($token->[2]->{'id'})) { 
                   6032: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6033: 		    }
1.175     www      6034: 
1.339     albertel 6035: 		    if ($entry eq 'import') {
1.175     www      6036: #
                   6037: # Importing a library here
1.339     albertel 6038: #
                   6039: 			if ($depthcount<20) {
                   6040: 			    my $location=$parser->get_text('/import');
                   6041: 			    my $dir=$filename;
                   6042: 			    $dir=~s|[^/]*$||;
                   6043: 			    $location=&filelocation($dir,$location);
1.736     albertel 6044: 			    my $metadata = 
                   6045: 				&metadata($uri,'keys', $location,$unikey,
                   6046: 					  $depthcount+1);
                   6047: 			    foreach my $meta (split(',',$metadata)) {
                   6048: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6049: 				$metathesekeys{$meta}=1;
1.339     albertel 6050: 			    }
                   6051: 			}
                   6052: 		    } else { 
                   6053: 			
                   6054: 			if (defined($token->[2]->{'name'})) { 
                   6055: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6056: 			}
                   6057: 			$metathesekeys{$unikey}=1;
1.736     albertel 6058: 			foreach my $param (@{$token->[3]}) {
                   6059: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6060: 				$token->[2]->{$param};
1.339     albertel 6061: 			}
                   6062: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6063: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6064: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6065: 		 # only ws inside the tag, and not in default, so use default
                   6066: 		 # as value
1.599     albertel 6067: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6068: 			} else {
1.321     albertel 6069: 		  # either something interesting inside the tag or default
                   6070:                   # uninteresting
1.599     albertel 6071: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6072: 			}
1.172     www      6073: # end of not-a-package not-a-library import
1.339     albertel 6074: 		    }
1.172     www      6075: # end of not-a-package start tag
1.339     albertel 6076: 		}
1.172     www      6077: # the next is the end of "start tag"
1.339     albertel 6078: 	    }
                   6079: 	}
1.483     albertel 6080: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6081: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6082: 	    #no specific packages #how's our extension
                   6083: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6084: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6085: 					 \%metathesekeys);
                   6086: 	}
1.599     albertel 6087: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6088: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6089: 		#no specific packages well let's get default then
                   6090: 		if ($key!~/^default&/) { next; }
1.488     albertel 6091: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6092: 					     \%metathesekeys);
                   6093: 	    }
                   6094: 	}
1.338     www      6095: # are there custom rights to evaluate
1.599     albertel 6096: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6097: 
1.338     www      6098:     #
                   6099:     # Importing a rights file here
1.339     albertel 6100:     #
                   6101: 	    unless ($depthcount) {
1.599     albertel 6102: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6103: 		my $dir=$filename;
                   6104: 		$dir=~s|[^/]*$||;
                   6105: 		$location=&filelocation($dir,$location);
1.736     albertel 6106: 		my $rights_metadata =
                   6107: 		    &metadata($uri,'keys',$location,'_rights',
                   6108: 			      $depthcount+1);
                   6109: 		foreach my $rights (split(',',$rights_metadata)) {
                   6110: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6111: 		    $metathesekeys{$rights}=1;
1.339     albertel 6112: 		}
                   6113: 	    }
                   6114: 	}
1.737     albertel 6115: 	# uniqifiy package listing
                   6116: 	my %seen;
                   6117: 	my @uniq_packages =
                   6118: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6119: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6120: 
                   6121: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6122: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6123: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6124: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6125: # this is the end of "was not already recently cached
1.71      www      6126:     }
1.599     albertel 6127:     return $metaentry{':'.$what};
1.261     albertel 6128: }
                   6129: 
1.488     albertel 6130: sub metadata_create_package_def {
1.483     albertel 6131:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6132:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6133:     if ($subp eq 'default') { next; }
                   6134:     
1.599     albertel 6135:     if (defined($metaentry{':packages'})) {
                   6136: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6137:     } else {
1.599     albertel 6138: 	$metaentry{':packages'}=$package;
1.483     albertel 6139:     }
                   6140:     my $value=$packagetab{$key};
                   6141:     my $unikey;
                   6142:     $unikey='parameter_0_'.$name;
1.599     albertel 6143:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6144:     $$metathesekeys{$unikey}=1;
1.599     albertel 6145:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6146: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6147:     }
1.599     albertel 6148:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6149: 	$metaentry{':'.$unikey}=
                   6150: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6151:     }
                   6152: }
                   6153: 
1.261     albertel 6154: sub metadata_generate_part0 {
                   6155:     my ($metadata,$metacache,$uri) = @_;
                   6156:     my %allnames;
1.737     albertel 6157:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6158: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6159: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6160: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6161: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6162: 	    $allnames{$name}=$part;
                   6163: 	  }
                   6164: 	}
                   6165:     }
                   6166:     foreach my $name (keys(%allnames)) {
                   6167:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6168:       my $key=":parameter_0_$name";
1.261     albertel 6169:       $$metacache{"$key.part"}='0';
                   6170:       $$metacache{"$key.name"}=$name;
1.428     albertel 6171:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6172: 					   $allnames{$name}.'_'.$name.
                   6173: 					   '.type'};
1.428     albertel 6174:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6175: 			     '.display'};
1.644     www      6176:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6177:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6178:       $$metacache{"$key.display"}=$olddis;
                   6179:     }
1.71      www      6180: }
                   6181: 
1.764     albertel 6182: # ------------------------------------------------------ Devalidate title cache
                   6183: 
                   6184: sub devalidate_title_cache {
                   6185:     my ($url)=@_;
                   6186:     if (!$env{'request.course.id'}) { return; }
                   6187:     my $symb=&symbread($url);
                   6188:     if (!$symb) { return; }
                   6189:     my $key=$env{'request.course.id'}."\0".$symb;
                   6190:     &devalidate_cache_new('title',$key);
                   6191: }
                   6192: 
1.301     www      6193: # ------------------------------------------------- Get the title of a resource
                   6194: 
                   6195: sub gettitle {
                   6196:     my $urlsymb=shift;
                   6197:     my $symb=&symbread($urlsymb);
1.534     albertel 6198:     if ($symb) {
1.620     albertel 6199: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6200: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6201: 	if (defined($cached)) { 
                   6202: 	    return $result;
                   6203: 	}
1.534     albertel 6204: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6205: 	my $title='';
                   6206: 	my %bighash;
1.620     albertel 6207: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6208: 		&GDBM_READER(),0640)) {
                   6209: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6210: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6211: 	    untie %bighash;
                   6212: 	}
                   6213: 	$title=~s/\&colon\;/\:/gs;
                   6214: 	if ($title) {
1.599     albertel 6215: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6216: 	}
                   6217: 	$urlsymb=$url;
                   6218:     }
                   6219:     my $title=&metadata($urlsymb,'title');
                   6220:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6221:     return $title;
1.301     www      6222: }
1.613     albertel 6223: 
1.614     albertel 6224: sub get_slot {
                   6225:     my ($which,$cnum,$cdom)=@_;
                   6226:     if (!$cnum || !$cdom) {
1.790     albertel 6227: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6228: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6229: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6230:     }
1.703     albertel 6231:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6232:     my %slotinfo;
                   6233:     if (exists($remembered{$key})) {
                   6234: 	$slotinfo{$which} = $remembered{$key};
                   6235:     } else {
                   6236: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6237: 	&Apache::lonhomework::showhash(%slotinfo);
                   6238: 	my ($tmp)=keys(%slotinfo);
                   6239: 	if ($tmp=~/^error:/) { return (); }
                   6240: 	$remembered{$key} = $slotinfo{$which};
                   6241:     }
1.616     albertel 6242:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6243: 	return %{$slotinfo{$which}};
                   6244:     }
                   6245:     return $slotinfo{$which};
1.614     albertel 6246: }
1.31      www      6247: # ------------------------------------------------- Update symbolic store links
                   6248: 
                   6249: sub symblist {
                   6250:     my ($mapname,%newhash)=@_;
1.438     www      6251:     $mapname=&deversion(&declutter($mapname));
1.31      www      6252:     my %hash;
1.620     albertel 6253:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6254:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6255:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6256: 	    foreach my $url (keys %newhash) {
                   6257: 		next if ($url eq 'last_known'
                   6258: 			 && $env{'form.no_update_last_known'});
                   6259: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6260: 						    $newhash{$url}->[1],
                   6261: 						    $newhash{$url}->[0]);
1.191     harris41 6262:             }
1.31      www      6263:             if (untie(%hash)) {
                   6264: 		return 'ok';
                   6265:             }
                   6266:         }
                   6267:     }
                   6268:     return 'error';
1.212     www      6269: }
                   6270: 
                   6271: # --------------------------------------------------------------- Verify a symb
                   6272: 
                   6273: sub symbverify {
1.510     www      6274:     my ($symb,$thisurl)=@_;
                   6275:     my $thisfn=$thisurl;
1.439     www      6276:     $thisfn=&declutter($thisfn);
1.215     www      6277: # direct jump to resource in page or to a sequence - will construct own symbs
                   6278:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6279: # check URL part
1.409     www      6280:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6281: 
1.431     www      6282:     unless ($url eq $thisfn) { return 0; }
1.213     www      6283: 
1.216     www      6284:     $symb=&symbclean($symb);
1.510     www      6285:     $thisurl=&deversion($thisurl);
1.439     www      6286:     $thisfn=&deversion($thisfn);
1.213     www      6287: 
                   6288:     my %bighash;
                   6289:     my $okay=0;
1.431     www      6290: 
1.620     albertel 6291:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6292:                             &GDBM_READER(),0640)) {
1.510     www      6293:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6294:         unless ($ids) { 
1.510     www      6295:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6296:         }
                   6297:         if ($ids) {
                   6298: # ------------------------------------------------------------------- Has ID(s)
                   6299: 	    foreach (split(/\,/,$ids)) {
1.644     www      6300: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6301:                if (
                   6302:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6303:    eq $symb) { 
1.620     albertel 6304: 		   if (($env{'request.role.adv'}) ||
                   6305: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6306: 		       $okay=1; 
                   6307: 		   }
                   6308: 	       }
1.216     www      6309: 	   }
                   6310:         }
1.213     www      6311: 	untie(%bighash);
                   6312:     }
                   6313:     return $okay;
1.31      www      6314: }
                   6315: 
1.210     www      6316: # --------------------------------------------------------------- Clean-up symb
                   6317: 
                   6318: sub symbclean {
                   6319:     my $symb=shift;
1.568     albertel 6320:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6321: # remove version from map
                   6322:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6323: 
1.210     www      6324: # remove version from URL
                   6325:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6326: 
1.507     www      6327: # remove wrapper
                   6328: 
1.510     www      6329:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6330:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6331:     return $symb;
1.409     www      6332: }
                   6333: 
                   6334: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6335: 
                   6336: sub encode_symb {
                   6337:     my ($map,$resid,$url)=@_;
                   6338:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6339: }
1.409     www      6340: 
                   6341: sub decode_symb {
1.568     albertel 6342:     my $symb=shift;
                   6343:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6344:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6345:     return (&fixversion($map),$resid,&fixversion($url));
                   6346: }
                   6347: 
                   6348: sub fixversion {
                   6349:     my $fn=shift;
1.609     banghart 6350:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6351:     my %bighash;
                   6352:     my $uri=&clutter($fn);
1.620     albertel 6353:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6354: # is this cached?
1.599     albertel 6355:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6356:     if (defined($cached)) { return $result; }
                   6357: # unfortunately not cached, or expired
1.620     albertel 6358:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6359: 	    &GDBM_READER(),0640)) {
                   6360:  	if ($bighash{'version_'.$uri}) {
                   6361:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6362:  	    unless (($version eq 'mostrecent') || 
                   6363: 		    ($version==&getversion($uri))) {
1.440     www      6364:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6365:  	    }
                   6366:  	}
                   6367:  	untie %bighash;
1.413     www      6368:     }
1.599     albertel 6369:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6370: }
                   6371: 
                   6372: sub deversion {
                   6373:     my $url=shift;
                   6374:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6375:     return $url;
1.210     www      6376: }
                   6377: 
1.31      www      6378: # ------------------------------------------------------ Return symb list entry
                   6379: 
                   6380: sub symbread {
1.249     www      6381:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6382:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6383:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6384: # no filename provided? try from environment
1.44      www      6385:     unless ($thisfn) {
1.620     albertel 6386:         if ($env{'request.symb'}) {
                   6387: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6388: 	}
1.620     albertel 6389: 	$thisfn=$env{'request.filename'};
1.44      www      6390:     }
1.569     albertel 6391:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6392: # is that filename actually a symb? Verify, clean, and return
                   6393:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6394: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6395: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6396: 	}
1.242     www      6397:     }
1.44      www      6398:     $thisfn=declutter($thisfn);
1.31      www      6399:     my %hash;
1.37      www      6400:     my %bighash;
                   6401:     my $syval='';
1.620     albertel 6402:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6403:         my $targetfn = $thisfn;
1.609     banghart 6404:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6405:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6406:         }
1.687     albertel 6407: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6408: 	    $targetfn=$1;
                   6409: 	}
1.620     albertel 6410:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6411:                       &GDBM_READER(),0640)) {
1.481     raeburn  6412: 	    $syval=$hash{$targetfn};
1.37      www      6413:             untie(%hash);
                   6414:         }
                   6415: # ---------------------------------------------------------- There was an entry
                   6416:         if ($syval) {
1.601     albertel 6417: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6418: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6419: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6420: 		    #return $env{$cache_str}='';
1.601     albertel 6421: 		#}    
                   6422: 		#$syval.=$1;
                   6423: 	    #}
1.37      www      6424:         } else {
                   6425: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6426:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6427:                             &GDBM_READER(),0640)) {
1.37      www      6428: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6429:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6430:               unless ($ids) { 
                   6431:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6432:               }
                   6433:               unless ($ids) {
                   6434: # alias?
                   6435: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6436:               }
1.37      www      6437:               if ($ids) {
                   6438: # ------------------------------------------------------------------- Has ID(s)
                   6439:                  my @possibilities=split(/\,/,$ids);
1.39      www      6440:                  if ($#possibilities==0) {
                   6441: # ----------------------------------------------- There is only one possibility
1.37      www      6442: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6443: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6444: 						    $resid,$thisfn);
1.249     www      6445:                  } elsif (!$donotrecurse) {
1.39      www      6446: # ------------------------------------------ There is more than one possibility
                   6447:                      my $realpossible=0;
1.191     harris41 6448:                      foreach (@possibilities) {
1.39      www      6449: 			 my $file=$bighash{'src_'.$_};
                   6450:                          if (&allowed('bre',$file)) {
                   6451:          		    my ($mapid,$resid)=split(/\./,$_);
                   6452:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6453: 				$realpossible++;
1.626     albertel 6454:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6455: 						    $resid,$thisfn);
1.39      www      6456:                             }
                   6457: 			 }
1.191     harris41 6458:                      }
1.39      www      6459: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6460:                  } else {
                   6461:                      $syval='';
1.37      www      6462:                  }
                   6463: 	      }
                   6464:               untie(%bighash)
1.481     raeburn  6465:            }
1.31      www      6466:         }
1.62      www      6467:         if ($syval) {
1.620     albertel 6468: 	    return $env{$cache_str}=$syval;
1.62      www      6469:         }
1.31      www      6470:     }
1.44      www      6471:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6472:     return $env{$cache_str}='';
1.31      www      6473: }
                   6474: 
                   6475: # ---------------------------------------------------------- Return random seed
                   6476: 
1.32      www      6477: sub numval {
                   6478:     my $txt=shift;
                   6479:     $txt=~tr/A-J/0-9/;
                   6480:     $txt=~tr/a-j/0-9/;
                   6481:     $txt=~tr/K-T/0-9/;
                   6482:     $txt=~tr/k-t/0-9/;
                   6483:     $txt=~tr/U-Z/0-5/;
                   6484:     $txt=~tr/u-z/0-5/;
                   6485:     $txt=~s/\D//g;
1.564     albertel 6486:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6487:     return int($txt);
1.368     albertel 6488: }
                   6489: 
1.484     albertel 6490: sub numval2 {
                   6491:     my $txt=shift;
                   6492:     $txt=~tr/A-J/0-9/;
                   6493:     $txt=~tr/a-j/0-9/;
                   6494:     $txt=~tr/K-T/0-9/;
                   6495:     $txt=~tr/k-t/0-9/;
                   6496:     $txt=~tr/U-Z/0-5/;
                   6497:     $txt=~tr/u-z/0-5/;
                   6498:     $txt=~s/\D//g;
                   6499:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6500:     my $total;
                   6501:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6502:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6503:     return int($total);
                   6504: }
                   6505: 
1.575     albertel 6506: sub numval3 {
                   6507:     use integer;
                   6508:     my $txt=shift;
                   6509:     $txt=~tr/A-J/0-9/;
                   6510:     $txt=~tr/a-j/0-9/;
                   6511:     $txt=~tr/K-T/0-9/;
                   6512:     $txt=~tr/k-t/0-9/;
                   6513:     $txt=~tr/U-Z/0-5/;
                   6514:     $txt=~tr/u-z/0-5/;
                   6515:     $txt=~s/\D//g;
                   6516:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6517:     my $total;
                   6518:     foreach my $val (@txts) { $total+=$val; }
                   6519:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6520:     return $total;
                   6521: }
                   6522: 
1.675     albertel 6523: sub digest {
                   6524:     my ($data)=@_;
                   6525:     my $digest=&Digest::MD5::md5($data);
                   6526:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6527:     my ($e,$f);
                   6528:     {
                   6529:         use integer;
                   6530:         $e=($a+$b);
                   6531:         $f=($c+$d);
                   6532:         if ($_64bit) {
                   6533:             $e=(($e<<32)>>32);
                   6534:             $f=(($f<<32)>>32);
                   6535:         }
                   6536:     }
                   6537:     if (wantarray) {
                   6538: 	return ($e,$f);
                   6539:     } else {
                   6540: 	my $g;
                   6541: 	{
                   6542: 	    use integer;
                   6543: 	    $g=($e+$f);
                   6544: 	    if ($_64bit) {
                   6545: 		$g=(($g<<32)>>32);
                   6546: 	    }
                   6547: 	}
                   6548: 	return $g;
                   6549:     }
                   6550: }
                   6551: 
1.368     albertel 6552: sub latest_rnd_algorithm_id {
1.675     albertel 6553:     return '64bit5';
1.366     albertel 6554: }
1.32      www      6555: 
1.503     albertel 6556: sub get_rand_alg {
                   6557:     my ($courseid)=@_;
1.790     albertel 6558:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6559:     if ($courseid) {
1.620     albertel 6560: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6561:     }
                   6562:     return &latest_rnd_algorithm_id();
                   6563: }
                   6564: 
1.562     albertel 6565: sub validCODE {
                   6566:     my ($CODE)=@_;
                   6567:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6568:     return 0;
                   6569: }
                   6570: 
1.491     albertel 6571: sub getCODE {
1.620     albertel 6572:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6573:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6574: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6575: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6576: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6577:     }
                   6578:     return undef;
                   6579: }
                   6580: 
1.31      www      6581: sub rndseed {
1.155     albertel 6582:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6583: 
1.790     albertel 6584:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6585:     if (!$symb) {
1.366     albertel 6586: 	unless ($symb=$wsymb) { return time; }
                   6587:     }
                   6588:     if (!$courseid) { $courseid=$wcourseid; }
                   6589:     if (!$domain) { $domain=$wdomain; }
                   6590:     if (!$username) { $username=$wusername }
1.503     albertel 6591:     my $which=&get_rand_alg();
1.491     albertel 6592:     if (defined(&getCODE())) {
1.675     albertel 6593: 	if ($which eq '64bit5') {
                   6594: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6595: 	} elsif ($which eq '64bit4') {
1.575     albertel 6596: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6597: 	} else {
                   6598: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6599: 	}
1.675     albertel 6600:     } elsif ($which eq '64bit5') {
                   6601: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6602:     } elsif ($which eq '64bit4') {
                   6603: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6604:     } elsif ($which eq '64bit3') {
                   6605: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6606:     } elsif ($which eq '64bit2') {
                   6607: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6608:     } elsif ($which eq '64bit') {
                   6609: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6610:     }
                   6611:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6612: }
                   6613: 
                   6614: sub rndseed_32bit {
                   6615:     my ($symb,$courseid,$domain,$username)=@_;
                   6616:     {
                   6617: 	use integer;
                   6618: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6619: 	my $symbseed=numval($symb) << 22;
                   6620: 	my $namechck=unpack("%32C*",$username) << 17;
                   6621: 	my $nameseed=numval($username) << 12;
                   6622: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6623: 	my $courseseed=unpack("%32C*",$courseid);
                   6624: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6625: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6626: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6627: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6628: 	return $num;
                   6629:     }
                   6630: }
                   6631: 
                   6632: sub rndseed_64bit {
                   6633:     my ($symb,$courseid,$domain,$username)=@_;
                   6634:     {
                   6635: 	use integer;
                   6636: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6637: 	my $symbseed=numval($symb) << 10;
                   6638: 	my $namechck=unpack("%32S*",$username);
                   6639: 	
                   6640: 	my $nameseed=numval($username) << 21;
                   6641: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6642: 	my $courseseed=unpack("%32S*",$courseid);
                   6643: 	
                   6644: 	my $num1=$symbchck+$symbseed+$namechck;
                   6645: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6646: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6647: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6648: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6649: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6650: 	return "$num1,$num2";
1.155     albertel 6651:     }
1.366     albertel 6652: }
                   6653: 
1.443     albertel 6654: sub rndseed_64bit2 {
                   6655:     my ($symb,$courseid,$domain,$username)=@_;
                   6656:     {
                   6657: 	use integer;
                   6658: 	# strings need to be an even # of cahracters long, it it is odd the
                   6659:         # last characters gets thrown away
                   6660: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6661: 	my $symbseed=numval($symb) << 10;
                   6662: 	my $namechck=unpack("%32S*",$username.' ');
                   6663: 	
                   6664: 	my $nameseed=numval($username) << 21;
1.501     albertel 6665: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6666: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6667: 	
                   6668: 	my $num1=$symbchck+$symbseed+$namechck;
                   6669: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6670: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6671: 	#&logthis("rndseed :$num:$symb");
1.501     albertel 6672: 	return "$num1,$num2";
                   6673:     }
                   6674: }
                   6675: 
                   6676: sub rndseed_64bit3 {
                   6677:     my ($symb,$courseid,$domain,$username)=@_;
                   6678:     {
                   6679: 	use integer;
                   6680: 	# strings need to be an even # of cahracters long, it it is odd the
                   6681:         # last characters gets thrown away
                   6682: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6683: 	my $symbseed=numval2($symb) << 10;
                   6684: 	my $namechck=unpack("%32S*",$username.' ');
                   6685: 	
                   6686: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6687: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6688: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6689: 	
                   6690: 	my $num1=$symbchck+$symbseed+$namechck;
                   6691: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6692: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6693: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6694: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6695: 	
1.503     albertel 6696: 	return "$num1:$num2";
1.443     albertel 6697:     }
                   6698: }
                   6699: 
1.575     albertel 6700: sub rndseed_64bit4 {
                   6701:     my ($symb,$courseid,$domain,$username)=@_;
                   6702:     {
                   6703: 	use integer;
                   6704: 	# strings need to be an even # of cahracters long, it it is odd the
                   6705:         # last characters gets thrown away
                   6706: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6707: 	my $symbseed=numval3($symb) << 10;
                   6708: 	my $namechck=unpack("%32S*",$username.' ');
                   6709: 	
                   6710: 	my $nameseed=numval3($username) << 21;
                   6711: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6712: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6713: 	
                   6714: 	my $num1=$symbchck+$symbseed+$namechck;
                   6715: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6716: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6717: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6718: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6719: 	
                   6720: 	return "$num1:$num2";
                   6721:     }
                   6722: }
                   6723: 
1.675     albertel 6724: sub rndseed_64bit5 {
                   6725:     my ($symb,$courseid,$domain,$username)=@_;
                   6726:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6727:     return "$num1:$num2";
                   6728: }
                   6729: 
1.366     albertel 6730: sub rndseed_CODE_64bit {
                   6731:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6732:     {
1.366     albertel 6733: 	use integer;
1.443     albertel 6734: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6735: 	my $symbseed=numval2($symb);
1.491     albertel 6736: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6737: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6738: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6739: 	my $num1=$symbseed+$CODEchck;
                   6740: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6741: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6742: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6743: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6744: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6745: 	return "$num1:$num2";
1.366     albertel 6746:     }
                   6747: }
                   6748: 
1.575     albertel 6749: sub rndseed_CODE_64bit4 {
                   6750:     my ($symb,$courseid,$domain,$username)=@_;
                   6751:     {
                   6752: 	use integer;
                   6753: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6754: 	my $symbseed=numval3($symb);
                   6755: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6756: 	my $CODEseed=numval3(&getCODE());
                   6757: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6758: 	my $num1=$symbseed+$CODEchck;
                   6759: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6760: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6761: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6762: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6763: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6764: 	return "$num1:$num2";
                   6765:     }
                   6766: }
                   6767: 
1.675     albertel 6768: sub rndseed_CODE_64bit5 {
                   6769:     my ($symb,$courseid,$domain,$username)=@_;
                   6770:     my $code = &getCODE();
                   6771:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6772:     return "$num1:$num2";
                   6773: }
                   6774: 
1.366     albertel 6775: sub setup_random_from_rndseed {
                   6776:     my ($rndseed)=@_;
1.503     albertel 6777:     if ($rndseed =~/([,:])/) {
                   6778: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6779: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6780:     } else {
                   6781: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6782:     }
1.36      albertel 6783: }
                   6784: 
1.474     albertel 6785: sub latest_receipt_algorithm_id {
                   6786:     return 'receipt2';
                   6787: }
                   6788: 
1.480     www      6789: sub recunique {
                   6790:     my $fucourseid=shift;
                   6791:     my $unique;
1.620     albertel 6792:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6793: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6794:     } else {
                   6795: 	$unique=$perlvar{'lonReceipt'};
                   6796:     }
                   6797:     return unpack("%32C*",$unique);
                   6798: }
                   6799: 
                   6800: sub recprefix {
                   6801:     my $fucourseid=shift;
                   6802:     my $prefix;
1.620     albertel 6803:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6804: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6805:     } else {
                   6806: 	$prefix=$perlvar{'lonHostID'};
                   6807:     }
                   6808:     return unpack("%32C*",$prefix);
                   6809: }
                   6810: 
1.76      www      6811: sub ireceipt {
1.474     albertel 6812:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6813:     my $cuname=unpack("%32C*",$funame);
                   6814:     my $cudom=unpack("%32C*",$fudom);
                   6815:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6816:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6817:     my $cunique=&recunique($fucourseid);
1.474     albertel 6818:     my $cpart=unpack("%32S*",$part);
1.480     www      6819:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6820:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6821: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6822: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6823: 			       
                   6824: 	$return.= ($cunique%$cuname+
                   6825: 		   $cunique%$cudom+
                   6826: 		   $cusymb%$cuname+
                   6827: 		   $cusymb%$cudom+
                   6828: 		   $cucourseid%$cuname+
                   6829: 		   $cucourseid%$cudom+
                   6830: 		   $cpart%$cuname+
                   6831: 		   $cpart%$cudom);
                   6832:     } else {
                   6833: 	$return.= ($cunique%$cuname+
                   6834: 		   $cunique%$cudom+
                   6835: 		   $cusymb%$cuname+
                   6836: 		   $cusymb%$cudom+
                   6837: 		   $cucourseid%$cuname+
                   6838: 		   $cucourseid%$cudom);
                   6839:     }
                   6840:     return $return;
1.76      www      6841: }
                   6842: 
                   6843: sub receipt {
1.474     albertel 6844:     my ($part)=@_;
1.790     albertel 6845:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6846:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6847: }
1.260     ng       6848: 
1.790     albertel 6849: sub whichuser {
                   6850:     my ($passedsymb)=@_;
                   6851:     my ($symb,$courseid,$domain,$name,$publicuser);
                   6852:     if (defined($env{'form.grade_symb'})) {
                   6853: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   6854: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   6855: 	if (!$allowed &&
                   6856: 	    exists($env{'request.course.sec'}) &&
                   6857: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   6858: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   6859: 			      '/'.$env{'request.course.sec'});
                   6860: 	}
                   6861: 	if ($allowed) {
                   6862: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   6863: 	    $courseid=$tmp_courseid;
                   6864: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   6865: 	    ($name)=&get_env_multiple('form.grade_username');
                   6866: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   6867: 	}
                   6868:     }
                   6869:     if (!$passedsymb) {
                   6870: 	$symb=&symbread();
                   6871:     } else {
                   6872: 	$symb=$passedsymb;
                   6873:     }
                   6874:     $courseid=$env{'request.course.id'};
                   6875:     $domain=$env{'user.domain'};
                   6876:     $name=$env{'user.name'};
                   6877:     if ($name eq 'public' && $domain eq 'public') {
                   6878: 	if (!defined($env{'form.username'})) {
                   6879: 	    $env{'form.username'}.=time.rand(10000000);
                   6880: 	}
                   6881: 	$name.=$env{'form.username'};
                   6882:     }
                   6883:     return ($symb,$courseid,$domain,$name,$publicuser);
                   6884: 
                   6885: }
                   6886: 
1.36      albertel 6887: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6888: # returns either the contents of the file or 
                   6889: # -1 if the file doesn't exist
1.481     raeburn  6890: #
                   6891: # if the target is a file that was uploaded via DOCS, 
                   6892: # a check will be made to see if a current copy exists on the local server,
                   6893: # if it does this will be served, otherwise a copy will be retrieved from
                   6894: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6895: # the local server.   
1.472     albertel 6896: 
1.36      albertel 6897: sub getfile {
1.538     albertel 6898:     my ($file) = @_;
1.609     banghart 6899:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6900:     &repcopy($file);
                   6901:     return &readfile($file);
                   6902: }
                   6903: 
                   6904: sub repcopy_userfile {
                   6905:     my ($file)=@_;
1.609     banghart 6906:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6907:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6908:     my ($cdom,$cnum,$filename) = 
                   6909: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6910:     my ($info,$rtncode);
                   6911:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6912:     if (-e "$file") {
                   6913: 	my @fileinfo = stat($file);
                   6914: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6915: 	if ($lwpresp ne 'ok') {
                   6916: 	    if ($rtncode eq '404') {
1.538     albertel 6917: 		unlink($file);
1.482     albertel 6918: 	    }
1.517     albertel 6919: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6920: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6921: 	    #my $response=$ua->request($request);
                   6922: 	    #if ($response->is_success()) {
                   6923: 	#	return $response->content;
                   6924: 	#    } else {
                   6925: 	#	return -1;
                   6926: 	#    }
1.482     albertel 6927: 	    return -1;
                   6928: 	}
                   6929: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6930: 	    return 'ok';
1.482     albertel 6931: 	}
                   6932: 	$info = '';
1.538     albertel 6933: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6934: 	if ($lwpresp ne 'ok') {
                   6935: 	    return -1;
                   6936: 	}
                   6937:     } else {
1.538     albertel 6938: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6939: 	if ($lwpresp ne 'ok') {
1.517     albertel 6940: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6941: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6942: 	    my $response=$ua->request($request);
                   6943: 	    if ($response->is_success()) {
1.538     albertel 6944: 		$info=$response->content;
1.517     albertel 6945: 	    } else {
                   6946: 		return -1;
                   6947: 	    }
1.482     albertel 6948: 	}
                   6949: 	my @parts = ($cdom,$cnum); 
                   6950: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6951: 	    push @parts, split(/\//,$1);
1.518     albertel 6952: 	}
1.538     albertel 6953: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6954: 	foreach my $part (@parts) {
                   6955: 	    $path .= '/'.$part;
                   6956: 	    if (!-e $path) {
                   6957: 		mkdir($path,0770);
                   6958: 	    }
                   6959: 	}
                   6960:     }
1.538     albertel 6961:     open(FILE,">$file");
1.482     albertel 6962:     print FILE $info;
                   6963:     close(FILE);
1.607     raeburn  6964:     return 'ok';
1.481     raeburn  6965: }
                   6966: 
1.517     albertel 6967: sub tokenwrapper {
                   6968:     my $uri=shift;
1.552     albertel 6969:     $uri=~s|^http\://([^/]+)||;
                   6970:     $uri=~s|^/||;
1.620     albertel 6971:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6972:     my $token=$1;
1.552     albertel 6973:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6974:     if ($udom && $uname && $file) {
                   6975: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6976:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6977:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6978:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6979:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6980:     } else {
                   6981:         return '/adm/notfound.html';
                   6982:     }
                   6983: }
                   6984: 
1.481     raeburn  6985: sub getuploaded {
                   6986:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6987:     $uri=~s/^\///;
                   6988:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6989:     my $ua=new LWP::UserAgent;
                   6990:     my $request=new HTTP::Request($reqtype,$uri);
                   6991:     my $response=$ua->request($request);
                   6992:     $$rtncode = $response->code;
1.482     albertel 6993:     if (! $response->is_success()) {
                   6994: 	return 'failed';
                   6995:     }      
                   6996:     if ($reqtype eq 'HEAD') {
1.486     www      6997: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6998:     } elsif ($reqtype eq 'GET') {
                   6999: 	$$info = $response->content;
1.472     albertel 7000:     }
1.482     albertel 7001:     return 'ok';
1.36      albertel 7002: }
                   7003: 
1.481     raeburn  7004: sub readfile {
                   7005:     my $file = shift;
                   7006:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7007:     my $fh;
                   7008:     open($fh,"<$file");
                   7009:     my $a='';
                   7010:     while (<$fh>) { $a .=$_; }
                   7011:     return $a;
                   7012: }
                   7013: 
1.36      albertel 7014: sub filelocation {
1.590     banghart 7015:     my ($dir,$file) = @_;
                   7016:     my $location;
                   7017:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7018: 
                   7019:     if ($file =~ m-^/adm/-) {
                   7020: 	$file=~s-^/adm/wrapper/-/-;
                   7021: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7022:     }
1.590     banghart 7023:     if ($file=~m:^/~:) { # is a contruction space reference
                   7024:         $location = $file;
                   7025:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 7026:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   7027: 	# is a correct contruction space reference
                   7028:         $location = $file;
1.609     banghart 7029:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7030:         my ($udom,$uname,$filename)=
1.609     banghart 7031:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 7032:         my $home=&homeserver($uname,$udom);
                   7033:         my $is_me=0;
                   7034:         my @ids=&current_machine_ids();
                   7035:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7036:         if ($is_me) {
1.740     www      7037:   	    $location=&propath($udom,$uname).
1.590     banghart 7038:   	      '/userfiles/'.$filename;
                   7039:         } else {
                   7040:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7041:   	      $udom.'/'.$uname.'/'.$filename;
                   7042:         }
                   7043:     } else {
                   7044:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7045:         $file=~s:^/res/:/:;
                   7046:         if ( !( $file =~ m:^/:) ) {
                   7047:             $location = $dir. '/'.$file;
                   7048:         } else {
                   7049:             $location = '/home/httpd/html/res'.$file;
                   7050:         }
1.59      albertel 7051:     }
1.590     banghart 7052:     $location=~s://+:/:g; # remove duplicate /
                   7053:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7054:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7055:     return $location;
1.46      www      7056: }
1.36      albertel 7057: 
1.46      www      7058: sub hreflocation {
                   7059:     my ($dir,$file)=@_;
1.460     albertel 7060:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7061: 	$file=filelocation($dir,$file);
1.700     albertel 7062:     } elsif ($file=~m-^/adm/-) {
                   7063: 	$file=~s-^/adm/wrapper/-/-;
                   7064: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7065:     }
                   7066:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7067: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   7068:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 7069: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 7070:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   7071: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7072: 	    -/uploaded/$1/$2/-x;
1.46      www      7073:     }
1.462     albertel 7074:     return $file;
1.465     albertel 7075: }
                   7076: 
                   7077: sub current_machine_domains {
                   7078:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7079:     my @domains;
                   7080:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7081: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7082: 	if ($hostname eq $name) {
                   7083: 	    push(@domains,$hostdom{$id});
                   7084: 	}
                   7085:     }
                   7086:     return @domains;
                   7087: }
                   7088: 
                   7089: sub current_machine_ids {
                   7090:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7091:     my @ids;
                   7092:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7093: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7094: 	if ($hostname eq $name) {
                   7095: 	    push(@ids,$id);
                   7096: 	}
                   7097:     }
                   7098:     return @ids;
1.31      www      7099: }
                   7100: 
                   7101: # ------------------------------------------------------------- Declutters URLs
                   7102: 
                   7103: sub declutter {
                   7104:     my $thisfn=shift;
1.569     albertel 7105:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7106:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7107:     $thisfn=~s/^\///;
1.697     albertel 7108:     $thisfn=~s|^adm/wrapper/||;
                   7109:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7110:     $thisfn=~s/^res\///;
1.235     www      7111:     $thisfn=~s/\?.+$//;
1.268     www      7112:     return $thisfn;
                   7113: }
                   7114: 
                   7115: # ------------------------------------------------------------- Clutter up URLs
                   7116: 
                   7117: sub clutter {
                   7118:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7119:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7120:        $thisfn='/res'.$thisfn; 
                   7121:     }
1.694     albertel 7122:     if ($thisfn !~m|/adm|) {
1.695     albertel 7123: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7124: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7125: 	} else {
                   7126: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7127: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7128: 	    if ($embstyle eq 'ssi'
                   7129: 		|| ($embstyle eq 'hdn')
                   7130: 		|| ($embstyle eq 'rat')
                   7131: 		|| ($embstyle eq 'prv')
                   7132: 		|| ($embstyle eq 'ign')) {
                   7133: 		#do nothing with these
                   7134: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7135: 		|| ($embstyle eq 'emb')
                   7136: 		|| ($embstyle eq 'wrp')) {
                   7137: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7138: 	    } elsif ($embstyle eq 'unk'
                   7139: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7140: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7141: 	    } else {
1.718     www      7142: #		&logthis("Got a blank emb style");
1.695     albertel 7143: 	    }
1.694     albertel 7144: 	}
                   7145:     }
1.31      www      7146:     return $thisfn;
1.12      www      7147: }
                   7148: 
1.787     albertel 7149: sub clutter_with_no_wrapper {
                   7150:     my $uri = &clutter(shift);
                   7151:     if ($uri =~ m-^/adm/-) {
                   7152: 	$uri =~ s-^/adm/wrapper/-/-;
                   7153: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7154:     }
                   7155:     return $uri;
                   7156: }
                   7157: 
1.557     albertel 7158: sub freeze_escape {
                   7159:     my ($value)=@_;
                   7160:     if (ref($value)) {
                   7161: 	$value=&nfreeze($value);
                   7162: 	return '__FROZEN__'.&escape($value);
                   7163:     }
                   7164:     return &escape($value);
                   7165: }
                   7166: 
1.11      www      7167: 
1.557     albertel 7168: sub thaw_unescape {
                   7169:     my ($value)=@_;
                   7170:     if ($value =~ /^__FROZEN__/) {
                   7171: 	substr($value,0,10,undef);
                   7172: 	$value=&unescape($value);
                   7173: 	return &thaw($value);
                   7174:     }
                   7175:     return &unescape($value);
                   7176: }
                   7177: 
1.436     albertel 7178: sub correct_line_ends {
                   7179:     my ($result)=@_;
                   7180:     $$result =~s/\r\n/\n/mg;
                   7181:     $$result =~s/\r/\n/mg;
1.415     albertel 7182: }
1.1       albertel 7183: # ================================================================ Main Program
                   7184: 
1.184     www      7185: sub goodbye {
1.204     albertel 7186:    &logthis("Starting Shut down");
1.443     albertel 7187: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7188:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7189: #converted
1.599     albertel 7190: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7191:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7192: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7193: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7194: #1.1 only
1.599     albertel 7195: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7196: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7197: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7198: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7199:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7200:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7201:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7202:    &flushcourselogs();
                   7203:    &logthis("Shutting down");
                   7204: }
                   7205: 
1.179     www      7206: BEGIN {
1.228     harris41 7207: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7208:     unless ($readit) {
1.217     harris41 7209: {
1.781     raeburn  7210:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7211:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7212: }
1.1       albertel 7213: 
1.327     albertel 7214: # ------------------------------------------------------------ Read domain file
                   7215: {
                   7216:     %domaindescription = ();
                   7217:     %domain_auth_def = ();
                   7218:     %domain_auth_arg_def = ();
1.448     albertel 7219:     my $fh;
                   7220:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7221:        while (<$fh>) {
1.390     matthew  7222:            next if (/^(\#|\s*$)/);
                   7223: #           next if /^\#/;
1.327     albertel 7224:            chomp;
1.403     www      7225:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7226: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7227: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7228:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7229: 	   $domaindescription{$domain}=$domain_description;
                   7230: 	   $domain_lang_def{$domain}=$def_lang;
                   7231: 	   $domain_city{$domain}=$city;
                   7232: 	   $domain_longi{$domain}=$longi;
                   7233: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7234:            $domain_primary{$domain}=$primary;
1.403     www      7235: 
1.448     albertel 7236:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7237: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7238: 	}
1.327     albertel 7239:     }
1.448     albertel 7240:     close ($fh);
1.327     albertel 7241: }
                   7242: 
                   7243: 
1.1       albertel 7244: # ------------------------------------------------------------- Read hosts file
                   7245: {
1.448     albertel 7246:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7247: 
                   7248:     while (my $configline=<$config>) {
1.303     matthew  7249:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7250:        chomp($configline);
1.595     albertel 7251:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7252:        $name=~s/\s//g;
1.595     albertel 7253:        if ($id && $domain && $role && $name) {
1.252     albertel 7254: 	 $hostname{$id}=$name;
                   7255: 	 $hostdom{$id}=$domain;
                   7256: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7257:        }
1.1       albertel 7258:     }
1.448     albertel 7259:     close($config);
1.619     albertel 7260:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7261:     #&get_iphost();
1.1       albertel 7262: }
                   7263: 
1.598     albertel 7264: sub get_iphost {
                   7265:     if (%iphost) { return %iphost; }
1.653     albertel 7266:     my %name_to_ip;
1.598     albertel 7267:     foreach my $id (keys(%hostname)) {
                   7268: 	my $name=$hostname{$id};
1.653     albertel 7269: 	my $ip;
                   7270: 	if (!exists($name_to_ip{$name})) {
                   7271: 	    $ip = gethostbyname($name);
                   7272: 	    if (!$ip || length($ip) ne 4) {
                   7273: 		&logthis("Skipping host $id name $name no IP found\n");
                   7274: 		next;
                   7275: 	    }
                   7276: 	    $ip=inet_ntoa($ip);
                   7277: 	    $name_to_ip{$name} = $ip;
                   7278: 	} else {
                   7279: 	    $ip = $name_to_ip{$name};
1.598     albertel 7280: 	}
                   7281: 	push(@{$iphost{$ip}},$id);
                   7282:     }
                   7283:     return %iphost;
                   7284: }
                   7285: 
1.1       albertel 7286: # ------------------------------------------------------ Read spare server file
                   7287: {
1.448     albertel 7288:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7289: 
                   7290:     while (my $configline=<$config>) {
                   7291:        chomp($configline);
1.284     matthew  7292:        if ($configline) {
1.784     albertel 7293: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7294: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7295: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7296:        }
                   7297:     }
1.448     albertel 7298:     close($config);
1.1       albertel 7299: }
1.11      www      7300: # ------------------------------------------------------------ Read permissions
                   7301: {
1.448     albertel 7302:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7303: 
                   7304:     while (my $configline=<$config>) {
1.448     albertel 7305: 	chomp($configline);
                   7306: 	if ($configline) {
                   7307: 	    my ($role,$perm)=split(/ /,$configline);
                   7308: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7309: 	}
1.11      www      7310:     }
1.448     albertel 7311:     close($config);
1.11      www      7312: }
                   7313: 
                   7314: # -------------------------------------------- Read plain texts for permissions
                   7315: {
1.448     albertel 7316:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7317: 
                   7318:     while (my $configline=<$config>) {
1.448     albertel 7319: 	chomp($configline);
                   7320: 	if ($configline) {
1.742     raeburn  7321: 	    my ($short,@plain)=split(/:/,$configline);
                   7322:             %{$prp{$short}} = ();
                   7323: 	    if (@plain > 0) {
                   7324:                 $prp{$short}{'std'} = $plain[0];
                   7325:                 for (my $i=1; $i<@plain; $i++) {
                   7326:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7327:                 }
                   7328:             }
1.448     albertel 7329: 	}
1.135     www      7330:     }
1.448     albertel 7331:     close($config);
1.135     www      7332: }
                   7333: 
                   7334: # ---------------------------------------------------------- Read package table
                   7335: {
1.448     albertel 7336:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7337: 
                   7338:     while (my $configline=<$config>) {
1.483     albertel 7339: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7340: 	chomp($configline);
                   7341: 	my ($short,$plain)=split(/:/,$configline);
                   7342: 	my ($pack,$name)=split(/\&/,$short);
                   7343: 	if ($plain ne '') {
                   7344: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7345: 	    $packagetab{$short}=$plain; 
                   7346: 	}
1.11      www      7347:     }
1.448     albertel 7348:     close($config);
1.329     matthew  7349: }
                   7350: 
                   7351: # ------------- set up temporary directory
                   7352: {
                   7353:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7354: 
1.11      www      7355: }
                   7356: 
1.599     albertel 7357: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7358: 
1.281     www      7359: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7360: $dumpcount=0;
1.22      www      7361: 
1.163     harris41 7362: &logtouch();
1.672     albertel 7363: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7364: $readit=1;
1.564     albertel 7365:     {
                   7366: 	use integer;
                   7367: 	my $test=(2**32)+1;
1.568     albertel 7368: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7369: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7370:     }
1.195     www      7371: }
1.1       albertel 7372: }
1.179     www      7373: 
1.1       albertel 7374: 1;
1.191     harris41 7375: __END__
                   7376: 
1.243     albertel 7377: =pod
                   7378: 
1.191     harris41 7379: =head1 NAME
                   7380: 
1.243     albertel 7381: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7382: 
                   7383: =head1 SYNOPSIS
                   7384: 
1.243     albertel 7385: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7386: 
                   7387:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7388: 
1.243     albertel 7389: Common parameters:
                   7390: 
                   7391: =over 4
                   7392: 
                   7393: =item *
                   7394: 
                   7395: $uname : an internal username (if $cname expecting a course Id specifically)
                   7396: 
                   7397: =item *
                   7398: 
                   7399: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7400: 
                   7401: =item *
                   7402: 
                   7403: $symb : a resource instance identifier
                   7404: 
                   7405: =item *
                   7406: 
                   7407: $namespace : the name of a .db file that contains the data needed or
                   7408: being set.
                   7409: 
                   7410: =back
                   7411: 
1.394     bowersj2 7412: =head1 OVERVIEW
1.191     harris41 7413: 
1.394     bowersj2 7414: lonnet provides subroutines which interact with the
                   7415: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7416: about classes, users, and resources.
1.243     albertel 7417: 
                   7418: For many of these objects you can also use this to store data about
                   7419: them or modify them in various ways.
1.191     harris41 7420: 
1.394     bowersj2 7421: =head2 Symbs
1.191     harris41 7422: 
1.394     bowersj2 7423: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7424: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7425: map, the resource number of the resource in the map, and the URL of
                   7426: the resource itself. The latter is somewhat redundant, but might help
                   7427: if maps change.
                   7428: 
                   7429: An example is
                   7430: 
                   7431:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7432: 
                   7433: The respective map entry is
                   7434: 
                   7435:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7436:   title="Problem 2">
                   7437:  </resource>
                   7438: 
                   7439: Symbs are used by the random number generator, as well as to store and
                   7440: restore data specific to a certain instance of for example a problem.
                   7441: 
                   7442: =head2 Storing And Retrieving Data
                   7443: 
                   7444: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7445: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7446: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7447: is is the non-critical message twin of cstore. These functions are for
                   7448: handlers to store a perl hash to a user's permanent data space in an
                   7449: easy manner, and to retrieve it again on another call. It is expected
                   7450: that a handler would use this once at the beginning to retrieve data,
                   7451: and then again once at the end to send only the new data back.
                   7452: 
                   7453: The data is stored in the user's data directory on the user's
                   7454: homeserver under the ID of the course.
                   7455: 
                   7456: The hash that is returned by restore will have all of the previous
                   7457: value for all of the elements of the hash.
                   7458: 
                   7459: Example:
                   7460: 
                   7461:  #creating a hash
                   7462:  my %hash;
                   7463:  $hash{'foo'}='bar';
                   7464: 
                   7465:  #storing it
                   7466:  &Apache::lonnet::cstore(\%hash);
                   7467: 
                   7468:  #changing a value
                   7469:  $hash{'foo'}='notbar';
                   7470: 
                   7471:  #adding a new value
                   7472:  $hash{'bar'}='foo';
                   7473:  &Apache::lonnet::cstore(\%hash);
                   7474: 
                   7475:  #retrieving the hash
                   7476:  my %history=&Apache::lonnet::restore();
                   7477: 
                   7478:  #print the hash
                   7479:  foreach my $key (sort(keys(%history))) {
                   7480:    print("\%history{$key} = $history{$key}");
                   7481:  }
                   7482: 
                   7483: Will print out:
1.191     harris41 7484: 
1.394     bowersj2 7485:  %history{1:foo} = bar
                   7486:  %history{1:keys} = foo:timestamp
                   7487:  %history{1:timestamp} = 990455579
                   7488:  %history{2:bar} = foo
                   7489:  %history{2:foo} = notbar
                   7490:  %history{2:keys} = foo:bar:timestamp
                   7491:  %history{2:timestamp} = 990455580
                   7492:  %history{bar} = foo
                   7493:  %history{foo} = notbar
                   7494:  %history{timestamp} = 990455580
                   7495:  %history{version} = 2
                   7496: 
                   7497: Note that the special hash entries C<keys>, C<version> and
                   7498: C<timestamp> were added to the hash. C<version> will be equal to the
                   7499: total number of versions of the data that have been stored. The
                   7500: C<timestamp> attribute will be the UNIX time the hash was
                   7501: stored. C<keys> is available in every historical section to list which
                   7502: keys were added or changed at a specific historical revision of a
                   7503: hash.
                   7504: 
                   7505: B<Warning>: do not store the hash that restore returns directly. This
                   7506: will cause a mess since it will restore the historical keys as if the
                   7507: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7508: 
1.394     bowersj2 7509: Calling convention:
1.191     harris41 7510: 
1.394     bowersj2 7511:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7512:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7513: 
1.394     bowersj2 7514: For more detailed information, see lonnet specific documentation.
1.191     harris41 7515: 
1.394     bowersj2 7516: =head1 RETURN MESSAGES
1.191     harris41 7517: 
1.394     bowersj2 7518: =over 4
1.191     harris41 7519: 
1.394     bowersj2 7520: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7521: 
1.394     bowersj2 7522: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7523: when the connection is brought back up
1.191     harris41 7524: 
1.394     bowersj2 7525: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7526: for later delivery
1.191     harris41 7527: 
1.394     bowersj2 7528: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7529: 
1.394     bowersj2 7530: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7531: that was requested
1.191     harris41 7532: 
1.243     albertel 7533: =back
1.191     harris41 7534: 
1.243     albertel 7535: =head1 PUBLIC SUBROUTINES
1.191     harris41 7536: 
1.243     albertel 7537: =head2 Session Environment Functions
1.191     harris41 7538: 
1.243     albertel 7539: =over 4
1.191     harris41 7540: 
1.394     bowersj2 7541: =item * 
                   7542: X<appenv()>
                   7543: B<appenv(%hash)>: the value of %hash is written to
                   7544: the user envirnoment file, and will be restored for each access this
1.620     albertel 7545: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7546: process
1.191     harris41 7547: 
                   7548: =item *
1.394     bowersj2 7549: X<delenv()>
                   7550: B<delenv($regexp)>: removes all items from the session
                   7551: environment file that matches the regular expression in $regexp. The
1.620     albertel 7552: values are also delted from the current processes %env.
1.191     harris41 7553: 
1.243     albertel 7554: =back
                   7555: 
                   7556: =head2 User Information
1.191     harris41 7557: 
1.243     albertel 7558: =over 4
1.191     harris41 7559: 
                   7560: =item *
1.394     bowersj2 7561: X<queryauthenticate()>
                   7562: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7563: authentication scheme
                   7564: 
                   7565: =item *
1.394     bowersj2 7566: X<authenticate()>
                   7567: B<authenticate($uname,$upass,$udom)>: try to
                   7568: authenticate user from domain's lib servers (first use the current
                   7569: one). C<$upass> should be the users password.
1.191     harris41 7570: 
                   7571: =item *
1.394     bowersj2 7572: X<homeserver()>
                   7573: B<homeserver($uname,$udom)>: find the server which has
                   7574: the user's directory and files (there must be only one), this caches
                   7575: the answer, and also caches if there is a borken connection.
1.191     harris41 7576: 
                   7577: =item *
1.394     bowersj2 7578: X<idget()>
                   7579: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7580: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7581: username, and only 1 username per ID in a specific domain) (returns
                   7582: hash: id=>name,id=>name)
1.191     harris41 7583: 
                   7584: =item *
1.394     bowersj2 7585: X<idrget()>
                   7586: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7587: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7588: 
                   7589: =item *
1.394     bowersj2 7590: X<idput()>
                   7591: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7592: 
                   7593: =item *
1.394     bowersj2 7594: X<rolesinit()>
                   7595: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7596: 
                   7597: =item *
1.551     albertel 7598: X<getsection()>
                   7599: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7600: course $cname, return section name/number or '' for "not in course"
                   7601: and '-1' for "no section"
                   7602: 
                   7603: =item *
1.394     bowersj2 7604: X<userenvironment()>
                   7605: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7606: passed in @what from the requested user's environment, returns a hash
                   7607: 
                   7608: =back
                   7609: 
                   7610: =head2 User Roles
                   7611: 
                   7612: =over 4
                   7613: 
                   7614: =item *
                   7615: 
                   7616: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7617: actions
                   7618:  F: full access
                   7619:  U,I,K: authentication modes (cxx only)
                   7620:  '': forbidden
                   7621:  1: user needs to choose course
                   7622:  2: browse allowed
1.766     albertel 7623:  A: passphrase authentication needed
1.243     albertel 7624: 
                   7625: =item *
                   7626: 
                   7627: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7628: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7629: and course level
                   7630: 
                   7631: =item *
                   7632: 
                   7633: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7634: explanation of a user role term
                   7635: 
                   7636: =back
                   7637: 
                   7638: =head2 User Modification
                   7639: 
                   7640: =over 4
                   7641: 
                   7642: =item *
                   7643: 
                   7644: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7645: user for the level given by URL.  Optional start and end dates (leave empty
                   7646: string or zero for "no date")
1.191     harris41 7647: 
                   7648: =item *
                   7649: 
1.243     albertel 7650: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7651: change a users, password, possible return values are: ok,
                   7652: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7653: refused
1.191     harris41 7654: 
                   7655: =item *
                   7656: 
1.243     albertel 7657: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7658: 
                   7659: =item *
                   7660: 
1.243     albertel 7661: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7662: modify user
1.191     harris41 7663: 
                   7664: =item *
                   7665: 
1.286     matthew  7666: modifystudent
                   7667: 
                   7668: modify a students enrollment and identification information.
                   7669: The course id is resolved based on the current users environment.  
                   7670: This means the envoking user must be a course coordinator or otherwise
                   7671: associated with a course.
                   7672: 
1.297     matthew  7673: This call is essentially a wrapper for lonnet::modifyuser and
                   7674: lonnet::modify_student_enrollment
1.286     matthew  7675: 
                   7676: Inputs: 
                   7677: 
                   7678: =over 4
                   7679: 
                   7680: =item B<$udom> Students loncapa domain
                   7681: 
                   7682: =item B<$uname> Students loncapa login name
                   7683: 
                   7684: =item B<$uid> Students id/student number
                   7685: 
                   7686: =item B<$umode> Students authentication mode
                   7687: 
                   7688: =item B<$upass> Students password
                   7689: 
                   7690: =item B<$first> Students first name
                   7691: 
                   7692: =item B<$middle> Students middle name
                   7693: 
                   7694: =item B<$last> Students last name
                   7695: 
                   7696: =item B<$gene> Students generation
                   7697: 
                   7698: =item B<$usec> Students section in course
                   7699: 
                   7700: =item B<$end> Unix time of the roles expiration
                   7701: 
                   7702: =item B<$start> Unix time of the roles start date
                   7703: 
                   7704: =item B<$forceid> If defined, allow $uid to be changed
                   7705: 
                   7706: =item B<$desiredhome> server to use as home server for student
                   7707: 
                   7708: =back
1.297     matthew  7709: 
                   7710: =item *
                   7711: 
                   7712: modify_student_enrollment
                   7713: 
                   7714: Change a students enrollment status in a class.  The environment variable
                   7715: 'role.request.course' must be defined for this function to proceed.
                   7716: 
                   7717: Inputs:
                   7718: 
                   7719: =over 4
                   7720: 
                   7721: =item $udom, students domain
                   7722: 
                   7723: =item $uname, students name
                   7724: 
                   7725: =item $uid, students user id
                   7726: 
                   7727: =item $first, students first name
                   7728: 
                   7729: =item $middle
                   7730: 
                   7731: =item $last
                   7732: 
                   7733: =item $gene
                   7734: 
                   7735: =item $usec
                   7736: 
                   7737: =item $end
                   7738: 
                   7739: =item $start
                   7740: 
                   7741: =back
                   7742: 
1.191     harris41 7743: 
                   7744: =item *
                   7745: 
1.243     albertel 7746: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7747: custom role; give a custom role to a user for the level given by URL.  Specify
                   7748: name and domain of role author, and role name
1.191     harris41 7749: 
                   7750: =item *
                   7751: 
1.243     albertel 7752: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7753: 
                   7754: =item *
                   7755: 
1.243     albertel 7756: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7757: 
                   7758: =back
                   7759: 
                   7760: =head2 Course Infomation
                   7761: 
                   7762: =over 4
1.191     harris41 7763: 
                   7764: =item *
                   7765: 
1.631     albertel 7766: coursedescription($courseid) : returns a hash of information about the
                   7767: specified course id, including all environment settings for the
                   7768: course, the description of the course will be in the hash under the
                   7769: key 'description'
1.191     harris41 7770: 
                   7771: =item *
                   7772: 
1.624     albertel 7773: resdata($name,$domain,$type,@which) : request for current parameter
                   7774: setting for a specific $type, where $type is either 'course' or 'user',
                   7775: @what should be a list of parameters to ask about. This routine caches
                   7776: answers for 5 minutes.
1.243     albertel 7777: 
                   7778: =back
                   7779: 
                   7780: =head2 Course Modification
                   7781: 
                   7782: =over 4
1.191     harris41 7783: 
                   7784: =item *
                   7785: 
1.243     albertel 7786: writecoursepref($courseid,%prefs) : write preferences (environment
                   7787: database) for a course
1.191     harris41 7788: 
                   7789: =item *
                   7790: 
1.243     albertel 7791: createcourse($udom,$description,$url) : make/modify course
                   7792: 
                   7793: =back
                   7794: 
                   7795: =head2 Resource Subroutines
                   7796: 
                   7797: =over 4
1.191     harris41 7798: 
                   7799: =item *
                   7800: 
1.243     albertel 7801: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7802: 
                   7803: =item *
                   7804: 
1.243     albertel 7805: repcopy($filename) : subscribes to the requested file, and attempts to
                   7806: replicate from the owning library server, Might return
1.607     raeburn  7807: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7808: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7809: resource. Expects the local filesystem pathname
                   7810: (/home/httpd/html/res/....)
                   7811: 
                   7812: =back
                   7813: 
                   7814: =head2 Resource Information
                   7815: 
                   7816: =over 4
1.191     harris41 7817: 
                   7818: =item *
                   7819: 
1.243     albertel 7820: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7821: a vairety of different possible values, $varname should be a request
                   7822: string, and the other parameters can be used to specify who and what
                   7823: one is asking about.
                   7824: 
                   7825: Possible values for $varname are environment.lastname (or other item
                   7826: from the envirnment hash), user.name (or someother aspect about the
                   7827: user), resource.0.maxtries (or some other part and parameter of a
                   7828: resource)
1.204     albertel 7829: 
                   7830: =item *
                   7831: 
1.243     albertel 7832: directcondval($number) : get current value of a condition; reads from a state
                   7833: string
1.204     albertel 7834: 
                   7835: =item *
                   7836: 
1.243     albertel 7837: condval($condidx) : value of condition index based on state
1.204     albertel 7838: 
                   7839: =item *
                   7840: 
1.243     albertel 7841: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7842: resource's metadata, $what should be either a specific key, or either
                   7843: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7844: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7845: 
                   7846: this function automatically caches all requests
1.191     harris41 7847: 
                   7848: =item *
                   7849: 
1.243     albertel 7850: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7851: network of library servers; returns file handle of where SQL and regex results
                   7852: will be stored for query
1.191     harris41 7853: 
                   7854: =item *
                   7855: 
1.243     albertel 7856: symbread($filename) : return symbolic list entry (filename argument optional);
                   7857: returns the data handle
1.191     harris41 7858: 
                   7859: =item *
                   7860: 
1.243     albertel 7861: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7862: a possible symb for the URL in $thisfn, and if is an encryypted
                   7863: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7864: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7865: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7866: 
1.191     harris41 7867: 
                   7868: =item *
                   7869: 
1.243     albertel 7870: symbclean($symb) : removes versions numbers from a symb, returns the
                   7871: cleaned symb
1.191     harris41 7872: 
                   7873: =item *
                   7874: 
1.243     albertel 7875: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7876: course map, user must be in a course for it to work.
1.191     harris41 7877: 
                   7878: =item *
                   7879: 
1.243     albertel 7880: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7881: 
                   7882: =item *
                   7883: 
1.243     albertel 7884: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7885: a random seed, all arguments are optional, if they aren't sent it uses the
                   7886: environment to derive them. Note: if symb isn't sent and it can't get one
                   7887: from &symbread it will use the current time as its return value
1.191     harris41 7888: 
                   7889: =item *
                   7890: 
1.243     albertel 7891: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7892: unfakeable, receipt
1.191     harris41 7893: 
                   7894: =item *
                   7895: 
1.620     albertel 7896: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7897: 
                   7898: =item *
                   7899: 
1.243     albertel 7900: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7901: 
                   7902: =item *
                   7903: 
1.243     albertel 7904: 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 7905: 
                   7906: =item *
                   7907: 
1.243     albertel 7908: 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 7909: 
                   7910: =item *
                   7911: 
1.243     albertel 7912: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7913: 
                   7914: =item *
                   7915: 
1.243     albertel 7916: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7917: forcing spreadsheet to reevaluate the resource scores next time.
                   7918: 
                   7919: =back
                   7920: 
                   7921: =head2 Storing/Retreiving Data
                   7922: 
                   7923: =over 4
1.191     harris41 7924: 
                   7925: =item *
                   7926: 
1.243     albertel 7927: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7928: for this url; hashref needs to be given and should be a \%hashname; the
                   7929: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7930: be derived from the env
1.191     harris41 7931: 
                   7932: =item *
                   7933: 
1.243     albertel 7934: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7935: uses critical subroutine
1.191     harris41 7936: 
                   7937: =item *
                   7938: 
1.243     albertel 7939: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7940: all args are optional
1.191     harris41 7941: 
                   7942: =item *
                   7943: 
1.717     albertel 7944: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7945: dumps the complete (or key matching regexp) namespace into a hash
                   7946: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7947: normally &store()ed into
                   7948: 
                   7949: $range should be either an integer '100' (give me the first 100
                   7950:                                            matching records)
                   7951:               or be  two integers sperated by a - with no spaces
                   7952:                  '30-50' (give me the 30th through the 50th matching
                   7953:                           records)
                   7954: 
                   7955: 
                   7956: =item *
                   7957: 
                   7958: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7959: replaces a &store() version of data with a replacement set of data
                   7960: for a particular resource in a namespace passed in the $storehash hash 
                   7961: reference
                   7962: 
                   7963: =item *
                   7964: 
1.243     albertel 7965: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7966: works very similar to store/cstore, but all data is stored in a
                   7967: temporary location and can be reset using tmpreset, $storehash should
                   7968: be a hash reference, returns nothing on success
1.191     harris41 7969: 
                   7970: =item *
                   7971: 
1.243     albertel 7972: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7973: similar to restore, but all data is stored in a temporary location and
                   7974: can be reset using tmpreset. Returns a hash of values on success,
                   7975: error string otherwise.
1.191     harris41 7976: 
                   7977: =item *
                   7978: 
1.243     albertel 7979: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7980: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7981: 
                   7982: =item *
                   7983: 
1.243     albertel 7984: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7985: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7986: 
                   7987: =item *
                   7988: 
1.243     albertel 7989: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7990: namesp ($udom and $uname are optional)
1.191     harris41 7991: 
                   7992: =item *
                   7993: 
1.702     albertel 7994: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7995: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7996: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7997: 
1.702     albertel 7998: $range should be either an integer '100' (give me the first 100
                   7999:                                            matching records)
                   8000:               or be  two integers sperated by a - with no spaces
                   8001:                  '30-50' (give me the 30th through the 50th matching
                   8002:                           records)
1.449     matthew  8003: =item *
                   8004: 
                   8005: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8006: $store can be a scalar, an array reference, or if the amount to be 
                   8007: incremented is > 1, a hash reference.
                   8008: 
                   8009: ($udom and $uname are optional)
1.191     harris41 8010: 
                   8011: =item *
                   8012: 
1.243     albertel 8013: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8014: ($udom and $uname are optional)
1.191     harris41 8015: 
                   8016: =item *
                   8017: 
1.243     albertel 8018: cput($namespace,$storehash,$udom,$uname) : critical put
                   8019: ($udom and $uname are optional)
1.191     harris41 8020: 
                   8021: =item *
                   8022: 
1.748     albertel 8023: newput($namespace,$storehash,$udom,$uname) :
                   8024: 
                   8025: Attempts to store the items in the $storehash, but only if they don't
                   8026: currently exist, if this succeeds you can be certain that you have 
                   8027: successfully created a new key value pair in the $namespace db.
                   8028: 
                   8029: 
                   8030: Args:
                   8031:  $namespace: name of database to store values to
                   8032:  $storehash: hashref to store to the db
                   8033:  $udom: (optional) domain of user containing the db
                   8034:  $uname: (optional) name of user caontaining the db
                   8035: 
                   8036: Returns:
                   8037:  'ok' -> succeeded in storing all keys of $storehash
                   8038:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8039:                         least <key> already existed in the db (other
                   8040:                         requested keys may also already exist)
                   8041:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8042:  'con_lost' -> unable to contact request server
                   8043:  'refused' -> action was not allowed by remote machine
                   8044: 
                   8045: 
                   8046: =item *
                   8047: 
1.243     albertel 8048: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8049: reference filled in from namesp (encrypts the return communication)
                   8050: ($udom and $uname are optional)
1.191     harris41 8051: 
                   8052: =item *
                   8053: 
1.243     albertel 8054: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8055: critical subroutine
                   8056: 
                   8057: =back
                   8058: 
                   8059: =head2 Network Status Functions
                   8060: 
                   8061: =over 4
1.191     harris41 8062: 
                   8063: =item *
                   8064: 
                   8065: dirlist($uri) : return directory list based on URI
                   8066: 
                   8067: =item *
                   8068: 
1.243     albertel 8069: spareserver() : find server with least workload from spare.tab
                   8070: 
                   8071: =back
                   8072: 
                   8073: =head2 Apache Request
                   8074: 
                   8075: =over 4
1.191     harris41 8076: 
                   8077: =item *
                   8078: 
1.243     albertel 8079: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8080: localhost, posts hash
                   8081: 
                   8082: =back
                   8083: 
                   8084: =head2 Data to String to Data
                   8085: 
                   8086: =over 4
1.191     harris41 8087: 
                   8088: =item *
                   8089: 
1.243     albertel 8090: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8091: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8092: 
                   8093: =item *
                   8094: 
1.243     albertel 8095: hashref2str($hashref) : convert a hashref into a string complete with
                   8096: escaping and '=' and '&' separators, supports elements that are
                   8097: arrayrefs and hashrefs
1.191     harris41 8098: 
                   8099: =item *
                   8100: 
1.243     albertel 8101: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8102: with escaping and '&' separators, supports elements that are arrayrefs
                   8103: and hashrefs
1.191     harris41 8104: 
                   8105: =item *
                   8106: 
1.243     albertel 8107: str2hash($string) : convert string to hash using unescaping and
                   8108: splitting on '=' and '&', supports elements that are arrayrefs and
                   8109: hashrefs
1.191     harris41 8110: 
                   8111: =item *
                   8112: 
1.243     albertel 8113: str2array($string) : convert string to hash using unescaping and
                   8114: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8115: 
                   8116: =back
                   8117: 
                   8118: =head2 Logging Routines
                   8119: 
                   8120: =over 4
                   8121: 
                   8122: These routines allow one to make log messages in the lonnet.log and
                   8123: lonnet.perm logfiles.
1.191     harris41 8124: 
                   8125: =item *
                   8126: 
1.243     albertel 8127: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8128: 
                   8129: =item *
                   8130: 
1.243     albertel 8131: logthis() : append message to the normal lonnet.log file, it gets
                   8132: preiodically rolled over and deleted.
1.191     harris41 8133: 
                   8134: =item *
                   8135: 
1.243     albertel 8136: logperm() : append a permanent message to lonnet.perm.log, this log
                   8137: file never gets deleted by any automated portion of the system, only
                   8138: messages of critical importance should go in here.
                   8139: 
                   8140: =back
                   8141: 
                   8142: =head2 General File Helper Routines
                   8143: 
                   8144: =over 4
1.191     harris41 8145: 
                   8146: =item *
                   8147: 
1.481     raeburn  8148: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8149: (a) files in /uploaded
                   8150:   (i) If a local copy of the file exists - 
                   8151:       compares modification date of local copy with last-modified date for 
                   8152:       definitive version stored on home server for course. If local copy is 
                   8153:       stale, requests a new version from the home server and stores it. 
                   8154:       If the original has been removed from the home server, then local copy 
                   8155:       is unlinked.
                   8156:   (ii) If local copy does not exist -
                   8157:       requests the file from the home server and stores it. 
                   8158:   
                   8159:   If $caller is 'uploadrep':  
                   8160:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8161:     for request for files originally uploaded via DOCS. 
                   8162:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8163:   
                   8164:   Otherwise:
                   8165:      This indicates a call from the content generation phase of the request.
                   8166:      -  returns the entire contents of the file or -1.
                   8167:      
                   8168: (b) files in /res
                   8169:    - returns the entire contents of a file or -1; 
                   8170:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8171: 
1.712     albertel 8172: 
                   8173: =item *
                   8174: 
                   8175: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8176:                   reference
                   8177: 
                   8178: returns either a stat() list of data about the file or an empty list
                   8179: if the file doesn't exist or couldn't find out about it (connection
                   8180: problems or user unknown)
                   8181: 
1.191     harris41 8182: =item *
                   8183: 
1.243     albertel 8184: filelocation($dir,$file) : returns file system location of a file
                   8185: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8186: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8187: and a file of ../bob will become /a/bob)
1.191     harris41 8188: 
                   8189: =item *
                   8190: 
                   8191: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8192: filelocation except for hrefs
                   8193: 
                   8194: =item *
                   8195: 
                   8196: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8197: 
1.243     albertel 8198: =back
                   8199: 
1.608     albertel 8200: =head2 Usererfile file routines (/uploaded*)
                   8201: 
                   8202: =over 4
                   8203: 
                   8204: =item *
                   8205: 
                   8206: userfileupload(): main rotine for putting a file in a user or course's
                   8207:                   filespace, arguments are,
                   8208: 
1.620     albertel 8209:  formname - required - this is the name of the element in $env where the
1.608     albertel 8210:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8211:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8212:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8213:  coursedoc - if true, store the file in the course of the active role
                   8214:              of the current user
                   8215:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8216:          if undefined, it will be placed in "unknown"
                   8217: 
                   8218:  (This routine calls clean_filename() to remove any dangerous
                   8219:  characters from the filename, and then calls finuserfileupload() to
                   8220:  complete the transaction)
                   8221: 
                   8222:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8223:  and /adm/notfound.html if unsuccessful
                   8224: 
                   8225: =item *
                   8226: 
                   8227: clean_filename(): routine for cleaing a filename up for storage in
                   8228:                  userfile space, argument is:
                   8229: 
                   8230:  filename - proposed filename
                   8231: 
                   8232: returns: the new clean filename
                   8233: 
                   8234: =item *
                   8235: 
                   8236: finishuserfileupload(): routine that creaes and sends the file to
                   8237: userspace, probably shouldn't be called directly
                   8238: 
                   8239:   docuname: username or courseid of destination for the file
                   8240:   docudom: domain of user/course of destination for the file
                   8241:   formname: same as for userfileupload()
                   8242:   fname: filename (inculding subdirectories) for the file
                   8243: 
                   8244:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8245:  and /adm/notfound.html if unsuccessful
                   8246: 
                   8247: =item *
                   8248: 
                   8249: renameuserfile(): renames an existing userfile to a new name
                   8250: 
                   8251:   Args:
                   8252:    docuname: username or courseid of destination for the file
                   8253:    docudom: domain of user/course of destination for the file
                   8254:    old: current file name (including any subdirs under userfiles)
                   8255:    new: desired file name (including any subdirs under userfiles)
                   8256: 
                   8257: =item *
                   8258: 
                   8259: mkdiruserfile(): creates a directory is a userfiles dir
                   8260: 
                   8261:   Args:
                   8262:    docuname: username or courseid of destination for the file
                   8263:    docudom: domain of user/course of destination for the file
                   8264:    dir: dir to create (including any subdirs under userfiles)
                   8265: 
                   8266: =item *
                   8267: 
                   8268: removeuserfile(): removes a file that exists in userfiles
                   8269: 
                   8270:   Args:
                   8271:    docuname: username or courseid of destination for the file
                   8272:    docudom: domain of user/course of destination for the file
                   8273:    fname: filname to delete (including any subdirs under userfiles)
                   8274: 
                   8275: =item *
                   8276: 
                   8277: removeuploadedurl(): convience function for removeuserfile()
                   8278: 
                   8279:   Args:
                   8280:    url:  a full /uploaded/... url to delete
                   8281: 
1.747     albertel 8282: =item * 
                   8283: 
                   8284: get_portfile_permissions():
                   8285:   Args:
                   8286:     domain: domain of user or course contain the portfolio files
                   8287:     user: name of user or num of course contain the portfolio files
                   8288:   Returns:
                   8289:     hashref of a dump of the proper file_permissions.db
                   8290:    
                   8291: 
                   8292: =item * 
                   8293: 
                   8294: get_access_controls():
                   8295: 
                   8296: Args:
                   8297:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8298:   group: (optional) the group you want the files associated with
                   8299:   file: (optional) the file you want access info on
                   8300: 
                   8301: Returns:
1.749     raeburn  8302:     a hash (keys are file names) of hashes containing
                   8303:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8304:         values are XML containing access control settings (see below) 
1.747     albertel 8305: 
                   8306: Internal notes:
                   8307: 
1.749     raeburn  8308:  access controls are stored in file_permissions.db as key=value pairs.
                   8309:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8310:         where scope -> public,guest,course,group,domains or users.
                   8311:               end -> UNIX time for end of access (0 -> no end date)
                   8312:               start -> UNIX time for start of access
                   8313: 
                   8314:     value -> XML description of access control
                   8315:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8316:             <start></start>
                   8317:             <end></end>
                   8318: 
                   8319:             <password></password>  for scope type = guest
                   8320: 
                   8321:             <domain></domain>     for scope type = course or group
                   8322:             <number></number>
                   8323:             <roles id="">
                   8324:              <role></role>
                   8325:              <access></access>
                   8326:              <section></section>
                   8327:              <group></group>
                   8328:             </roles>
                   8329: 
                   8330:             <dom></dom>         for scope type = domains
                   8331: 
                   8332:             <users>             for scope type = users
                   8333:              <user>
                   8334:               <uname></uname>
                   8335:               <udom></udom>
                   8336:              </user>
                   8337:             </users>
                   8338:            </scope> 
                   8339:               
                   8340:  Access data is also aggregated for each file in an additional key=value pair:
                   8341:  key -> path to file/file_name\0accesscontrol 
                   8342:  value -> reference to hash
                   8343:           hash contains key = value pairs
                   8344:           where key = uniqueID:scope_end_start
                   8345:                 value = UNIX time record was last updated
                   8346: 
                   8347:           Used to improve speed of look-ups of access controls for each file.  
                   8348:  
                   8349:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8350: 
                   8351: modify_access_controls():
                   8352: 
                   8353: Modifies access controls for a portfolio file
                   8354: Args
                   8355: 1. file name
                   8356: 2. reference to hash of required changes,
                   8357: 3. domain
                   8358: 4. username
                   8359:   where domain,username are the domain of the portfolio owner 
                   8360:   (either a user or a course) 
                   8361: 
                   8362: Returns:
                   8363: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8364: 2. result of deletions ('ok' or 'error', with error message).
                   8365: 3. reference to hash of any new or updated access controls.
                   8366: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8367:    key = integer (inbound ID)
                   8368:    value = uniqueID  
1.747     albertel 8369: 
1.608     albertel 8370: =back
                   8371: 
1.243     albertel 8372: =head2 HTTP Helper Routines
                   8373: 
                   8374: =over 4
                   8375: 
1.191     harris41 8376: =item *
                   8377: 
                   8378: escape() : unpack non-word characters into CGI-compatible hex codes
                   8379: 
                   8380: =item *
                   8381: 
                   8382: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8383: 
1.243     albertel 8384: =back
                   8385: 
                   8386: =head1 PRIVATE SUBROUTINES
                   8387: 
                   8388: =head2 Underlying communication routines (Shouldn't call)
                   8389: 
                   8390: =over 4
                   8391: 
                   8392: =item *
                   8393: 
                   8394: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8395: 
                   8396: =item *
                   8397: 
                   8398: reply() : uses subreply to send a message to remote machine, logs all failures
                   8399: 
                   8400: =item *
                   8401: 
                   8402: critical() : passes a critical message to another server; if cannot
                   8403: get through then place message in connection buffer directory and
                   8404: returns con_delayed, if incapable of saving message, returns
                   8405: con_failed
                   8406: 
                   8407: =item *
                   8408: 
                   8409: reconlonc() : tries to reconnect lonc client processes.
                   8410: 
                   8411: =back
                   8412: 
                   8413: =head2 Resource Access Logging
                   8414: 
                   8415: =over 4
                   8416: 
                   8417: =item *
                   8418: 
                   8419: flushcourselogs() : flush (save) buffer logs and access logs
                   8420: 
                   8421: =item *
                   8422: 
                   8423: courselog($what) : save message for course in hash
                   8424: 
                   8425: =item *
                   8426: 
                   8427: courseacclog($what) : save message for course using &courselog().  Perform
                   8428: special processing for specific resource types (problems, exams, quizzes, etc).
                   8429: 
1.191     harris41 8430: =item *
                   8431: 
                   8432: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8433: as a PerlChildExitHandler
1.243     albertel 8434: 
                   8435: =back
                   8436: 
                   8437: =head2 Other
                   8438: 
                   8439: =over 4
                   8440: 
                   8441: =item *
                   8442: 
                   8443: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8444: 
                   8445: =back
                   8446: 
                   8447: =cut

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